blob: ed987d50b0b93cf7e6be95b11fd1e816942d125c [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 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500114 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200115 * 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
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500346 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100347 */
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
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500406/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100407 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500408 * with sample fetch wrappers. The input arguments are given to the
409 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100410 */
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
Ilya Shipitsind4259502020-04-08 01:07:56 +0500444 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100445 */
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
Ilya Shipitsind4259502020-04-08 01:07:56 +0500496 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100497 */
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
Ilya Shipitsind4259502020-04-08 01:07:56 +0500587/* This function check the "argp" built 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 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500591 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100592 * 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
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500656 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100657 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/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500805 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100806 * 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
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500886 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100887 * 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
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500889 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100890 *
891 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500892 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100893 *
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
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500897 * protected 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;
Christopher Fauletbc275a92020-02-26 14:55:16 +0100910 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100911 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100912 lua->T = lua_newthread(gL.T);
913 if (!lua->T) {
914 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100915 if (!already_safe)
916 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100917 return 0;
918 }
919 hlua_sethlua(lua);
920 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
921 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100922 if (!already_safe)
923 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100924 return 1;
925}
926
Willy Tarreau87b09662015-04-03 00:22:06 +0200927/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100928 * is destroyed. The destroy also the memory context. The struct "lua"
929 * is not freed.
930 */
931void hlua_ctx_destroy(struct hlua *lua)
932{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100933 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100934 return;
935
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100936 if (!lua->T)
937 goto end;
938
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100939 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +0200940 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100941
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200942 if (!SET_SAFE_LJMP(lua->T))
943 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100944 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200945 RESET_SAFE_LJMP(lua->T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200946
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200947 if (!SET_SAFE_LJMP(gL.T))
948 return;
949 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
950 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200951 /* Forces a garbage collecting process. If the Lua program is finished
952 * without error, we run the GC on the thread pointer. Its freed all
953 * the unused memory.
954 * If the thread is finnish with an error or is currently yielded,
955 * it seems that the GC applied on the thread doesn't clean anything,
956 * so e run the GC on the main thread.
957 * NOTE: maybe this action locks all the Lua threads untiml the en of
958 * the garbage collection.
959 */
Willy Tarreauf31af932020-01-14 09:59:38 +0100960 if (lua->gc_count) {
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200961 if (!SET_SAFE_LJMP(gL.T))
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200962 return;
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200963 lua_gc(gL.T, LUA_GCCOLLECT, 0);
964 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200965 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200966
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200967 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100968
969end:
Willy Tarreaubafbe012017-11-24 17:34:44 +0100970 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100971}
972
973/* This function is used to restore the Lua context when a coroutine
974 * fails. This function copy the common memory between old coroutine
975 * and the new coroutine. The old coroutine is destroyed, and its
976 * replaced by the new coroutine.
977 * If the flag "keep_msg" is set, the last entry of the old is assumed
978 * as string error message and it is copied in the new stack.
979 */
980static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
981{
982 lua_State *T;
983 int new_ref;
984
985 /* Renew the main LUA stack doesn't have sense. */
986 if (lua == &gL)
987 return 0;
988
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100989 /* New Lua coroutine. */
990 T = lua_newthread(gL.T);
991 if (!T)
992 return 0;
993
994 /* Copy last error message. */
995 if (keep_msg)
996 lua_xmove(lua->T, T, 1);
997
998 /* Copy data between the coroutines. */
999 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1000 lua_xmove(lua->T, T, 1);
1001 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
1002
1003 /* Destroy old data. */
1004 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1005
1006 /* The thread is garbage collected by Lua. */
1007 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
1008
1009 /* Fill the struct with the new coroutine values. */
1010 lua->Mref = new_ref;
1011 lua->T = T;
1012 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
1013
1014 /* Set context. */
1015 hlua_sethlua(lua);
1016
1017 return 1;
1018}
1019
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001020void hlua_hook(lua_State *L, lua_Debug *ar)
1021{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001022 struct hlua *hlua = hlua_gethlua(L);
1023
1024 /* Lua cannot yield when its returning from a function,
1025 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001026 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001027 */
1028 if (lua_gethookmask(L) & LUA_MASKRET) {
1029 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1030 return;
1031 }
1032
1033 /* restore the interrupt condition. */
1034 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1035
1036 /* If we interrupt the Lua processing in yieldable state, we yield.
1037 * If the state is not yieldable, trying yield causes an error.
1038 */
1039 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001040 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001041
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001042 /* If we cannot yield, update the clock and check the timeout. */
1043 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001044 hlua->run_time += now_ms - hlua->start_time;
1045 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001046 lua_pushfstring(L, "execution timeout");
1047 WILL_LJMP(lua_error(L));
1048 }
1049
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001050 /* Update the start time. */
1051 hlua->start_time = now_ms;
1052
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001053 /* Try to interrupt the process at the end of the current
1054 * unyieldable function.
1055 */
1056 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001057}
1058
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001059/* This function start or resumes the Lua stack execution. If the flag
1060 * "yield_allowed" if no set and the LUA stack execution returns a yield
1061 * The function return an error.
1062 *
1063 * The function can returns 4 values:
1064 * - HLUA_E_OK : The execution is terminated without any errors.
1065 * - HLUA_E_AGAIN : The execution must continue at the next associated
1066 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001067 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001068 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001069 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001070 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001071 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001072 * LUA code.
1073 */
1074static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1075{
1076 int ret;
1077 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001078 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001079
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001080 /* Initialise run time counter. */
1081 if (!HLUA_IS_RUNNING(lua))
1082 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001083
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001084 /* Lock the whole Lua execution. This lock must be before the
1085 * label "resume_execution".
1086 */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001087 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001088
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001089resume_execution:
1090
1091 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1092 * instructions. it is used for preventing infinite loops.
1093 */
1094 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1095
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001096 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001097 HLUA_SET_RUN(lua);
1098 HLUA_CLR_CTRLYIELD(lua);
1099 HLUA_CLR_WAKERESWR(lua);
1100 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001101
Christopher Fauletbc275a92020-02-26 14:55:16 +01001102 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001103 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001104 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001105
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001106 /* Call the function. */
1107 ret = lua_resume(lua->T, gL.T, lua->nargs);
1108 switch (ret) {
1109
1110 case LUA_OK:
1111 ret = HLUA_E_OK;
1112 break;
1113
1114 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001115 /* Check if the execution timeout is expired. It it is the case, we
1116 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001117 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001118 tv_update_date(0, 1);
1119 lua->run_time += now_ms - lua->start_time;
1120 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001121 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001122 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001123 break;
1124 }
1125 /* Process the forced yield. if the general yield is not allowed or
1126 * if no task were associated this the current Lua execution
1127 * coroutine, we resume the execution. Else we want to return in the
1128 * scheduler and we want to be waked up again, to continue the
1129 * current Lua execution. So we schedule our own task.
1130 */
1131 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001132 if (!yield_allowed || !lua->task)
1133 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001134 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001135 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001136 if (!yield_allowed) {
1137 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001138 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001139 break;
1140 }
1141 ret = HLUA_E_AGAIN;
1142 break;
1143
1144 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001145
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001146 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001147 * because the errors ares the only one mean to return immediately
1148 * from and lua execution.
1149 */
1150 if (lua->flags & HLUA_EXIT) {
1151 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001152 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001153 break;
1154 }
1155
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001156 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001157 if (!lua_checkstack(lua->T, 1)) {
1158 ret = HLUA_E_ERR;
1159 break;
1160 }
1161 msg = lua_tostring(lua->T, -1);
1162 lua_settop(lua->T, 0); /* Empty the stack. */
1163 lua_pop(lua->T, 1);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001164 trace = hlua_traceback(lua->T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001165 if (msg)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001166 lua_pushfstring(lua->T, "runtime error: %s from %s", msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001167 else
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001168 lua_pushfstring(lua->T, "unknown runtime error from %s", trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001169 ret = HLUA_E_ERRMSG;
1170 break;
1171
1172 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001173 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001174 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001175 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001176 break;
1177
1178 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001179 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001180 if (!lua_checkstack(lua->T, 1)) {
1181 ret = HLUA_E_ERR;
1182 break;
1183 }
1184 msg = lua_tostring(lua->T, -1);
1185 lua_settop(lua->T, 0); /* Empty the stack. */
1186 lua_pop(lua->T, 1);
1187 if (msg)
1188 lua_pushfstring(lua->T, "message handler error: %s", msg);
1189 else
1190 lua_pushfstring(lua->T, "message handler error");
1191 ret = HLUA_E_ERRMSG;
1192 break;
1193
1194 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001195 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001196 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001197 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001198 break;
1199 }
1200
1201 switch (ret) {
1202 case HLUA_E_AGAIN:
1203 break;
1204
1205 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001206 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001207 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001208 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001209 break;
1210
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001211 case HLUA_E_ETMOUT:
1212 case HLUA_E_NOMEM:
1213 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001214 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001215 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001216 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001217 hlua_ctx_renew(lua, 0);
1218 break;
1219
1220 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001221 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001222 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001223 break;
1224 }
1225
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001226 /* This is the main exit point, remove the Lua lock. */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001227 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001228
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001229 return ret;
1230}
1231
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001232/* This function exit the current code. */
1233__LJMP static int hlua_done(lua_State *L)
1234{
1235 struct hlua *hlua = hlua_gethlua(L);
1236
1237 hlua->flags |= HLUA_EXIT;
1238 WILL_LJMP(lua_error(L));
1239
1240 return 0;
1241}
1242
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001243/* This function is an LUA binding. It provides a function
1244 * for deleting ACL from a referenced ACL file.
1245 */
1246__LJMP static int hlua_del_acl(lua_State *L)
1247{
1248 const char *name;
1249 const char *key;
1250 struct pat_ref *ref;
1251
1252 MAY_LJMP(check_args(L, 2, "del_acl"));
1253
1254 name = MAY_LJMP(luaL_checkstring(L, 1));
1255 key = MAY_LJMP(luaL_checkstring(L, 2));
1256
1257 ref = pat_ref_lookup(name);
1258 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001259 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001260
1261 pat_ref_delete(ref, key);
1262 return 0;
1263}
1264
1265/* This function is an LUA binding. It provides a function
1266 * for deleting map entry from a referenced map file.
1267 */
1268static int hlua_del_map(lua_State *L)
1269{
1270 const char *name;
1271 const char *key;
1272 struct pat_ref *ref;
1273
1274 MAY_LJMP(check_args(L, 2, "del_map"));
1275
1276 name = MAY_LJMP(luaL_checkstring(L, 1));
1277 key = MAY_LJMP(luaL_checkstring(L, 2));
1278
1279 ref = pat_ref_lookup(name);
1280 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001281 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001282
1283 pat_ref_delete(ref, key);
1284 return 0;
1285}
1286
1287/* This function is an LUA binding. It provides a function
1288 * for adding ACL pattern from a referenced ACL file.
1289 */
1290static int hlua_add_acl(lua_State *L)
1291{
1292 const char *name;
1293 const char *key;
1294 struct pat_ref *ref;
1295
1296 MAY_LJMP(check_args(L, 2, "add_acl"));
1297
1298 name = MAY_LJMP(luaL_checkstring(L, 1));
1299 key = MAY_LJMP(luaL_checkstring(L, 2));
1300
1301 ref = pat_ref_lookup(name);
1302 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001303 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001304
1305 if (pat_ref_find_elt(ref, key) == NULL)
1306 pat_ref_add(ref, key, NULL, NULL);
1307 return 0;
1308}
1309
1310/* This function is an LUA binding. It provides a function
1311 * for setting map pattern and sample from a referenced map
1312 * file.
1313 */
1314static int hlua_set_map(lua_State *L)
1315{
1316 const char *name;
1317 const char *key;
1318 const char *value;
1319 struct pat_ref *ref;
1320
1321 MAY_LJMP(check_args(L, 3, "set_map"));
1322
1323 name = MAY_LJMP(luaL_checkstring(L, 1));
1324 key = MAY_LJMP(luaL_checkstring(L, 2));
1325 value = MAY_LJMP(luaL_checkstring(L, 3));
1326
1327 ref = pat_ref_lookup(name);
1328 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001329 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001330
1331 if (pat_ref_find_elt(ref, key) != NULL)
1332 pat_ref_set(ref, key, value, NULL);
1333 else
1334 pat_ref_add(ref, key, value, NULL);
1335 return 0;
1336}
1337
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001338/* A class is a lot of memory that contain data. This data can be a table,
1339 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001340 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001341 * the name of the object (_G[<name>] = <metable> ).
1342 *
1343 * A metable is a table that modify the standard behavior of a standard
1344 * access to the associated data. The entries of this new metatable are
1345 * defined as is:
1346 *
1347 * http://lua-users.org/wiki/MetatableEvents
1348 *
1349 * __index
1350 *
1351 * we access an absent field in a table, the result is nil. This is
1352 * true, but it is not the whole truth. Actually, such access triggers
1353 * the interpreter to look for an __index metamethod: If there is no
1354 * such method, as usually happens, then the access results in nil;
1355 * otherwise, the metamethod will provide the result.
1356 *
1357 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1358 * the key does not appear in the table, but the metatable has an __index
1359 * property:
1360 *
1361 * - if the value is a function, the function is called, passing in the
1362 * table and the key; the return value of that function is returned as
1363 * the result.
1364 *
1365 * - if the value is another table, the value of the key in that table is
1366 * asked for and returned (and if it doesn't exist in that table, but that
1367 * table's metatable has an __index property, then it continues on up)
1368 *
1369 * - Use "rawget(myTable,key)" to skip this metamethod.
1370 *
1371 * http://www.lua.org/pil/13.4.1.html
1372 *
1373 * __newindex
1374 *
1375 * Like __index, but control property assignment.
1376 *
1377 * __mode - Control weak references. A string value with one or both
1378 * of the characters 'k' and 'v' which specifies that the the
1379 * keys and/or values in the table are weak references.
1380 *
1381 * __call - Treat a table like a function. When a table is followed by
1382 * parenthesis such as "myTable( 'foo' )" and the metatable has
1383 * a __call key pointing to a function, that function is invoked
1384 * (passing any specified arguments) and the return value is
1385 * returned.
1386 *
1387 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1388 * called, if the metatable for myTable has a __metatable
1389 * key, the value of that key is returned instead of the
1390 * actual metatable.
1391 *
1392 * __tostring - Control string representation. When the builtin
1393 * "tostring( myTable )" function is called, if the metatable
1394 * for myTable has a __tostring property set to a function,
1395 * that function is invoked (passing myTable to it) and the
1396 * return value is used as the string representation.
1397 *
1398 * __len - Control table length. When the table length is requested using
1399 * the length operator ( '#' ), if the metatable for myTable has
1400 * a __len key pointing to a function, that function is invoked
1401 * (passing myTable to it) and the return value used as the value
1402 * of "#myTable".
1403 *
1404 * __gc - Userdata finalizer code. When userdata is set to be garbage
1405 * collected, if the metatable has a __gc field pointing to a
1406 * function, that function is first invoked, passing the userdata
1407 * to it. The __gc metamethod is not called for tables.
1408 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1409 *
1410 * Special metamethods for redefining standard operators:
1411 * http://www.lua.org/pil/13.1.html
1412 *
1413 * __add "+"
1414 * __sub "-"
1415 * __mul "*"
1416 * __div "/"
1417 * __unm "!"
1418 * __pow "^"
1419 * __concat ".."
1420 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001421 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001422 * http://www.lua.org/pil/13.2.html
1423 *
1424 * __eq "=="
1425 * __lt "<"
1426 * __le "<="
1427 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001428
1429/*
1430 *
1431 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001432 * Class Map
1433 *
1434 *
1435 */
1436
1437/* Returns a struct hlua_map if the stack entry "ud" is
1438 * a class session, otherwise it throws an error.
1439 */
1440__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1441{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001442 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001443}
1444
1445/* This function is the map constructor. It don't need
1446 * the class Map object. It creates and return a new Map
1447 * object. It must be called only during "body" or "init"
1448 * context because it process some filesystem accesses.
1449 */
1450__LJMP static int hlua_map_new(struct lua_State *L)
1451{
1452 const char *fn;
1453 int match = PAT_MATCH_STR;
1454 struct sample_conv conv;
1455 const char *file = "";
1456 int line = 0;
1457 lua_Debug ar;
1458 char *err = NULL;
1459 struct arg args[2];
1460
1461 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1462 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1463
1464 fn = MAY_LJMP(luaL_checkstring(L, 1));
1465
1466 if (lua_gettop(L) >= 2) {
1467 match = MAY_LJMP(luaL_checkinteger(L, 2));
1468 if (match < 0 || match >= PAT_MATCH_NUM)
1469 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1470 }
1471
1472 /* Get Lua filename and line number. */
1473 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1474 lua_getinfo(L, "Sl", &ar); /* get info about it */
1475 if (ar.currentline > 0) { /* is there info? */
1476 file = ar.short_src;
1477 line = ar.currentline;
1478 }
1479 }
1480
1481 /* fill fake sample_conv struct. */
1482 conv.kw = ""; /* unused. */
1483 conv.process = NULL; /* unused. */
1484 conv.arg_mask = 0; /* unused. */
1485 conv.val_args = NULL; /* unused. */
1486 conv.out_type = SMP_T_STR;
1487 conv.private = (void *)(long)match;
1488 switch (match) {
1489 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1490 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1491 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1492 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1493 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1494 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1495 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001496 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001497 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1498 default:
1499 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1500 }
1501
1502 /* fill fake args. */
1503 args[0].type = ARGT_STR;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001504 args[0].data.str.area = (char *)fn;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001505 args[1].type = ARGT_STOP;
1506
1507 /* load the map. */
1508 if (!sample_load_map(args, &conv, file, line, &err)) {
1509 /* error case: we cant use luaL_error because we must
1510 * free the err variable.
1511 */
1512 luaL_where(L, 1);
1513 lua_pushfstring(L, "'new': %s.", err);
1514 lua_concat(L, 2);
1515 free(err);
1516 WILL_LJMP(lua_error(L));
1517 }
1518
1519 /* create the lua object. */
1520 lua_newtable(L);
1521 lua_pushlightuserdata(L, args[0].data.map);
1522 lua_rawseti(L, -2, 0);
1523
1524 /* Pop a class Map metatable and affect it to the userdata. */
1525 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1526 lua_setmetatable(L, -2);
1527
1528
1529 return 1;
1530}
1531
1532__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1533{
1534 struct map_descriptor *desc;
1535 struct pattern *pat;
1536 struct sample smp;
1537
1538 MAY_LJMP(check_args(L, 2, "lookup"));
1539 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001540 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001541 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001542 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001543 }
1544 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001545 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001546 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001547 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 +02001548 }
1549
1550 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001551 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001552 if (str)
1553 lua_pushstring(L, "");
1554 else
1555 lua_pushnil(L);
1556 return 1;
1557 }
1558
1559 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001560 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001561 return 1;
1562}
1563
1564__LJMP static int hlua_map_lookup(struct lua_State *L)
1565{
1566 return _hlua_map_lookup(L, 0);
1567}
1568
1569__LJMP static int hlua_map_slookup(struct lua_State *L)
1570{
1571 return _hlua_map_lookup(L, 1);
1572}
1573
1574/*
1575 *
1576 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001577 * Class Socket
1578 *
1579 *
1580 */
1581
1582__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1583{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001584 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001585}
1586
1587/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001588 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001589 * received.
1590 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001591static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001592{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001593 struct stream_interface *si = appctx->owner;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001594
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001595 if (appctx->ctx.hlua_cosocket.die) {
1596 si_shutw(si);
1597 si_shutr(si);
1598 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001599 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1600 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001601 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1602 }
1603
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001604 /* If we cant write, wakeup the pending write signals. */
1605 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001606 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001607
1608 /* If we cant read, wakeup the pending read signals. */
1609 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001610 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001611
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001612 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001613 * to be notified whenever the connection completes.
1614 */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001615 if (si_opposite(si)->state < SI_ST_EST) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01001616 si_cant_get(si);
Willy Tarreau12c24232018-12-06 15:29:50 +01001617 si_rx_conn_blk(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01001618 si_rx_endp_more(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001619 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001620 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001621
1622 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001623 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001624
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001625 /* Wake the tasks which wants to write if the buffer have available space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001626 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001627 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001628
1629 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001630 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001631 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001632
1633 /* Some data were injected in the buffer, notify the stream
1634 * interface.
1635 */
1636 if (!channel_is_empty(si_ic(si)))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001637 si_update(si);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001638
1639 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01001640 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001641 */
1642 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
Willy Tarreau3367d412018-11-15 10:57:41 +01001643 si_rx_endp_more(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001644}
1645
Willy Tarreau87b09662015-04-03 00:22:06 +02001646/* This function is called when the "struct stream" is destroyed.
1647 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001648 * Wake all the pending signals.
1649 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001650static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001651{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001652 struct xref *peer;
1653
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001654 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001655 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1656 if (peer)
1657 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001658
1659 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001660 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1661 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001662}
1663
1664/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001665 * uses this object. If the stream does not exists, just quit.
1666 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001667 * pending signal can rest in the read and write lists. destroy
1668 * it.
1669 */
1670__LJMP static int hlua_socket_gc(lua_State *L)
1671{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001672 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001673 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001674 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001675
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001676 MAY_LJMP(check_args(L, 1, "__gc"));
1677
1678 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001679 peer = xref_get_peer_and_lock(&socket->xref);
1680 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001681 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001682 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001683
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001684 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001685 appctx->ctx.hlua_cosocket.die = 1;
1686 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001687
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001688 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001689 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001690 return 0;
1691}
1692
1693/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001694 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001695 */
sada05ed3302018-05-11 11:48:18 -07001696__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001697{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001698 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001699 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001700 struct xref *peer;
Willy Tarreauf31af932020-01-14 09:59:38 +01001701 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001702
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001703 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001704
1705 /* Check if we run on the same thread than the xreator thread.
1706 * We cannot access to the socket if the thread is different.
1707 */
1708 if (socket->tid != tid)
1709 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1710
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001711 peer = xref_get_peer_and_lock(&socket->xref);
1712 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001713 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001714
1715 hlua->gc_count--;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001716 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001717
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001718 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001719 appctx->ctx.hlua_cosocket.die = 1;
1720 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001721
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001722 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001723 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001724 return 0;
1725}
1726
sada05ed3302018-05-11 11:48:18 -07001727/* The close function calls close_helper.
1728 */
1729__LJMP static int hlua_socket_close(lua_State *L)
1730{
1731 MAY_LJMP(check_args(L, 1, "close"));
1732 return hlua_socket_close_helper(L);
1733}
1734
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001735/* This Lua function assumes that the stack contain three parameters.
1736 * 1 - USERDATA containing a struct socket
1737 * 2 - INTEGER with values of the macro defined below
1738 * If the integer is -1, we must read at most one line.
1739 * If the integer is -2, we ust read all the data until the
1740 * end of the stream.
1741 * If the integer is positive value, we must read a number of
1742 * bytes corresponding to this value.
1743 */
1744#define HLSR_READ_LINE (-1)
1745#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001746__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001747{
1748 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1749 int wanted = lua_tointeger(L, 2);
1750 struct hlua *hlua = hlua_gethlua(L);
1751 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001752 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001753 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02001754 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001755 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02001756 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001757 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001758 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001759 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001760 struct stream_interface *si;
1761 struct stream *s;
1762 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001763 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001764
1765 /* Check if this lua stack is schedulable. */
1766 if (!hlua || !hlua->task)
1767 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1768 "'frontend', 'backend' or 'task'"));
1769
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001770 /* Check if we run on the same thread than the xreator thread.
1771 * We cannot access to the socket if the thread is different.
1772 */
1773 if (socket->tid != tid)
1774 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1775
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001776 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001777 peer = xref_get_peer_and_lock(&socket->xref);
1778 if (!peer)
1779 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001780 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1781 si = appctx->owner;
1782 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001783
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001784 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001785 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001786 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001787 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001788 if (nblk < 0) /* Connection close. */
1789 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001790 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001791 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001792
1793 /* remove final \r\n. */
1794 if (nblk == 1) {
1795 if (blk1[len1-1] == '\n') {
1796 len1--;
1797 skip_at_end++;
1798 if (blk1[len1-1] == '\r') {
1799 len1--;
1800 skip_at_end++;
1801 }
1802 }
1803 }
1804 else {
1805 if (blk2[len2-1] == '\n') {
1806 len2--;
1807 skip_at_end++;
1808 if (blk2[len2-1] == '\r') {
1809 len2--;
1810 skip_at_end++;
1811 }
1812 }
1813 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001814 }
1815
1816 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001817 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001818 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001819 if (nblk < 0) /* Connection close. */
1820 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001821 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001822 goto connection_empty;
1823 }
1824
1825 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001826 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001827 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001828 if (nblk < 0) /* Connection close. */
1829 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001830 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001831 goto connection_empty;
1832
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001833 missing_bytes = wanted - socket->b.n;
1834 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001835 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001836 len1 = missing_bytes;
1837 } if (nblk == 2 && len1 + len2 > missing_bytes)
1838 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001839 }
1840
1841 len = len1;
1842
1843 luaL_addlstring(&socket->b, blk1, len1);
1844 if (nblk == 2) {
1845 len += len2;
1846 luaL_addlstring(&socket->b, blk2, len2);
1847 }
1848
1849 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001850 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001851
1852 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02001853 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001854
1855 /* If the pattern reclaim to read all the data
1856 * in the connection, got out.
1857 */
1858 if (wanted == HLSR_READ_ALL)
1859 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001860 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001861 goto connection_empty;
1862
1863 /* Return result. */
1864 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001865 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001866 return 1;
1867
1868connection_closed:
1869
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001870 xref_unlock(&socket->xref, peer);
1871
1872no_peer:
1873
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001874 /* If the buffer containds data. */
1875 if (socket->b.n > 0) {
1876 luaL_pushresult(&socket->b);
1877 return 1;
1878 }
1879 lua_pushnil(L);
1880 lua_pushstring(L, "connection closed.");
1881 return 2;
1882
1883connection_empty:
1884
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001885 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
1886 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001887 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001888 }
1889 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02001890 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001891 return 0;
1892}
1893
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001894/* This Lua function gets two parameters. The first one can be string
1895 * or a number. If the string is "*l", the user requires one line. If
1896 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001897 * If the value is a number, the user require a number of bytes equal
1898 * to the value. The default value is "*l" (a line).
1899 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001900 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001901 * integer takes this values:
1902 * -1 : read a line
1903 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001904 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001905 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001906 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001907 * concatenated with the read data.
1908 */
1909__LJMP static int hlua_socket_receive(struct lua_State *L)
1910{
1911 int wanted = HLSR_READ_LINE;
1912 const char *pattern;
1913 int type;
1914 char *error;
1915 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001916 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001917
1918 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1919 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1920
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001921 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001922
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001923 /* Check if we run on the same thread than the xreator thread.
1924 * We cannot access to the socket if the thread is different.
1925 */
1926 if (socket->tid != tid)
1927 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1928
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001929 /* check for pattern. */
1930 if (lua_gettop(L) >= 2) {
1931 type = lua_type(L, 2);
1932 if (type == LUA_TSTRING) {
1933 pattern = lua_tostring(L, 2);
1934 if (strcmp(pattern, "*a") == 0)
1935 wanted = HLSR_READ_ALL;
1936 else if (strcmp(pattern, "*l") == 0)
1937 wanted = HLSR_READ_LINE;
1938 else {
1939 wanted = strtoll(pattern, &error, 10);
1940 if (*error != '\0')
1941 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1942 }
1943 }
1944 else if (type == LUA_TNUMBER) {
1945 wanted = lua_tointeger(L, 2);
1946 if (wanted < 0)
1947 WILL_LJMP(luaL_error(L, "Unsupported size."));
1948 }
1949 }
1950
1951 /* Set pattern. */
1952 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01001953
1954 /* Check if we would replace the top by itself. */
1955 if (lua_gettop(L) != 2)
1956 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001957
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001958 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001959 luaL_buffinit(L, &socket->b);
1960
1961 /* Check prefix. */
1962 if (lua_gettop(L) >= 3) {
1963 if (lua_type(L, 3) != LUA_TSTRING)
1964 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1965 pattern = lua_tolstring(L, 3, &len);
1966 luaL_addlstring(&socket->b, pattern, len);
1967 }
1968
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001969 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001970}
1971
1972/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08001973 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001974 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001975static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001976{
1977 struct hlua_socket *socket;
1978 struct hlua *hlua = hlua_gethlua(L);
1979 struct appctx *appctx;
1980 size_t buf_len;
1981 const char *buf;
1982 int len;
1983 int send_len;
1984 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001985 struct xref *peer;
1986 struct stream_interface *si;
1987 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001988
1989 /* Check if this lua stack is schedulable. */
1990 if (!hlua || !hlua->task)
1991 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1992 "'frontend', 'backend' or 'task'"));
1993
1994 /* Get object */
1995 socket = MAY_LJMP(hlua_checksocket(L, 1));
1996 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001997 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001998
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001999 /* Check if we run on the same thread than the xreator thread.
2000 * We cannot access to the socket if the thread is different.
2001 */
2002 if (socket->tid != tid)
2003 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2004
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002005 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002006 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002007 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002008 lua_pushinteger(L, -1);
2009 return 1;
2010 }
2011 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2012 si = appctx->owner;
2013 s = si_strm(si);
2014
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002015 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002016 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002017 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002018 lua_pushinteger(L, -1);
2019 return 1;
2020 }
2021
2022 /* Update the input buffer data. */
2023 buf += sent;
2024 send_len = buf_len - sent;
2025
2026 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002027 if (sent >= buf_len) {
2028 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002029 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002030 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002031
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002032 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002033 * the request buffer if its not required.
2034 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002035 if (s->req.buf.size == 0) {
Willy Tarreau581abd32018-10-25 10:21:41 +02002036 if (!si_alloc_ibuf(si, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002037 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002038 }
2039
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002040 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002041 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002042 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002043 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002044 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002045
2046 /* send data */
2047 if (len < send_len)
2048 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002049 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002050
2051 /* "Not enough space" (-1), "Buffer too little to contain
2052 * the data" (-2) are not expected because the available length
2053 * is tested.
2054 * Other unknown error are also not expected.
2055 */
2056 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002057 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002058 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002059
sada05ed3302018-05-11 11:48:18 -07002060 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002061 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002062 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002063 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002064 return 1;
2065 }
2066
2067 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002068 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002069
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002070 s->req.rex = TICK_ETERNITY;
2071 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002072
2073 /* Update length sent. */
2074 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002075 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002076
2077 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002078 if (sent + len >= buf_len) {
2079 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002080 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002081 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002082
2083hlua_socket_write_yield_return:
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002084 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2085 xref_unlock(&socket->xref, peer);
2086 WILL_LJMP(luaL_error(L, "out of memory"));
2087 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002088 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002089 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002090 return 0;
2091}
2092
2093/* This function initiate the send of data. It just check the input
2094 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002095 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002096 * "hlua_socket_write_yield" that can yield.
2097 *
2098 * The Lua function gets between 3 and 4 parameters. The first one is
2099 * the associated object. The second is a string buffer. The third is
2100 * a facultative integer that represents where is the buffer position
2101 * of the start of the data that can send. The first byte is the
2102 * position "1". The default value is "1". The fourth argument is a
2103 * facultative integer that represents where is the buffer position
2104 * of the end of the data that can send. The default is the last byte.
2105 */
2106static int hlua_socket_send(struct lua_State *L)
2107{
2108 int i;
2109 int j;
2110 const char *buf;
2111 size_t buf_len;
2112
2113 /* Check number of arguments. */
2114 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2115 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2116
2117 /* Get the string. */
2118 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2119
2120 /* Get and check j. */
2121 if (lua_gettop(L) == 4) {
2122 j = MAY_LJMP(luaL_checkinteger(L, 4));
2123 if (j < 0)
2124 j = buf_len + j + 1;
2125 if (j > buf_len)
2126 j = buf_len + 1;
2127 lua_pop(L, 1);
2128 }
2129 else
2130 j = buf_len;
2131
2132 /* Get and check i. */
2133 if (lua_gettop(L) == 3) {
2134 i = MAY_LJMP(luaL_checkinteger(L, 3));
2135 if (i < 0)
2136 i = buf_len + i + 1;
2137 if (i > buf_len)
2138 i = buf_len + 1;
2139 lua_pop(L, 1);
2140 } else
2141 i = 1;
2142
2143 /* Check bth i and j. */
2144 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002145 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002146 return 1;
2147 }
2148 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002149 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002150 return 1;
2151 }
2152 if (i == 0)
2153 i = 1;
2154 if (j == 0)
2155 j = 1;
2156
2157 /* Pop the string. */
2158 lua_pop(L, 1);
2159
2160 /* Update the buffer length. */
2161 buf += i - 1;
2162 buf_len = j - i + 1;
2163 lua_pushlstring(L, buf, buf_len);
2164
2165 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002166 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002167
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002168 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002169}
2170
Willy Tarreau22b0a682015-06-17 19:43:49 +02002171#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002172__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2173{
2174 static char buffer[SOCKET_INFO_MAX_LEN];
2175 int ret;
2176 int len;
2177 char *p;
2178
2179 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2180 if (ret <= 0) {
2181 lua_pushnil(L);
2182 return 1;
2183 }
2184
2185 if (ret == AF_UNIX) {
2186 lua_pushstring(L, buffer+1);
2187 return 1;
2188 }
2189 else if (ret == AF_INET6) {
2190 buffer[0] = '[';
2191 len = strlen(buffer);
2192 buffer[len] = ']';
2193 len++;
2194 buffer[len] = ':';
2195 len++;
2196 p = buffer;
2197 }
2198 else if (ret == AF_INET) {
2199 p = buffer + 1;
2200 len = strlen(p);
2201 p[len] = ':';
2202 len++;
2203 }
2204 else {
2205 lua_pushnil(L);
2206 return 1;
2207 }
2208
2209 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2210 lua_pushnil(L);
2211 return 1;
2212 }
2213
2214 lua_pushstring(L, p);
2215 return 1;
2216}
2217
2218/* Returns information about the peer of the connection. */
2219__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2220{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002221 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002222 struct xref *peer;
2223 struct appctx *appctx;
2224 struct stream_interface *si;
2225 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002226 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002227
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002228 MAY_LJMP(check_args(L, 1, "getpeername"));
2229
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002230 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002231
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002232 /* Check if we run on the same thread than the xreator thread.
2233 * We cannot access to the socket if the thread is different.
2234 */
2235 if (socket->tid != tid)
2236 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2237
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002238 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002239 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002240 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002241 lua_pushnil(L);
2242 return 1;
2243 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002244 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2245 si = appctx->owner;
2246 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002247
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002248 if (!s->target_addr) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002249 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002250 lua_pushnil(L);
2251 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002252 }
2253
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002254 ret = MAY_LJMP(hlua_socket_info(L, s->target_addr));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002255 xref_unlock(&socket->xref, peer);
2256 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002257}
2258
2259/* Returns information about my connection side. */
2260static int hlua_socket_getsockname(struct lua_State *L)
2261{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002262 struct hlua_socket *socket;
2263 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002264 struct appctx *appctx;
2265 struct xref *peer;
2266 struct stream_interface *si;
2267 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002268 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002269
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002270 MAY_LJMP(check_args(L, 1, "getsockname"));
2271
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002272 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002273
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002274 /* Check if we run on the same thread than the xreator thread.
2275 * We cannot access to the socket if the thread is different.
2276 */
2277 if (socket->tid != tid)
2278 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2279
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002280 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002281 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002282 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002283 lua_pushnil(L);
2284 return 1;
2285 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002286 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2287 si = appctx->owner;
2288 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002289
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002290 conn = cs_conn(objt_cs(s->si[1].end));
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002291 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002292 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002293 lua_pushnil(L);
2294 return 1;
2295 }
2296
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002297 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002298 xref_unlock(&socket->xref, peer);
2299 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002300}
2301
2302/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002303static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002304 .obj_type = OBJ_TYPE_APPLET,
2305 .name = "<LUA_TCP>",
2306 .fct = hlua_socket_handler,
2307 .release = hlua_socket_release,
2308};
2309
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002310__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002311{
2312 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2313 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002314 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002315 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002316 struct stream_interface *si;
2317 struct stream *s;
2318
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002319 /* Check if we run on the same thread than the xreator thread.
2320 * We cannot access to the socket if the thread is different.
2321 */
2322 if (socket->tid != tid)
2323 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2324
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002325 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002326 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002327 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002328 lua_pushnil(L);
2329 lua_pushstring(L, "Can't connect");
2330 return 2;
2331 }
2332 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2333 si = appctx->owner;
2334 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002335
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002336 /* Check if we run on the same thread than the xreator thread.
2337 * We cannot access to the socket if the thread is different.
2338 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002339 if (socket->tid != tid) {
2340 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002341 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002342 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002343
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002344 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002345 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002346 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002347 lua_pushnil(L);
2348 lua_pushstring(L, "Can't connect");
2349 return 2;
2350 }
2351
Willy Tarreaue09101e2018-10-16 17:37:12 +02002352 appctx = __objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002353
2354 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002355 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002356 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002357 lua_pushinteger(L, 1);
2358 return 1;
2359 }
2360
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002361 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2362 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002363 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002364 }
2365 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002366 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002367 return 0;
2368}
2369
2370/* This function fail or initite the connection. */
2371__LJMP static int hlua_socket_connect(struct lua_State *L)
2372{
2373 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002374 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002375 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002376 struct hlua *hlua;
2377 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002378 int low, high;
2379 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002380 struct xref *peer;
2381 struct stream_interface *si;
2382 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002383
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002384 if (lua_gettop(L) < 2)
2385 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002386
2387 /* Get args. */
2388 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002389
2390 /* Check if we run on the same thread than the xreator thread.
2391 * We cannot access to the socket if the thread is different.
2392 */
2393 if (socket->tid != tid)
2394 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2395
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002396 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002397 if (lua_gettop(L) >= 3) {
2398 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002399 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002400
Tim Duesterhus6edab862018-01-06 19:04:45 +01002401 /* Force the ip to end with a colon, to support IPv6 addresses
2402 * that are not enclosed within square brackets.
2403 */
2404 if (port > 0) {
2405 luaL_buffinit(L, &b);
2406 luaL_addstring(&b, ip);
2407 luaL_addchar(&b, ':');
2408 luaL_pushresult(&b);
2409 ip = lua_tolstring(L, lua_gettop(L), NULL);
2410 }
2411 }
2412
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002413 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002414 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002415 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002416 lua_pushnil(L);
2417 return 1;
2418 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002419
2420 /* Parse ip address. */
Willy Tarreau48ef4c92017-01-06 18:32:38 +01002421 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, 0);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002422 if (!addr) {
2423 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002424 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002425 }
2426 if (low != high) {
2427 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002428 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002429 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002430
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002431 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002432 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002433 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002434 if (port == -1) {
2435 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002436 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002437 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002438 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2439 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002440 if (port == -1) {
2441 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002442 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002443 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002444 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002445 }
2446 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002447
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002448 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2449 si = appctx->owner;
2450 s = si_strm(si);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002451
2452 if (!sockaddr_alloc(&s->target_addr)) {
2453 xref_unlock(&socket->xref, peer);
2454 WILL_LJMP(luaL_error(L, "connect: internal error"));
2455 }
2456 *s->target_addr = *addr;
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002457 s->flags |= SF_ADDR_SET;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002458
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002459 hlua = hlua_gethlua(L);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002460
2461 /* inform the stream that we want to be notified whenever the
2462 * connection completes.
2463 */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01002464 si_cant_get(&s->si[0]);
Willy Tarreau3367d412018-11-15 10:57:41 +01002465 si_rx_endp_more(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002466 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002467
Willy Tarreauf31af932020-01-14 09:59:38 +01002468 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002469
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002470 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2471 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002472 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002473 }
2474 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002475
2476 task_wakeup(s->task, TASK_WOKEN_INIT);
2477 /* Return yield waiting for connection. */
2478
Willy Tarreau9635e032018-10-16 17:52:55 +02002479 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002480
2481 return 0;
2482}
2483
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002484#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002485__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2486{
2487 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002488 struct xref *peer;
2489 struct appctx *appctx;
2490 struct stream_interface *si;
2491 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002492
2493 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2494 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002495
2496 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002497 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002498 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002499 lua_pushnil(L);
2500 return 1;
2501 }
2502 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2503 si = appctx->owner;
2504 s = si_strm(si);
2505
2506 s->target = &socket_ssl.obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002507 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002508 return MAY_LJMP(hlua_socket_connect(L));
2509}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002510#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002511
2512__LJMP static int hlua_socket_setoption(struct lua_State *L)
2513{
2514 return 0;
2515}
2516
2517__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2518{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002519 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002520 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002521 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002522 struct xref *peer;
2523 struct appctx *appctx;
2524 struct stream_interface *si;
2525 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002526
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002527 MAY_LJMP(check_args(L, 2, "settimeout"));
2528
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002529 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002530
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002531 /* convert the timeout to millis */
2532 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002533
Thierry Fournier17a921b2018-03-08 09:59:02 +01002534 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002535 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002536 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2537
Mark Lakes56cc1252018-03-27 09:48:06 +02002538 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002539 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002540
2541 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002542 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002543 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002544
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002545 /* Check if we run on the same thread than the xreator thread.
2546 * We cannot access to the socket if the thread is different.
2547 */
2548 if (socket->tid != tid)
2549 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2550
Mark Lakes56cc1252018-03-27 09:48:06 +02002551 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002552 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002553 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002554 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2555 WILL_LJMP(lua_error(L));
2556 return 0;
2557 }
2558 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2559 si = appctx->owner;
2560 s = si_strm(si);
2561
Cyril Bonté7bb63452018-08-17 23:51:02 +02002562 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002563 s->req.rto = tmout;
2564 s->req.wto = tmout;
2565 s->res.rto = tmout;
2566 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002567 s->req.rex = tick_add_ifset(now_ms, tmout);
2568 s->req.wex = tick_add_ifset(now_ms, tmout);
2569 s->res.rex = tick_add_ifset(now_ms, tmout);
2570 s->res.wex = tick_add_ifset(now_ms, tmout);
2571
2572 s->task->expire = tick_add_ifset(now_ms, tmout);
2573 task_queue(s->task);
2574
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002575 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002576
Thierry Fourniere9636f12018-03-08 09:54:32 +01002577 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002578 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002579}
2580
2581__LJMP static int hlua_socket_new(lua_State *L)
2582{
2583 struct hlua_socket *socket;
2584 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002585 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002586 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002587
2588 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002589 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002590 hlua_pusherror(L, "socket: full stack");
2591 goto out_fail_conf;
2592 }
2593
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002594 /* Create the object: obj[0] = userdata. */
2595 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002596 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002597 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002598 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002599 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002600
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002601 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002602 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002603 hlua_pusherror(L, "socket: uninitialized pools.");
2604 goto out_fail_conf;
2605 }
2606
Willy Tarreau87b09662015-04-03 00:22:06 +02002607 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002608 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2609 lua_setmetatable(L, -2);
2610
Willy Tarreaud420a972015-04-06 00:39:18 +02002611 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002612 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002613 if (!appctx) {
2614 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002615 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002616 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002617
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002618 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002619 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002620 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2621 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002622
Willy Tarreaud420a972015-04-06 00:39:18 +02002623 /* Now create a session, task and stream for this applet */
2624 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2625 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002626 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002627 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002628 }
2629
Willy Tarreau87787ac2017-08-28 16:22:54 +02002630 strm = stream_new(sess, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002631 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002632 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002633 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002634 }
2635
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002636 /* Initialise cross reference between stream and Lua socket object. */
2637 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002638
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002639 /* Configure "right" stream interface. this "si" is used to connect
2640 * and retrieve data from the server. The connection is initialized
2641 * with the "struct server".
2642 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002643 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002644
2645 /* Force destination server. */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002646 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002647 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002648
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002649 return 1;
2650
Willy Tarreaud420a972015-04-06 00:39:18 +02002651 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002652 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002653 out_fail_sess:
2654 appctx_free(appctx);
2655 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002656 WILL_LJMP(lua_error(L));
2657 return 0;
2658}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002659
2660/*
2661 *
2662 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002663 * Class Channel
2664 *
2665 *
2666 */
2667
2668/* Returns the struct hlua_channel join to the class channel in the
2669 * stack entry "ud" or throws an argument error.
2670 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002671__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002672{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002673 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002674}
2675
Willy Tarreau47860ed2015-03-10 14:07:50 +01002676/* Pushes the channel onto the top of the stack. If the stask does not have a
2677 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002678 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002679static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002680{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002681 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002682 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002683 return 0;
2684
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002685 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002686 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002687 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002688
2689 /* Pop a class sesison metatable and affect it to the userdata. */
2690 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2691 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002692 return 1;
2693}
2694
2695/* Duplicate all the data present in the input channel and put it
2696 * in a string LUA variables. Returns -1 and push a nil value in
2697 * the stack if the channel is closed and all the data are consumed,
2698 * returns 0 if no data are available, otherwise it returns the length
Ilya Shipitsind4259502020-04-08 01:07:56 +05002699 * of the built string.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002700 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002701static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002702{
2703 char *blk1;
2704 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002705 size_t len1;
2706 size_t len2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002707 int ret;
2708 luaL_Buffer b;
2709
Willy Tarreau06d80a92017-10-19 14:32:15 +02002710 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002711 if (unlikely(ret == 0))
2712 return 0;
2713
2714 if (unlikely(ret < 0)) {
2715 lua_pushnil(L);
2716 return -1;
2717 }
2718
2719 luaL_buffinit(L, &b);
2720 luaL_addlstring(&b, blk1, len1);
2721 if (unlikely(ret == 2))
2722 luaL_addlstring(&b, blk2, len2);
2723 luaL_pushresult(&b);
2724
2725 if (unlikely(ret == 2))
2726 return len1 + len2;
2727 return len1;
2728}
2729
2730/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2731 * a yield. This function keep the data in the buffer.
2732 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002733__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002734{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002735 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002736
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002737 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2738
Christopher Faulet3f829a42018-12-13 21:56:45 +01002739 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2740 WILL_LJMP(lua_error(L));
2741
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002742 if (_hlua_channel_dup(chn, L) == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002743 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002744 return 1;
2745}
2746
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002747/* Check arguments for the function "hlua_channel_dup_yield". */
2748__LJMP static int hlua_channel_dup(lua_State *L)
2749{
2750 MAY_LJMP(check_args(L, 1, "dup"));
2751 MAY_LJMP(hlua_checkchannel(L, 1));
2752 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2753}
2754
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002755/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2756 * a yield. This function consumes the data in the buffer. It returns
2757 * a string containing the data or a nil pointer if no data are available
2758 * and the channel is closed.
2759 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002760__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002761{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002762 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002763 int ret;
2764
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002765 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002766
Christopher Faulet3f829a42018-12-13 21:56:45 +01002767 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2768 WILL_LJMP(lua_error(L));
2769
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002770 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002771 if (unlikely(ret == 0))
Willy Tarreau9635e032018-10-16 17:52:55 +02002772 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002773
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002774 if (unlikely(ret == -1))
2775 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002776
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002777 b_sub(&chn->buf, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002778 return 1;
2779}
2780
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002781/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002782__LJMP static int hlua_channel_get(lua_State *L)
2783{
2784 MAY_LJMP(check_args(L, 1, "get"));
2785 MAY_LJMP(hlua_checkchannel(L, 1));
2786 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2787}
2788
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002789/* This functions consumes and returns one line. If the channel is closed,
2790 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002791 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002792 * value.
2793 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002794__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002795{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002796 char *blk1;
2797 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002798 size_t len1;
2799 size_t len2;
2800 size_t len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002801 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002802 int ret;
2803 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002804
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002805 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2806
Christopher Faulet3f829a42018-12-13 21:56:45 +01002807 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2808 WILL_LJMP(lua_error(L));
2809
Willy Tarreau06d80a92017-10-19 14:32:15 +02002810 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002811 if (ret == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002812 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002813
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002814 if (ret == -1) {
2815 lua_pushnil(L);
2816 return 1;
2817 }
2818
2819 luaL_buffinit(L, &b);
2820 luaL_addlstring(&b, blk1, len1);
2821 len = len1;
2822 if (unlikely(ret == 2)) {
2823 luaL_addlstring(&b, blk2, len2);
2824 len += len2;
2825 }
2826 luaL_pushresult(&b);
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002827 b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn) + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002828 return 1;
2829}
2830
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002831/* Check arguments for the function "hlua_channel_getline_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002832__LJMP static int hlua_channel_getline(lua_State *L)
2833{
2834 MAY_LJMP(check_args(L, 1, "getline"));
2835 MAY_LJMP(hlua_checkchannel(L, 1));
2836 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2837}
2838
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002839/* This function takes a string as input, and append it at the
2840 * input side of channel. If the data is too big, but a space
2841 * is probably available after sending some data, the function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002842 * yields. If the data is bigger than the buffer, or if the
2843 * channel is closed, it returns -1. Otherwise, it returns the
2844 * amount of data written.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002845 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002846__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002847{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002848 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002849 size_t len;
2850 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2851 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2852 int ret;
2853 int max;
2854
Christopher Faulet3f829a42018-12-13 21:56:45 +01002855 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2856 WILL_LJMP(lua_error(L));
2857
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002858 /* Check if the buffer is available because HAProxy doesn't allocate
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002859 * the request buffer if its not required.
2860 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002861 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01002862 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02002863 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002864 }
2865
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002866 max = channel_recv_limit(chn) - b_data(&chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002867 if (max > len - l)
2868 max = len - l;
2869
Willy Tarreau06d80a92017-10-19 14:32:15 +02002870 ret = ci_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002871 if (ret == -2 || ret == -3) {
2872 lua_pushinteger(L, -1);
2873 return 1;
2874 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002875 if (ret == -1) {
2876 chn->flags |= CF_WAKE_WRITE;
Willy Tarreau9635e032018-10-16 17:52:55 +02002877 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002878 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002879 l += ret;
2880 lua_pop(L, 1);
2881 lua_pushinteger(L, l);
2882
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002883 max = channel_recv_limit(chn) - b_data(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02002884 if (max == 0 && co_data(chn) == 0) {
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002885 /* There are no space available, and the output buffer is empty.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002886 * in this case, we cannot add more data, so we cannot yield,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002887 * we return the amount of copied data.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002888 */
2889 return 1;
2890 }
2891 if (l < len)
Willy Tarreau9635e032018-10-16 17:52:55 +02002892 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002893 return 1;
2894}
2895
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002896/* Just a wrapper of "hlua_channel_append_yield". It returns the length
2897 * of the written string, or -1 if the channel is closed or if the
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002898 * buffer size is too little for the data.
2899 */
2900__LJMP static int hlua_channel_append(lua_State *L)
2901{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002902 size_t len;
2903
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002904 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002905 MAY_LJMP(hlua_checkchannel(L, 1));
2906 MAY_LJMP(luaL_checklstring(L, 2, &len));
2907 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002908 lua_pushinteger(L, 0);
2909
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002910 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002911}
2912
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002913/* Just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002914 * his process by cleaning the buffer. The result is a replacement
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002915 * of the current data. It returns the length of the written string,
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002916 * or -1 if the channel is closed or if the buffer size is too
2917 * little for the data.
2918 */
2919__LJMP static int hlua_channel_set(lua_State *L)
2920{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002921 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002922
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002923 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002924 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002925 lua_pushinteger(L, 0);
2926
Christopher Faulet3f829a42018-12-13 21:56:45 +01002927 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2928 WILL_LJMP(lua_error(L));
2929
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002930 b_set_data(&chn->buf, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002931
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002932 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002933}
2934
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002935/* Append data in the output side of the buffer. This data is immediately
2936 * sent. The function returns the amount of data written. If the buffer
2937 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002938 * if the channel is closed.
2939 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002940__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002941{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002942 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002943 size_t len;
2944 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2945 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2946 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002947 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002948
Christopher Faulet3f829a42018-12-13 21:56:45 +01002949 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2950 WILL_LJMP(lua_error(L));
2951
Willy Tarreau47860ed2015-03-10 14:07:50 +01002952 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002953 lua_pushinteger(L, -1);
2954 return 1;
2955 }
2956
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002957 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002958 * the request buffer if its not required.
2959 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002960 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01002961 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02002962 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002963 }
2964
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002965 /* The written data will be immediately sent, so we can check
2966 * the available space without taking in account the reserve.
2967 * The reserve is guaranteed for the processing of incoming
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002968 * data, because the buffer will be flushed.
2969 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002970 max = b_room(&chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002971
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002972 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002973 * in this case, we cannot add more data, so we cannot yield,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002974 * we return the amount of copied data.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002975 */
Willy Tarreaua79021a2018-06-15 18:07:57 +02002976 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002977 return 1;
2978
2979 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002980 if (max > len - l)
2981 max = len - l;
2982
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002983 /* The buffer available size may be not contiguous. This test
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002984 * detects a non contiguous buffer and realign it.
2985 */
Willy Tarreau3f679992018-06-15 15:06:42 +02002986 if (ci_space_for_replace(chn) < max)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002987 channel_slow_realign(chn, trash.area);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002988
2989 /* Copy input data in the buffer. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002990 max = b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn), str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002991
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002992 /* buffer replace considers that the input part is filled.
2993 * so, I must forward these new data in the output part.
2994 */
Willy Tarreaubcbd3932018-06-06 07:13:22 +02002995 c_adv(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002996
2997 l += max;
2998 lua_pop(L, 1);
2999 lua_pushinteger(L, l);
3000
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003001 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003002 * in this case, we cannot add more data, so we cannot yield,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003003 * we return the amount of copied data.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003004 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003005 max = b_room(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02003006 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003007 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003008
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003009 if (l < len) {
3010 /* If we are waiting for space in the response buffer, we
3011 * must set the flag WAKERESWR. This flag required the task
3012 * wake up if any activity is detected on the response buffer.
3013 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003014 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003015 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003016 else
3017 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003018 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003019 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003020
3021 return 1;
3022}
3023
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003024/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003025 * yield the LUA process, and resume it without checking the
3026 * input arguments.
3027 */
3028__LJMP static int hlua_channel_send(lua_State *L)
3029{
3030 MAY_LJMP(check_args(L, 2, "send"));
3031 lua_pushinteger(L, 0);
3032
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003033 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003034}
3035
3036/* This function forward and amount of butes. The data pass from
3037 * the input side of the buffer to the output side, and can be
3038 * forwarded. This function never fails.
3039 *
3040 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003041 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003042 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003043__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003044{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003045 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003046 int len;
3047 int l;
3048 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003049 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003050
3051 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003052
3053 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
3054 WILL_LJMP(lua_error(L));
3055
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003056 len = MAY_LJMP(luaL_checkinteger(L, 2));
3057 l = MAY_LJMP(luaL_checkinteger(L, -1));
3058
3059 max = len - l;
Willy Tarreaua79021a2018-06-15 18:07:57 +02003060 if (max > ci_data(chn))
3061 max = ci_data(chn);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003062 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003063 l += max;
3064
3065 lua_pop(L, 1);
3066 lua_pushinteger(L, l);
3067
3068 /* Check if it miss bytes to forward. */
3069 if (l < len) {
3070 /* The the input channel or the output channel are closed, we
3071 * must return the amount of data forwarded.
3072 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003073 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003074 return 1;
3075
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003076 /* If we are waiting for space data in the response buffer, we
3077 * must set the flag WAKERESWR. This flag required the task
3078 * wake up if any activity is detected on the response buffer.
3079 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003080 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003081 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003082 else
3083 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003084
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003085 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003086 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003087 }
3088
3089 return 1;
3090}
3091
3092/* Just check the input and prepare the stack for the previous
3093 * function "hlua_channel_forward_yield"
3094 */
3095__LJMP static int hlua_channel_forward(lua_State *L)
3096{
3097 MAY_LJMP(check_args(L, 2, "forward"));
3098 MAY_LJMP(hlua_checkchannel(L, 1));
3099 MAY_LJMP(luaL_checkinteger(L, 2));
3100
3101 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003102 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003103}
3104
3105/* Just returns the number of bytes available in the input
3106 * side of the buffer. This function never fails.
3107 */
3108__LJMP static int hlua_channel_get_in_len(lua_State *L)
3109{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003110 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003111
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003112 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003113 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003114 if (IS_HTX_STRM(chn_strm(chn))) {
3115 struct htx *htx = htxbuf(&chn->buf);
3116 lua_pushinteger(L, htx->data - co_data(chn));
3117 }
3118 else
3119 lua_pushinteger(L, ci_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003120 return 1;
3121}
3122
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003123/* Returns true if the channel is full. */
3124__LJMP static int hlua_channel_is_full(lua_State *L)
3125{
3126 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003127
3128 MAY_LJMP(check_args(L, 1, "is_full"));
3129 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01003130 /* ignore the reserve, we are not on a producer side (ie in an
3131 * applet).
3132 */
3133 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003134 return 1;
3135}
3136
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01003137/* Returns true if the channel is the response channel. */
3138__LJMP static int hlua_channel_is_resp(lua_State *L)
3139{
3140 struct channel *chn;
3141
3142 MAY_LJMP(check_args(L, 1, "is_resp"));
3143 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3144
3145 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
3146 return 1;
3147}
3148
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003149/* Just returns the number of bytes available in the output
3150 * side of the buffer. This function never fails.
3151 */
3152__LJMP static int hlua_channel_get_out_len(lua_State *L)
3153{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003154 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003155
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003156 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003157 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreaua79021a2018-06-15 18:07:57 +02003158 lua_pushinteger(L, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003159 return 1;
3160}
3161
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003162/*
3163 *
3164 *
3165 * Class Fetches
3166 *
3167 *
3168 */
3169
3170/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003171 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003172 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003173__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003174{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003175 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003176}
3177
3178/* This function creates and push in the stack a fetch object according
3179 * with a current TXN.
3180 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003181static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003182{
Willy Tarreau7073c472015-04-06 11:15:40 +02003183 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003184
3185 /* Check stack size. */
3186 if (!lua_checkstack(L, 3))
3187 return 0;
3188
3189 /* Create the object: obj[0] = userdata.
3190 * Note that the base of the Fetches object is the
3191 * transaction object.
3192 */
3193 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003194 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003195 lua_rawseti(L, -2, 0);
3196
Willy Tarreau7073c472015-04-06 11:15:40 +02003197 hsmp->s = txn->s;
3198 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003199 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003200 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003201
3202 /* Pop a class sesison metatable and affect it to the userdata. */
3203 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3204 lua_setmetatable(L, -2);
3205
3206 return 1;
3207}
3208
3209/* This function is an LUA binding. It is called with each sample-fetch.
3210 * It uses closure argument to store the associated sample-fetch. It
3211 * returns only one argument or throws an error. An error is thrown
3212 * only if an error is encountered during the argument parsing. If
3213 * the "sample-fetch" function fails, nil is returned.
3214 */
3215__LJMP static int hlua_run_sample_fetch(lua_State *L)
3216{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003217 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003218 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003219 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003220 int i;
3221 struct sample smp;
3222
3223 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003224 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003225
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003226 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003227 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003228
Thierry FOURNIERca988662015-12-20 18:43:03 +01003229 /* Check execution authorization. */
3230 if (f->use & SMP_USE_HTTP_ANY &&
3231 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3232 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3233 "is not available in Lua services", f->kw);
3234 WILL_LJMP(lua_error(L));
3235 }
3236
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003237 /* Get extra arguments. */
3238 for (i = 0; i < lua_gettop(L) - 1; i++) {
3239 if (i >= ARGM_NBARGS)
3240 break;
3241 hlua_lua2arg(L, i + 2, &args[i]);
3242 }
3243 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003244 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003245
3246 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003247 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003248
3249 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003250 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003251 lua_pushfstring(L, "error in arguments");
3252 WILL_LJMP(lua_error(L));
3253 }
3254
3255 /* Initialise the sample. */
3256 memset(&smp, 0, sizeof(smp));
3257
3258 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003259 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003260 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003261 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003262 lua_pushstring(L, "");
3263 else
3264 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003265 return 1;
3266 }
3267
3268 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003269 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003270 hlua_smp2lua_str(L, &smp);
3271 else
3272 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003273 return 1;
3274}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003275
3276/*
3277 *
3278 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003279 * Class Converters
3280 *
3281 *
3282 */
3283
3284/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003285 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003286 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003287__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003288{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003289 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003290}
3291
3292/* This function creates and push in the stack a Converters object
3293 * according with a current TXN.
3294 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003295static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003296{
Willy Tarreau7073c472015-04-06 11:15:40 +02003297 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003298
3299 /* Check stack size. */
3300 if (!lua_checkstack(L, 3))
3301 return 0;
3302
3303 /* Create the object: obj[0] = userdata.
3304 * Note that the base of the Converters object is the
3305 * same than the TXN object.
3306 */
3307 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003308 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003309 lua_rawseti(L, -2, 0);
3310
Willy Tarreau7073c472015-04-06 11:15:40 +02003311 hsmp->s = txn->s;
3312 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003313 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003314 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003315
Willy Tarreau87b09662015-04-03 00:22:06 +02003316 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003317 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3318 lua_setmetatable(L, -2);
3319
3320 return 1;
3321}
3322
3323/* This function is an LUA binding. It is called with each converter.
3324 * It uses closure argument to store the associated converter. It
3325 * returns only one argument or throws an error. An error is thrown
3326 * only if an error is encountered during the argument parsing. If
3327 * the converter function function fails, nil is returned.
3328 */
3329__LJMP static int hlua_run_sample_conv(lua_State *L)
3330{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003331 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003332 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003333 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003334 int i;
3335 struct sample smp;
3336
3337 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003338 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003339
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003340 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003341 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003342
3343 /* Get extra arguments. */
3344 for (i = 0; i < lua_gettop(L) - 2; i++) {
3345 if (i >= ARGM_NBARGS)
3346 break;
3347 hlua_lua2arg(L, i + 3, &args[i]);
3348 }
3349 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003350 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003351
3352 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003353 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003354
3355 /* Run the special args checker. */
3356 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3357 hlua_pusherror(L, "error in arguments");
3358 WILL_LJMP(lua_error(L));
3359 }
3360
3361 /* Initialise the sample. */
3362 if (!hlua_lua2smp(L, 2, &smp)) {
3363 hlua_pusherror(L, "error in the input argument");
3364 WILL_LJMP(lua_error(L));
3365 }
3366
Willy Tarreau1777ea62016-03-10 16:15:46 +01003367 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3368
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003369 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003370 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003371 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003372 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003373 WILL_LJMP(lua_error(L));
3374 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003375 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3376 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003377 hlua_pusherror(L, "error during the input argument casting");
3378 WILL_LJMP(lua_error(L));
3379 }
3380
3381 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003382 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003383 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003384 lua_pushstring(L, "");
3385 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003386 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003387 return 1;
3388 }
3389
3390 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003391 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003392 hlua_smp2lua_str(L, &smp);
3393 else
3394 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003395 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003396}
3397
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003398/*
3399 *
3400 *
3401 * Class AppletTCP
3402 *
3403 *
3404 */
3405
3406/* Returns a struct hlua_txn if the stack entry "ud" is
3407 * a class stream, otherwise it throws an error.
3408 */
3409__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3410{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003411 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003412}
3413
3414/* This function creates and push in the stack an Applet object
3415 * according with a current TXN.
3416 */
3417static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3418{
3419 struct hlua_appctx *appctx;
3420 struct stream_interface *si = ctx->owner;
3421 struct stream *s = si_strm(si);
3422 struct proxy *p = s->be;
3423
3424 /* Check stack size. */
3425 if (!lua_checkstack(L, 3))
3426 return 0;
3427
3428 /* Create the object: obj[0] = userdata.
3429 * Note that the base of the Converters object is the
3430 * same than the TXN object.
3431 */
3432 lua_newtable(L);
3433 appctx = lua_newuserdata(L, sizeof(*appctx));
3434 lua_rawseti(L, -2, 0);
3435 appctx->appctx = ctx;
3436 appctx->htxn.s = s;
3437 appctx->htxn.p = p;
3438
3439 /* Create the "f" field that contains a list of fetches. */
3440 lua_pushstring(L, "f");
3441 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3442 return 0;
3443 lua_settable(L, -3);
3444
3445 /* Create the "sf" field that contains a list of stringsafe fetches. */
3446 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003447 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003448 return 0;
3449 lua_settable(L, -3);
3450
3451 /* Create the "c" field that contains a list of converters. */
3452 lua_pushstring(L, "c");
3453 if (!hlua_converters_new(L, &appctx->htxn, 0))
3454 return 0;
3455 lua_settable(L, -3);
3456
3457 /* Create the "sc" field that contains a list of stringsafe converters. */
3458 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003459 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003460 return 0;
3461 lua_settable(L, -3);
3462
3463 /* Pop a class stream metatable and affect it to the table. */
3464 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3465 lua_setmetatable(L, -2);
3466
3467 return 1;
3468}
3469
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003470__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3471{
3472 struct hlua_appctx *appctx;
3473 struct stream *s;
3474 const char *name;
3475 size_t len;
3476 struct sample smp;
3477
3478 MAY_LJMP(check_args(L, 3, "set_var"));
3479
3480 /* It is useles to retrieve the stream, but this function
3481 * runs only in a stream context.
3482 */
3483 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3484 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3485 s = appctx->htxn.s;
3486
3487 /* Converts the third argument in a sample. */
3488 hlua_lua2smp(L, 3, &smp);
3489
3490 /* Store the sample in a variable. */
3491 smp_set_owner(&smp, s->be, s->sess, s, 0);
3492 vars_set_by_name(name, len, &smp);
3493 return 0;
3494}
3495
3496__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3497{
3498 struct hlua_appctx *appctx;
3499 struct stream *s;
3500 const char *name;
3501 size_t len;
3502 struct sample smp;
3503
3504 MAY_LJMP(check_args(L, 2, "unset_var"));
3505
3506 /* It is useles to retrieve the stream, but this function
3507 * runs only in a stream context.
3508 */
3509 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3510 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3511 s = appctx->htxn.s;
3512
3513 /* Unset the variable. */
3514 smp_set_owner(&smp, s->be, s->sess, s, 0);
3515 vars_unset_by_name(name, len, &smp);
3516 return 0;
3517}
3518
3519__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3520{
3521 struct hlua_appctx *appctx;
3522 struct stream *s;
3523 const char *name;
3524 size_t len;
3525 struct sample smp;
3526
3527 MAY_LJMP(check_args(L, 2, "get_var"));
3528
3529 /* It is useles to retrieve the stream, but this function
3530 * runs only in a stream context.
3531 */
3532 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3533 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3534 s = appctx->htxn.s;
3535
3536 smp_set_owner(&smp, s->be, s->sess, s, 0);
3537 if (!vars_get_by_name(name, len, &smp)) {
3538 lua_pushnil(L);
3539 return 1;
3540 }
3541
3542 return hlua_smp2lua(L, &smp);
3543}
3544
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003545__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3546{
3547 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3548 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003549 struct hlua *hlua;
3550
3551 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003552 if (!s->hlua)
3553 return 0;
3554 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003555
3556 MAY_LJMP(check_args(L, 2, "set_priv"));
3557
3558 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003559 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003560
3561 /* Get and store new value. */
3562 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3563 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3564
3565 return 0;
3566}
3567
3568__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3569{
3570 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3571 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003572 struct hlua *hlua;
3573
3574 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003575 if (!s->hlua) {
3576 lua_pushnil(L);
3577 return 1;
3578 }
3579 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003580
3581 /* Push configuration index in the stack. */
3582 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3583
3584 return 1;
3585}
3586
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003587/* If expected data not yet available, it returns a yield. This function
3588 * consumes the data in the buffer. It returns a string containing the
3589 * data. This string can be empty.
3590 */
3591__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3592{
3593 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3594 struct stream_interface *si = appctx->appctx->owner;
3595 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003596 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003597 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003598 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003599 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003600
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003601 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003602 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003603
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003604 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003605 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003606 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003607 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003608 }
3609
3610 /* End of data: commit the total strings and return. */
3611 if (ret < 0) {
3612 luaL_pushresult(&appctx->b);
3613 return 1;
3614 }
3615
3616 /* Ensure that the block 2 length is usable. */
3617 if (ret == 1)
3618 len2 = 0;
3619
3620 /* dont check the max length read and dont check. */
3621 luaL_addlstring(&appctx->b, blk1, len1);
3622 luaL_addlstring(&appctx->b, blk2, len2);
3623
3624 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003625 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003626 luaL_pushresult(&appctx->b);
3627 return 1;
3628}
3629
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003630/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003631__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3632{
3633 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3634
3635 /* Initialise the string catenation. */
3636 luaL_buffinit(L, &appctx->b);
3637
3638 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3639}
3640
3641/* If expected data not yet available, it returns a yield. This function
3642 * consumes the data in the buffer. It returns a string containing the
3643 * data. This string can be empty.
3644 */
3645__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3646{
3647 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3648 struct stream_interface *si = appctx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003649 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003650 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003651 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003652 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003653 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003654 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003655
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003656 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003657 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003658
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003659 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003660 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003661 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003662 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003663 }
3664
3665 /* End of data: commit the total strings and return. */
3666 if (ret < 0) {
3667 luaL_pushresult(&appctx->b);
3668 return 1;
3669 }
3670
3671 /* Ensure that the block 2 length is usable. */
3672 if (ret == 1)
3673 len2 = 0;
3674
3675 if (len == -1) {
3676
3677 /* If len == -1, catenate all the data avalaile and
3678 * yield because we want to get all the data until
3679 * the end of data stream.
3680 */
3681 luaL_addlstring(&appctx->b, blk1, len1);
3682 luaL_addlstring(&appctx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02003683 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003684 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003685 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003686
3687 } else {
3688
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003689 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003690 if (len1 > len)
3691 len1 = len;
3692 luaL_addlstring(&appctx->b, blk1, len1);
3693 len -= len1;
3694
3695 /* Copy the second block. */
3696 if (len2 > len)
3697 len2 = len;
3698 luaL_addlstring(&appctx->b, blk2, len2);
3699 len -= len2;
3700
3701 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003702 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003703
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003704 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003705 if (len > 0) {
3706 lua_pushinteger(L, len);
3707 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003708 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003709 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003710 }
3711
3712 /* return the result. */
3713 luaL_pushresult(&appctx->b);
3714 return 1;
3715 }
3716
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003717 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003718 hlua_pusherror(L, "Lua: internal error");
3719 WILL_LJMP(lua_error(L));
3720 return 0;
3721}
3722
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003723/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003724__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3725{
3726 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3727 int len = -1;
3728
3729 if (lua_gettop(L) > 2)
3730 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3731 if (lua_gettop(L) >= 2) {
3732 len = MAY_LJMP(luaL_checkinteger(L, 2));
3733 lua_pop(L, 1);
3734 }
3735
3736 /* Confirm or set the required length */
3737 lua_pushinteger(L, len);
3738
3739 /* Initialise the string catenation. */
3740 luaL_buffinit(L, &appctx->b);
3741
3742 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3743}
3744
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003745/* Append data in the output side of the buffer. This data is immediately
3746 * sent. The function returns the amount of data written. If the buffer
3747 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003748 * if the channel is closed.
3749 */
3750__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3751{
3752 size_t len;
3753 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3754 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3755 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3756 struct stream_interface *si = appctx->appctx->owner;
3757 struct channel *chn = si_ic(si);
3758 int max;
3759
3760 /* Get the max amount of data which can write as input in the channel. */
3761 max = channel_recv_max(chn);
3762 if (max > (len - l))
3763 max = len - l;
3764
3765 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003766 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003767
3768 /* update counters. */
3769 l += max;
3770 lua_pop(L, 1);
3771 lua_pushinteger(L, l);
3772
3773 /* If some data is not send, declares the situation to the
3774 * applet, and returns a yield.
3775 */
3776 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01003777 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003778 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003779 }
3780
3781 return 1;
3782}
3783
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003784/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003785 * yield the LUA process, and resume it without checking the
3786 * input arguments.
3787 */
3788__LJMP static int hlua_applet_tcp_send(lua_State *L)
3789{
3790 MAY_LJMP(check_args(L, 2, "send"));
3791 lua_pushinteger(L, 0);
3792
3793 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3794}
3795
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003796/*
3797 *
3798 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003799 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003800 *
3801 *
3802 */
3803
3804/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003805 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003806 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003807__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003808{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003809 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003810}
3811
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003812/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003813 * according with a current TXN.
3814 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003815static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003816{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003817 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003818 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003819 struct stream_interface *si = ctx->owner;
3820 struct stream *s = si_strm(si);
3821 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02003822 struct htx *htx;
3823 struct htx_blk *blk;
3824 struct htx_sl *sl;
3825 struct ist path;
3826 unsigned long long len = 0;
3827 int32_t pos;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003828
3829 /* Check stack size. */
3830 if (!lua_checkstack(L, 3))
3831 return 0;
3832
3833 /* Create the object: obj[0] = userdata.
3834 * Note that the base of the Converters object is the
3835 * same than the TXN object.
3836 */
3837 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003838 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003839 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003840 appctx->appctx = ctx;
3841 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003842 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003843 appctx->htxn.s = s;
3844 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003845
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003846 /* Create the "f" field that contains a list of fetches. */
3847 lua_pushstring(L, "f");
3848 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3849 return 0;
3850 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003851
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003852 /* Create the "sf" field that contains a list of stringsafe fetches. */
3853 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003854 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003855 return 0;
3856 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003857
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003858 /* Create the "c" field that contains a list of converters. */
3859 lua_pushstring(L, "c");
3860 if (!hlua_converters_new(L, &appctx->htxn, 0))
3861 return 0;
3862 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003863
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003864 /* Create the "sc" field that contains a list of stringsafe converters. */
3865 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003866 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003867 return 0;
3868 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003869
Christopher Fauleta2097962019-07-15 16:25:33 +02003870 htx = htxbuf(&s->req.buf);
3871 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01003872 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02003873 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003874
Christopher Fauleta2097962019-07-15 16:25:33 +02003875 /* Stores the request method. */
3876 lua_pushstring(L, "method");
3877 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
3878 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003879
Christopher Fauleta2097962019-07-15 16:25:33 +02003880 /* Stores the http version. */
3881 lua_pushstring(L, "version");
3882 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
3883 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003884
Christopher Fauleta2097962019-07-15 16:25:33 +02003885 /* creates an array of headers. hlua_http_get_headers() crates and push
3886 * the array on the top of the stack.
3887 */
3888 lua_pushstring(L, "headers");
3889 htxn.s = s;
3890 htxn.p = px;
3891 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01003892 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02003893 return 0;
3894 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003895
Christopher Fauleta2097962019-07-15 16:25:33 +02003896 path = http_get_path(htx_sl_req_uri(sl));
Tim Duesterhused526372020-03-05 17:56:33 +01003897 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02003898 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003899
Christopher Fauleta2097962019-07-15 16:25:33 +02003900 p = path.ptr;
3901 end = path.ptr + path.len;
3902 q = p;
3903 while (q < end && *q != '?')
3904 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003905
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003906 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02003907 lua_pushstring(L, "path");
3908 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003909 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003910
Christopher Fauleta2097962019-07-15 16:25:33 +02003911 /* Stores the query string. */
3912 lua_pushstring(L, "qs");
3913 if (*q == '?')
3914 q++;
3915 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003916 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02003917 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003918
Christopher Fauleta2097962019-07-15 16:25:33 +02003919 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3920 struct htx_blk *blk = htx_get_blk(htx, pos);
3921 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003922
Christopher Fauleta2097962019-07-15 16:25:33 +02003923 if (type == HTX_BLK_EOM || type == HTX_BLK_TLR || type == HTX_BLK_EOT)
3924 break;
3925 if (type == HTX_BLK_DATA)
3926 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003927 }
Christopher Fauleta2097962019-07-15 16:25:33 +02003928 if (htx->extra != ULLONG_MAX)
3929 len += htx->extra;
3930
3931 /* Stores the request path. */
3932 lua_pushstring(L, "length");
3933 lua_pushinteger(L, len);
3934 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003935
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003936 /* Create an empty array of HTTP request headers. */
3937 lua_pushstring(L, "response");
3938 lua_newtable(L);
3939 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003940
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003941 /* Pop a class stream metatable and affect it to the table. */
3942 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3943 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003944
3945 return 1;
3946}
3947
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003948__LJMP static int hlua_applet_http_set_var(lua_State *L)
3949{
3950 struct hlua_appctx *appctx;
3951 struct stream *s;
3952 const char *name;
3953 size_t len;
3954 struct sample smp;
3955
3956 MAY_LJMP(check_args(L, 3, "set_var"));
3957
3958 /* It is useles to retrieve the stream, but this function
3959 * runs only in a stream context.
3960 */
3961 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3962 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3963 s = appctx->htxn.s;
3964
3965 /* Converts the third argument in a sample. */
3966 hlua_lua2smp(L, 3, &smp);
3967
3968 /* Store the sample in a variable. */
3969 smp_set_owner(&smp, s->be, s->sess, s, 0);
3970 vars_set_by_name(name, len, &smp);
3971 return 0;
3972}
3973
3974__LJMP static int hlua_applet_http_unset_var(lua_State *L)
3975{
3976 struct hlua_appctx *appctx;
3977 struct stream *s;
3978 const char *name;
3979 size_t len;
3980 struct sample smp;
3981
3982 MAY_LJMP(check_args(L, 2, "unset_var"));
3983
3984 /* It is useles to retrieve the stream, but this function
3985 * runs only in a stream context.
3986 */
3987 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3988 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3989 s = appctx->htxn.s;
3990
3991 /* Unset the variable. */
3992 smp_set_owner(&smp, s->be, s->sess, s, 0);
3993 vars_unset_by_name(name, len, &smp);
3994 return 0;
3995}
3996
3997__LJMP static int hlua_applet_http_get_var(lua_State *L)
3998{
3999 struct hlua_appctx *appctx;
4000 struct stream *s;
4001 const char *name;
4002 size_t len;
4003 struct sample smp;
4004
4005 MAY_LJMP(check_args(L, 2, "get_var"));
4006
4007 /* It is useles to retrieve the stream, but this function
4008 * runs only in a stream context.
4009 */
4010 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4011 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4012 s = appctx->htxn.s;
4013
4014 smp_set_owner(&smp, s->be, s->sess, s, 0);
4015 if (!vars_get_by_name(name, len, &smp)) {
4016 lua_pushnil(L);
4017 return 1;
4018 }
4019
4020 return hlua_smp2lua(L, &smp);
4021}
4022
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004023__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4024{
4025 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4026 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004027 struct hlua *hlua;
4028
4029 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004030 if (!s->hlua)
4031 return 0;
4032 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004033
4034 MAY_LJMP(check_args(L, 2, "set_priv"));
4035
4036 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004037 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004038
4039 /* Get and store new value. */
4040 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4041 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4042
4043 return 0;
4044}
4045
4046__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4047{
4048 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4049 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004050 struct hlua *hlua;
4051
4052 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004053 if (!s->hlua) {
4054 lua_pushnil(L);
4055 return 1;
4056 }
4057 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004058
4059 /* Push configuration index in the stack. */
4060 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4061
4062 return 1;
4063}
4064
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004065/* If expected data not yet available, it returns a yield. This function
4066 * consumes the data in the buffer. It returns a string containing the
4067 * data. This string can be empty.
4068 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004069__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004070{
4071 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4072 struct stream_interface *si = appctx->appctx->owner;
4073 struct channel *req = si_oc(si);
4074 struct htx *htx;
4075 struct htx_blk *blk;
4076 size_t count;
4077 int stop = 0;
4078
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004079 htx = htx_from_buf(&req->buf);
4080 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004081 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004082
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004083 while (count && !stop && blk) {
4084 enum htx_blk_type type = htx_get_blk_type(blk);
4085 uint32_t sz = htx_get_blksz(blk);
4086 struct ist v;
4087 uint32_t vlen;
4088 char *nl;
4089
Christopher Faulete461e342018-12-18 16:43:35 +01004090 if (type == HTX_BLK_EOM) {
4091 stop = 1;
4092 break;
4093 }
4094
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004095 vlen = sz;
4096 if (vlen > count) {
4097 if (type != HTX_BLK_DATA)
4098 break;
4099 vlen = count;
4100 }
4101
4102 switch (type) {
4103 case HTX_BLK_UNUSED:
4104 break;
4105
4106 case HTX_BLK_DATA:
4107 v = htx_get_blk_value(htx, blk);
4108 v.len = vlen;
4109 nl = istchr(v, '\n');
4110 if (nl != NULL) {
4111 stop = 1;
4112 vlen = nl - v.ptr + 1;
4113 }
4114 luaL_addlstring(&appctx->b, v.ptr, vlen);
4115 break;
4116
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004117 case HTX_BLK_TLR:
4118 case HTX_BLK_EOM:
4119 stop = 1;
4120 break;
4121
4122 default:
4123 break;
4124 }
4125
4126 co_set_data(req, co_data(req) - vlen);
4127 count -= vlen;
4128 if (sz == vlen)
4129 blk = htx_remove_blk(htx, blk);
4130 else {
4131 htx_cut_data_blk(htx, blk, vlen);
4132 break;
4133 }
4134 }
4135
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004136 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004137 if (!stop) {
4138 si_cant_get(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02004139 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004140 }
4141
4142 /* return the result. */
4143 luaL_pushresult(&appctx->b);
4144 return 1;
4145}
4146
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004147
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004148/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004149__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004150{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004151 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004152
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004153 /* Initialise the string catenation. */
4154 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004155
Christopher Fauleta2097962019-07-15 16:25:33 +02004156 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004157}
4158
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004159/* If expected data not yet available, it returns a yield. This function
4160 * consumes the data in the buffer. It returns a string containing the
4161 * data. This string can be empty.
4162 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004163__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004164{
4165 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4166 struct stream_interface *si = appctx->appctx->owner;
4167 struct channel *req = si_oc(si);
4168 struct htx *htx;
4169 struct htx_blk *blk;
4170 size_t count;
4171 int len;
4172
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004173 htx = htx_from_buf(&req->buf);
4174 len = MAY_LJMP(luaL_checkinteger(L, 2));
4175 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02004176 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004177 while (count && len && blk) {
4178 enum htx_blk_type type = htx_get_blk_type(blk);
4179 uint32_t sz = htx_get_blksz(blk);
4180 struct ist v;
4181 uint32_t vlen;
4182
Christopher Faulete461e342018-12-18 16:43:35 +01004183 if (type == HTX_BLK_EOM) {
4184 len = 0;
4185 break;
4186 }
4187
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004188 vlen = sz;
4189 if (len > 0 && vlen > len)
4190 vlen = len;
4191 if (vlen > count) {
4192 if (type != HTX_BLK_DATA)
4193 break;
4194 vlen = count;
4195 }
4196
4197 switch (type) {
4198 case HTX_BLK_UNUSED:
4199 break;
4200
4201 case HTX_BLK_DATA:
4202 v = htx_get_blk_value(htx, blk);
4203 luaL_addlstring(&appctx->b, v.ptr, vlen);
4204 break;
4205
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004206 case HTX_BLK_TLR:
4207 case HTX_BLK_EOM:
4208 len = 0;
4209 break;
4210
4211 default:
4212 break;
4213 }
4214
4215 co_set_data(req, co_data(req) - vlen);
4216 count -= vlen;
4217 if (len > 0)
4218 len -= vlen;
4219 if (sz == vlen)
4220 blk = htx_remove_blk(htx, blk);
4221 else {
4222 htx_cut_data_blk(htx, blk, vlen);
4223 break;
4224 }
4225 }
4226
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004227 htx_to_buf(htx, &req->buf);
4228
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004229 /* If we are no other data available, yield waiting for new data. */
4230 if (len) {
4231 if (len > 0) {
4232 lua_pushinteger(L, len);
4233 lua_replace(L, 2);
4234 }
4235 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004236 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004237 }
4238
4239 /* return the result. */
4240 luaL_pushresult(&appctx->b);
4241 return 1;
4242}
4243
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004244/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004245__LJMP static int hlua_applet_http_recv(lua_State *L)
4246{
4247 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4248 int len = -1;
4249
4250 /* Check arguments. */
4251 if (lua_gettop(L) > 2)
4252 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4253 if (lua_gettop(L) >= 2) {
4254 len = MAY_LJMP(luaL_checkinteger(L, 2));
4255 lua_pop(L, 1);
4256 }
4257
Christopher Fauleta2097962019-07-15 16:25:33 +02004258 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004259
Christopher Fauleta2097962019-07-15 16:25:33 +02004260 /* Initialise the string catenation. */
4261 luaL_buffinit(L, &appctx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004262
Christopher Fauleta2097962019-07-15 16:25:33 +02004263 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004264}
4265
4266/* Append data in the output side of the buffer. This data is immediately
4267 * sent. The function returns the amount of data written. If the buffer
4268 * cannot contain the data, the function yields. The function returns -1
4269 * if the channel is closed.
4270 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004271__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004272{
4273 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4274 struct stream_interface *si = appctx->appctx->owner;
4275 struct channel *res = si_ic(si);
4276 struct htx *htx = htx_from_buf(&res->buf);
4277 const char *data;
4278 size_t len;
4279 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4280 int max;
4281
Christopher Faulet9060fc02019-07-03 11:39:30 +02004282 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004283 if (!max)
4284 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004285
4286 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
4287
4288 /* Get the max amount of data which can write as input in the channel. */
4289 if (max > (len - l))
4290 max = len - l;
4291
4292 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02004293 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004294 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004295
4296 /* update counters. */
4297 l += max;
4298 lua_pop(L, 1);
4299 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004300
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004301 /* If some data is not send, declares the situation to the
4302 * applet, and returns a yield.
4303 */
4304 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004305 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004306 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004307 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004308 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004309 }
4310
Christopher Fauleta2097962019-07-15 16:25:33 +02004311 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004312 return 1;
4313}
4314
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004315/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004316 * yield the LUA process, and resume it without checking the
4317 * input arguments.
4318 */
4319__LJMP static int hlua_applet_http_send(lua_State *L)
4320{
4321 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004322
4323 /* We want to send some data. Headers must be sent. */
4324 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4325 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4326 WILL_LJMP(lua_error(L));
4327 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004328
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004329 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004330 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004331
Christopher Fauleta2097962019-07-15 16:25:33 +02004332 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004333}
4334
4335__LJMP static int hlua_applet_http_addheader(lua_State *L)
4336{
4337 const char *name;
4338 int ret;
4339
4340 MAY_LJMP(hlua_checkapplet_http(L, 1));
4341 name = MAY_LJMP(luaL_checkstring(L, 2));
4342 MAY_LJMP(luaL_checkstring(L, 3));
4343
4344 /* Push in the stack the "response" entry. */
4345 ret = lua_getfield(L, 1, "response");
4346 if (ret != LUA_TTABLE) {
4347 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4348 "is expected as an array. %s found", lua_typename(L, ret));
4349 WILL_LJMP(lua_error(L));
4350 }
4351
4352 /* check if the header is already registered if it is not
4353 * the case, register it.
4354 */
4355 ret = lua_getfield(L, -1, name);
4356 if (ret == LUA_TNIL) {
4357
4358 /* Entry not found. */
4359 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4360
4361 /* Insert the new header name in the array in the top of the stack.
4362 * It left the new array in the top of the stack.
4363 */
4364 lua_newtable(L);
4365 lua_pushvalue(L, 2);
4366 lua_pushvalue(L, -2);
4367 lua_settable(L, -4);
4368
4369 } else if (ret != LUA_TTABLE) {
4370
4371 /* corruption error. */
4372 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4373 "is expected as an array. %s found", name, lua_typename(L, ret));
4374 WILL_LJMP(lua_error(L));
4375 }
4376
4377 /* Now the top od thestack is an array of values. We push
4378 * the header value as new entry.
4379 */
4380 lua_pushvalue(L, 3);
4381 ret = lua_rawlen(L, -2);
4382 lua_rawseti(L, -2, ret + 1);
4383 lua_pushboolean(L, 1);
4384 return 1;
4385}
4386
4387__LJMP static int hlua_applet_http_status(lua_State *L)
4388{
4389 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4390 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004391 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004392
4393 if (status < 100 || status > 599) {
4394 lua_pushboolean(L, 0);
4395 return 1;
4396 }
4397
4398 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004399 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004400 lua_pushboolean(L, 1);
4401 return 1;
4402}
4403
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004404
Christopher Fauleta2097962019-07-15 16:25:33 +02004405__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004406{
4407 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4408 struct stream_interface *si = appctx->appctx->owner;
4409 struct channel *res = si_ic(si);
4410 struct htx *htx;
4411 struct htx_sl *sl;
4412 struct h1m h1m;
4413 const char *status, *reason;
4414 const char *name, *value;
4415 size_t nlen, vlen;
4416 unsigned int flags;
4417
4418 /* Send the message at once. */
4419 htx = htx_from_buf(&res->buf);
4420 h1m_init_res(&h1m);
4421
4422 /* Use the same http version than the request. */
4423 status = ultoa_r(appctx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
4424 reason = appctx->appctx->ctx.hlua_apphttp.reason;
4425 if (reason == NULL)
4426 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
4427 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
4428 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
4429 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
4430 }
4431 else {
4432 flags = HTX_SL_F_IS_RESP;
4433 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
4434 }
4435 if (!sl) {
4436 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
4437 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4438 WILL_LJMP(lua_error(L));
4439 }
4440 sl->info.res.status = appctx->appctx->ctx.hlua_apphttp.status;
4441
4442 /* Get the array associated to the field "response" in the object AppletHTTP. */
4443 lua_pushvalue(L, 0);
4444 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4445 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4446 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4447 WILL_LJMP(lua_error(L));
4448 }
4449
4450 /* Browse the list of headers. */
4451 lua_pushnil(L);
4452 while(lua_next(L, -2) != 0) {
4453 /* We expect a string as -2. */
4454 if (lua_type(L, -2) != LUA_TSTRING) {
4455 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4456 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4457 lua_typename(L, lua_type(L, -2)));
4458 WILL_LJMP(lua_error(L));
4459 }
4460 name = lua_tolstring(L, -2, &nlen);
4461
4462 /* We expect an array as -1. */
4463 if (lua_type(L, -1) != LUA_TTABLE) {
4464 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4465 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4466 name,
4467 lua_typename(L, lua_type(L, -1)));
4468 WILL_LJMP(lua_error(L));
4469 }
4470
4471 /* Browse the table who is on the top of the stack. */
4472 lua_pushnil(L);
4473 while(lua_next(L, -2) != 0) {
4474 int id;
4475
4476 /* We expect a number as -2. */
4477 if (lua_type(L, -2) != LUA_TNUMBER) {
4478 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4479 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4480 name,
4481 lua_typename(L, lua_type(L, -2)));
4482 WILL_LJMP(lua_error(L));
4483 }
4484 id = lua_tointeger(L, -2);
4485
4486 /* We expect a string as -2. */
4487 if (lua_type(L, -1) != LUA_TSTRING) {
4488 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4489 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4490 name, id,
4491 lua_typename(L, lua_type(L, -1)));
4492 WILL_LJMP(lua_error(L));
4493 }
4494 value = lua_tolstring(L, -1, &vlen);
4495
4496 /* Simple Protocol checks. */
4497 if (isteqi(ist2(name, nlen), ist("transfer-encoding")))
Christopher Faulet700d9e82020-01-31 12:21:52 +01004498 h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004499 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
4500 struct ist v = ist2(value, vlen);
4501 int ret;
4502
4503 ret = h1_parse_cont_len_header(&h1m, &v);
4504 if (ret < 0) {
4505 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
4506 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4507 name);
4508 WILL_LJMP(lua_error(L));
4509 }
4510 else if (ret == 0)
4511 goto next; /* Skip it */
4512 }
4513
4514 /* Add a new header */
4515 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
4516 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
4517 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4518 name);
4519 WILL_LJMP(lua_error(L));
4520 }
4521 next:
4522 /* Remove the array from the stack, and get next element with a remaining string. */
4523 lua_pop(L, 1);
4524 }
4525
4526 /* Remove the array from the stack, and get next element with a remaining string. */
4527 lua_pop(L, 1);
4528 }
4529
4530 if (h1m.flags & H1_MF_CHNK)
4531 h1m.flags &= ~H1_MF_CLEN;
4532 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
4533 h1m.flags |= H1_MF_XFER_LEN;
4534
4535 /* Uset HTX start-line flags */
4536 if (h1m.flags & H1_MF_XFER_ENC)
4537 flags |= HTX_SL_F_XFER_ENC;
4538 if (h1m.flags & H1_MF_XFER_LEN) {
4539 flags |= HTX_SL_F_XFER_LEN;
4540 if (h1m.flags & H1_MF_CHNK)
4541 flags |= HTX_SL_F_CHNK;
4542 else if (h1m.flags & H1_MF_CLEN)
4543 flags |= HTX_SL_F_CLEN;
4544 if (h1m.body_len == 0)
4545 flags |= HTX_SL_F_BODYLESS;
4546 }
4547 sl->flags |= flags;
4548
4549 /* If we dont have a content-length set, and the HTTP version is 1.1
4550 * and the status code implies the presence of a message body, we must
4551 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004552 * for the keepalive compliance. If the applet announces a transfer-encoding
4553 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004554 */
4555 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
4556 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4557 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4558 appctx->appctx->ctx.hlua_apphttp.status != 304) {
4559 /* Add a new header */
4560 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
4561 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
4562 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
4563 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4564 WILL_LJMP(lua_error(L));
4565 }
4566 }
4567
4568 /* Finalize headers. */
4569 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
4570 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
4571 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4572 WILL_LJMP(lua_error(L));
4573 }
4574
4575 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
4576 b_reset(&res->buf);
4577 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4578 WILL_LJMP(lua_error(L));
4579 }
4580
4581 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004582 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004583
4584 /* Headers sent, set the flag. */
4585 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4586 return 0;
4587
4588}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004589/* We will build the status line and the headers of the HTTP response.
4590 * We will try send at once if its not possible, we give back the hand
4591 * waiting for more room.
4592 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004593__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004594{
4595 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4596 struct stream_interface *si = appctx->appctx->owner;
4597 struct channel *res = si_ic(si);
4598
4599 if (co_data(res)) {
4600 si_rx_room_blk(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02004601 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004602 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004603 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004604}
4605
4606
Christopher Fauleta2097962019-07-15 16:25:33 +02004607__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004608{
Christopher Fauleta2097962019-07-15 16:25:33 +02004609 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004610}
4611
Christopher Fauleta2097962019-07-15 16:25:33 +02004612/*
4613 *
4614 *
4615 * Class HTTP
4616 *
4617 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004618 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004619
4620/* Returns a struct hlua_txn if the stack entry "ud" is
4621 * a class stream, otherwise it throws an error.
4622 */
4623__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004624{
Christopher Fauleta2097962019-07-15 16:25:33 +02004625 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
4626}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004627
Christopher Fauleta2097962019-07-15 16:25:33 +02004628/* This function creates and push in the stack a HTTP object
4629 * according with a current TXN.
4630 */
4631static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4632{
4633 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004634
Christopher Fauleta2097962019-07-15 16:25:33 +02004635 /* Check stack size. */
4636 if (!lua_checkstack(L, 3))
4637 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004638
Christopher Fauleta2097962019-07-15 16:25:33 +02004639 /* Create the object: obj[0] = userdata.
4640 * Note that the base of the Converters object is the
4641 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004642 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004643 lua_newtable(L);
4644 htxn = lua_newuserdata(L, sizeof(*htxn));
4645 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004646
4647 htxn->s = txn->s;
4648 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02004649 htxn->dir = txn->dir;
4650 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004651
4652 /* Pop a class stream metatable and affect it to the table. */
4653 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4654 lua_setmetatable(L, -2);
4655
4656 return 1;
4657}
4658
4659/* This function creates ans returns an array of HTTP headers.
4660 * This function does not fails. It is used as wrapper with the
4661 * 2 following functions.
4662 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004663__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004664{
Christopher Fauleta2097962019-07-15 16:25:33 +02004665 struct htx *htx;
4666 int32_t pos;
4667
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004668 /* Create the table. */
4669 lua_newtable(L);
4670
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004671
Christopher Fauleta2097962019-07-15 16:25:33 +02004672 htx = htxbuf(&msg->chn->buf);
4673 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4674 struct htx_blk *blk = htx_get_blk(htx, pos);
4675 enum htx_blk_type type = htx_get_blk_type(blk);
4676 struct ist n, v;
4677 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01004678
Christopher Fauleta2097962019-07-15 16:25:33 +02004679 if (type == HTX_BLK_HDR) {
4680 n = htx_get_blk_name(htx,blk);
4681 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01004682 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004683 else if (type == HTX_BLK_EOH)
4684 break;
4685 else
4686 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01004687
Christopher Fauleta2097962019-07-15 16:25:33 +02004688 /* Check for existing entry:
4689 * assume that the table is on the top of the stack, and
4690 * push the key in the stack, the function lua_gettable()
4691 * perform the lookup.
4692 */
4693 lua_pushlstring(L, n.ptr, n.len);
4694 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01004695
Christopher Fauleta2097962019-07-15 16:25:33 +02004696 switch (lua_type(L, -1)) {
4697 case LUA_TNIL:
4698 /* Table not found, create it. */
4699 lua_pop(L, 1); /* remove the nil value. */
4700 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
4701 lua_newtable(L); /* create and push empty table. */
4702 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
4703 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4704 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01004705 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01004706
Christopher Fauleta2097962019-07-15 16:25:33 +02004707 case LUA_TTABLE:
4708 /* Entry found: push the value in the table. */
4709 len = lua_rawlen(L, -1);
4710 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
4711 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4712 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4713 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004714
Christopher Fauleta2097962019-07-15 16:25:33 +02004715 default:
4716 /* Other cases are errors. */
4717 hlua_pusherror(L, "internal error during the parsing of headers.");
4718 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004719 }
4720 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004721 return 1;
4722}
4723
4724__LJMP static int hlua_http_req_get_headers(lua_State *L)
4725{
4726 struct hlua_txn *htxn;
4727
4728 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4729 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4730
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004731 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004732 WILL_LJMP(lua_error(L));
4733
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004734 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004735}
4736
4737__LJMP static int hlua_http_res_get_headers(lua_State *L)
4738{
4739 struct hlua_txn *htxn;
4740
4741 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4742 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4743
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004744 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004745 WILL_LJMP(lua_error(L));
4746
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004747 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004748}
4749
4750/* This function replace full header, or just a value in
4751 * the request or in the response. It is a wrapper fir the
4752 * 4 following functions.
4753 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01004754__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004755{
4756 size_t name_len;
4757 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4758 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4759 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02004760 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02004761 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004762
Dragan Dosen26743032019-04-30 15:54:36 +02004763 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004764 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4765
Christopher Fauleta2097962019-07-15 16:25:33 +02004766 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01004767 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02004768 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004769 return 0;
4770}
4771
4772__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4773{
4774 struct hlua_txn *htxn;
4775
4776 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4777 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4778
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004779 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004780 WILL_LJMP(lua_error(L));
4781
Christopher Fauletd1914aa2020-02-24 16:52:46 +01004782 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004783}
4784
4785__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4786{
4787 struct hlua_txn *htxn;
4788
4789 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4790 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4791
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004792 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004793 WILL_LJMP(lua_error(L));
4794
Christopher Fauletd1914aa2020-02-24 16:52:46 +01004795 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004796}
4797
4798__LJMP static int hlua_http_req_rep_val(lua_State *L)
4799{
4800 struct hlua_txn *htxn;
4801
4802 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4803 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4804
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004805 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004806 WILL_LJMP(lua_error(L));
4807
Christopher Fauletd1914aa2020-02-24 16:52:46 +01004808 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004809}
4810
4811__LJMP static int hlua_http_res_rep_val(lua_State *L)
4812{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004813 struct hlua_txn *htxn;
4814
4815 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4816 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4817
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004818 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004819 WILL_LJMP(lua_error(L));
4820
Christopher Fauletd1914aa2020-02-24 16:52:46 +01004821 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004822}
4823
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004824/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004825 * It is a wrapper for the 2 following functions.
4826 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01004827__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004828{
4829 size_t len;
4830 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02004831 struct htx *htx = htxbuf(&msg->chn->buf);
4832 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004833
Christopher Fauleta2097962019-07-15 16:25:33 +02004834 ctx.blk = NULL;
4835 while (http_find_header(htx, ist2(name, len), &ctx, 1))
4836 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004837 return 0;
4838}
4839
4840__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4841{
4842 struct hlua_txn *htxn;
4843
4844 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4845 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4846
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004847 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004848 WILL_LJMP(lua_error(L));
4849
Christopher Fauletd31c7b32020-02-25 09:37:57 +01004850 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004851}
4852
4853__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4854{
4855 struct hlua_txn *htxn;
4856
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004857 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004858 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4859
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004860 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004861 WILL_LJMP(lua_error(L));
4862
Christopher Fauletd31c7b32020-02-25 09:37:57 +01004863 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004864}
4865
4866/* This function adds an header. It is a wrapper used by
4867 * the 2 following functions.
4868 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01004869__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004870{
4871 size_t name_len;
4872 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4873 size_t value_len;
4874 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02004875 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004876
Christopher Fauleta2097962019-07-15 16:25:33 +02004877 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
4878 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004879 return 0;
4880}
4881
4882__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4883{
4884 struct hlua_txn *htxn;
4885
4886 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4887 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4888
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004889 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004890 WILL_LJMP(lua_error(L));
4891
Christopher Fauletd31c7b32020-02-25 09:37:57 +01004892 return hlua_http_add_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004893}
4894
4895__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4896{
4897 struct hlua_txn *htxn;
4898
4899 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4900 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4901
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004902 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004903 WILL_LJMP(lua_error(L));
4904
Christopher Fauletd31c7b32020-02-25 09:37:57 +01004905 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004906}
4907
4908static int hlua_http_req_set_hdr(lua_State *L)
4909{
4910 struct hlua_txn *htxn;
4911
4912 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4913 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4914
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004915 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004916 WILL_LJMP(lua_error(L));
4917
Christopher Fauletd31c7b32020-02-25 09:37:57 +01004918 hlua_http_del_hdr(L, &htxn->s->txn->req);
4919 return hlua_http_add_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004920}
4921
4922static int hlua_http_res_set_hdr(lua_State *L)
4923{
4924 struct hlua_txn *htxn;
4925
4926 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4927 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4928
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004929 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004930 WILL_LJMP(lua_error(L));
4931
Christopher Fauletd31c7b32020-02-25 09:37:57 +01004932 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
4933 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004934}
4935
4936/* This function set the method. */
4937static int hlua_http_req_set_meth(lua_State *L)
4938{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004939 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004940 size_t name_len;
4941 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004942
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004943 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004944 WILL_LJMP(lua_error(L));
4945
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004946 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004947 return 1;
4948}
4949
4950/* This function set the method. */
4951static int hlua_http_req_set_path(lua_State *L)
4952{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004953 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004954 size_t name_len;
4955 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004956
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004957 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004958 WILL_LJMP(lua_error(L));
4959
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004960 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004961 return 1;
4962}
4963
4964/* This function set the query-string. */
4965static int hlua_http_req_set_query(lua_State *L)
4966{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004967 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004968 size_t name_len;
4969 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004970
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004971 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004972 WILL_LJMP(lua_error(L));
4973
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004974 /* Check length. */
4975 if (name_len > trash.size - 1) {
4976 lua_pushboolean(L, 0);
4977 return 1;
4978 }
4979
4980 /* Add the mark question as prefix. */
4981 chunk_reset(&trash);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004982 trash.area[trash.data++] = '?';
4983 memcpy(trash.area + trash.data, name, name_len);
4984 trash.data += name_len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004985
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004986 lua_pushboolean(L,
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004987 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004988 return 1;
4989}
4990
4991/* This function set the uri. */
4992static int hlua_http_req_set_uri(lua_State *L)
4993{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004994 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004995 size_t name_len;
4996 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004997
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004998 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004999 WILL_LJMP(lua_error(L));
5000
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005001 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005002 return 1;
5003}
5004
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005005/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005006static int hlua_http_res_set_status(lua_State *L)
5007{
5008 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5009 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Faulet96bff762019-12-17 13:46:18 +01005010 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5011 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005012
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005013 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005014 WILL_LJMP(lua_error(L));
5015
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005016 http_res_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005017 return 0;
5018}
5019
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005020/*
5021 *
5022 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005023 * Class TXN
5024 *
5025 *
5026 */
5027
5028/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005029 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005030 */
5031__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
5032{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005033 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005034}
5035
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005036__LJMP static int hlua_set_var(lua_State *L)
5037{
5038 struct hlua_txn *htxn;
5039 const char *name;
5040 size_t len;
5041 struct sample smp;
5042
5043 MAY_LJMP(check_args(L, 3, "set_var"));
5044
5045 /* It is useles to retrieve the stream, but this function
5046 * runs only in a stream context.
5047 */
5048 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5049 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5050
5051 /* Converts the third argument in a sample. */
5052 hlua_lua2smp(L, 3, &smp);
5053
5054 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005055 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005056 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005057 return 0;
5058}
5059
Christopher Faulet85d79c92016-11-09 16:54:56 +01005060__LJMP static int hlua_unset_var(lua_State *L)
5061{
5062 struct hlua_txn *htxn;
5063 const char *name;
5064 size_t len;
5065 struct sample smp;
5066
5067 MAY_LJMP(check_args(L, 2, "unset_var"));
5068
5069 /* It is useles to retrieve the stream, but this function
5070 * runs only in a stream context.
5071 */
5072 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5073 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5074
5075 /* Unset the variable. */
5076 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
5077 vars_unset_by_name(name, len, &smp);
5078 return 0;
5079}
5080
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005081__LJMP static int hlua_get_var(lua_State *L)
5082{
5083 struct hlua_txn *htxn;
5084 const char *name;
5085 size_t len;
5086 struct sample smp;
5087
5088 MAY_LJMP(check_args(L, 2, "get_var"));
5089
5090 /* It is useles to retrieve the stream, but this function
5091 * runs only in a stream context.
5092 */
5093 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5094 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5095
Willy Tarreau7560dd42016-03-10 16:28:58 +01005096 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005097 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005098 lua_pushnil(L);
5099 return 1;
5100 }
5101
5102 return hlua_smp2lua(L, &smp);
5103}
5104
Willy Tarreau59551662015-03-10 14:23:13 +01005105__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005106{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005107 struct hlua *hlua;
5108
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005109 MAY_LJMP(check_args(L, 2, "set_priv"));
5110
Willy Tarreau87b09662015-04-03 00:22:06 +02005111 /* It is useles to retrieve the stream, but this function
5112 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005113 */
5114 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005115 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005116
5117 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005118 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005119
5120 /* Get and store new value. */
5121 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5122 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5123
5124 return 0;
5125}
5126
Willy Tarreau59551662015-03-10 14:23:13 +01005127__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005128{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005129 struct hlua *hlua;
5130
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005131 MAY_LJMP(check_args(L, 1, "get_priv"));
5132
Willy Tarreau87b09662015-04-03 00:22:06 +02005133 /* It is useles to retrieve the stream, but this function
5134 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005135 */
5136 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005137 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005138
5139 /* Push configuration index in the stack. */
5140 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5141
5142 return 1;
5143}
5144
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005145/* Create stack entry containing a class TXN. This function
5146 * return 0 if the stack does not contains free slots,
5147 * otherwise it returns 1.
5148 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005149static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005150{
Willy Tarreaude491382015-04-06 11:04:28 +02005151 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005152
5153 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005154 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005155 return 0;
5156
5157 /* NOTE: The allocation never fails. The failure
5158 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005159 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005160 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005161 /* Create the object: obj[0] = userdata. */
5162 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005163 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005164 lua_rawseti(L, -2, 0);
5165
Willy Tarreaude491382015-04-06 11:04:28 +02005166 htxn->s = s;
5167 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005168 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005169 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005170
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005171 /* Create the "f" field that contains a list of fetches. */
5172 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005173 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005174 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005175 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005176
5177 /* Create the "sf" field that contains a list of stringsafe fetches. */
5178 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005179 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005180 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005181 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005182
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005183 /* Create the "c" field that contains a list of converters. */
5184 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005185 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005186 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005187 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005188
5189 /* Create the "sc" field that contains a list of stringsafe converters. */
5190 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005191 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005192 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005193 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005194
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005195 /* Create the "req" field that contains the request channel object. */
5196 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005197 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005198 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005199 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005200
5201 /* Create the "res" field that contains the response channel object. */
5202 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005203 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005204 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005205 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005206
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005207 /* Creates the HTTP object is the current proxy allows http. */
5208 lua_pushstring(L, "http");
5209 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005210 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005211 return 0;
5212 }
5213 else
5214 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005215 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005216
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005217 /* Pop a class sesison metatable and affect it to the userdata. */
5218 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5219 lua_setmetatable(L, -2);
5220
5221 return 1;
5222}
5223
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005224__LJMP static int hlua_txn_deflog(lua_State *L)
5225{
5226 const char *msg;
5227 struct hlua_txn *htxn;
5228
5229 MAY_LJMP(check_args(L, 2, "deflog"));
5230 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5231 msg = MAY_LJMP(luaL_checkstring(L, 2));
5232
5233 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5234 return 0;
5235}
5236
5237__LJMP static int hlua_txn_log(lua_State *L)
5238{
5239 int level;
5240 const char *msg;
5241 struct hlua_txn *htxn;
5242
5243 MAY_LJMP(check_args(L, 3, "log"));
5244 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5245 level = MAY_LJMP(luaL_checkinteger(L, 2));
5246 msg = MAY_LJMP(luaL_checkstring(L, 3));
5247
5248 if (level < 0 || level >= NB_LOG_LEVELS)
5249 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5250
5251 hlua_sendlog(htxn->s->be, level, msg);
5252 return 0;
5253}
5254
5255__LJMP static int hlua_txn_log_debug(lua_State *L)
5256{
5257 const char *msg;
5258 struct hlua_txn *htxn;
5259
5260 MAY_LJMP(check_args(L, 2, "Debug"));
5261 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5262 msg = MAY_LJMP(luaL_checkstring(L, 2));
5263 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5264 return 0;
5265}
5266
5267__LJMP static int hlua_txn_log_info(lua_State *L)
5268{
5269 const char *msg;
5270 struct hlua_txn *htxn;
5271
5272 MAY_LJMP(check_args(L, 2, "Info"));
5273 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5274 msg = MAY_LJMP(luaL_checkstring(L, 2));
5275 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5276 return 0;
5277}
5278
5279__LJMP static int hlua_txn_log_warning(lua_State *L)
5280{
5281 const char *msg;
5282 struct hlua_txn *htxn;
5283
5284 MAY_LJMP(check_args(L, 2, "Warning"));
5285 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5286 msg = MAY_LJMP(luaL_checkstring(L, 2));
5287 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5288 return 0;
5289}
5290
5291__LJMP static int hlua_txn_log_alert(lua_State *L)
5292{
5293 const char *msg;
5294 struct hlua_txn *htxn;
5295
5296 MAY_LJMP(check_args(L, 2, "Alert"));
5297 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5298 msg = MAY_LJMP(luaL_checkstring(L, 2));
5299 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5300 return 0;
5301}
5302
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005303__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5304{
5305 struct hlua_txn *htxn;
5306 int ll;
5307
5308 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5309 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5310 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5311
5312 if (ll < 0 || ll > 7)
5313 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5314
5315 htxn->s->logs.level = ll;
5316 return 0;
5317}
5318
5319__LJMP static int hlua_txn_set_tos(lua_State *L)
5320{
5321 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005322 int tos;
5323
5324 MAY_LJMP(check_args(L, 2, "set_tos"));
5325 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5326 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5327
Willy Tarreau1a18b542018-12-11 16:37:42 +01005328 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005329 return 0;
5330}
5331
5332__LJMP static int hlua_txn_set_mark(lua_State *L)
5333{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005334 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005335 int mark;
5336
5337 MAY_LJMP(check_args(L, 2, "set_mark"));
5338 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5339 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5340
Lukas Tribus579e3e32019-08-11 18:03:45 +02005341 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005342 return 0;
5343}
5344
Patrick Hemmer268a7072018-05-11 12:52:31 -04005345__LJMP static int hlua_txn_set_priority_class(lua_State *L)
5346{
5347 struct hlua_txn *htxn;
5348
5349 MAY_LJMP(check_args(L, 2, "set_priority_class"));
5350 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5351 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
5352 return 0;
5353}
5354
5355__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
5356{
5357 struct hlua_txn *htxn;
5358
5359 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
5360 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5361 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
5362 return 0;
5363}
5364
Christopher Faulet700d9e82020-01-31 12:21:52 +01005365/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005366 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01005367 * message and terminate the transaction. It returns 1 on success and 0 on
5368 * error. The Reply must be on top of the stack.
5369 */
5370__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
5371{
5372 struct htx *htx;
5373 struct htx_sl *sl;
5374 struct h1m h1m;
5375 const char *status, *reason, *body;
5376 size_t status_len, reason_len, body_len;
5377 int ret, code, flags;
5378
5379 code = 200;
5380 status = "200";
5381 status_len = 3;
5382 ret = lua_getfield(L, -1, "status");
5383 if (ret == LUA_TNUMBER) {
5384 code = lua_tointeger(L, -1);
5385 status = lua_tolstring(L, -1, &status_len);
5386 }
5387 lua_pop(L, 1);
5388
5389 reason = http_get_reason(code);
5390 reason_len = strlen(reason);
5391 ret = lua_getfield(L, -1, "reason");
5392 if (ret == LUA_TSTRING)
5393 reason = lua_tolstring(L, -1, &reason_len);
5394 lua_pop(L, 1);
5395
5396 body = NULL;
5397 body_len = 0;
5398 ret = lua_getfield(L, -1, "body");
5399 if (ret == LUA_TSTRING)
5400 body = lua_tolstring(L, -1, &body_len);
5401 lua_pop(L, 1);
5402
5403 /* Prepare the response before inserting the headers */
5404 h1m_init_res(&h1m);
5405 htx = htx_from_buf(&s->res.buf);
5406 channel_htx_truncate(&s->res, htx);
5407 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
5408 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5409 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
5410 ist2(status, status_len), ist2(reason, reason_len));
5411 }
5412 else {
5413 flags = HTX_SL_F_IS_RESP;
5414 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
5415 ist2(status, status_len), ist2(reason, reason_len));
5416 }
5417 if (!sl)
5418 goto fail;
5419 sl->info.res.status = code;
5420
5421 /* Push in the stack the "headers" entry. */
5422 ret = lua_getfield(L, -1, "headers");
5423 if (ret != LUA_TTABLE)
5424 goto skip_headers;
5425
5426 lua_pushnil(L);
5427 while (lua_next(L, -2) != 0) {
5428 struct ist name, value;
5429 const char *n, *v;
5430 size_t nlen, vlen;
5431
5432 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
5433 /* Skip element if the key is not a string or if the value is not a table */
5434 goto next_hdr;
5435 }
5436
5437 n = lua_tolstring(L, -2, &nlen);
5438 name = ist2(n, nlen);
5439 if (isteqi(name, ist("content-length"))) {
5440 /* Always skip content-length header. It will be added
5441 * later with the correct len
5442 */
5443 goto next_hdr;
5444 }
5445
5446 /* Loop on header's values */
5447 lua_pushnil(L);
5448 while (lua_next(L, -2)) {
5449 if (!lua_isstring(L, -1)) {
5450 /* Skip the value if it is not a string */
5451 goto next_value;
5452 }
5453
5454 v = lua_tolstring(L, -1, &vlen);
5455 value = ist2(v, vlen);
5456
5457 if (isteqi(name, ist("transfer-encoding")))
5458 h1_parse_xfer_enc_header(&h1m, value);
5459 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
5460 goto fail;
5461
5462 next_value:
5463 lua_pop(L, 1);
5464 }
5465
5466 next_hdr:
5467 lua_pop(L, 1);
5468 }
5469 skip_headers:
5470 lua_pop(L, 1);
5471
5472 /* Update h1m flags: CLEN is set if CHNK is not present */
5473 if (!(h1m.flags & H1_MF_CHNK)) {
5474 const char *clen = ultoa(body_len);
5475
5476 h1m.flags |= H1_MF_CLEN;
5477 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
5478 goto fail;
5479 }
5480 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5481 h1m.flags |= H1_MF_XFER_LEN;
5482
5483 /* Update HTX start-line flags */
5484 if (h1m.flags & H1_MF_XFER_ENC)
5485 flags |= HTX_SL_F_XFER_ENC;
5486 if (h1m.flags & H1_MF_XFER_LEN) {
5487 flags |= HTX_SL_F_XFER_LEN;
5488 if (h1m.flags & H1_MF_CHNK)
5489 flags |= HTX_SL_F_CHNK;
5490 else if (h1m.flags & H1_MF_CLEN)
5491 flags |= HTX_SL_F_CLEN;
5492 if (h1m.body_len == 0)
5493 flags |= HTX_SL_F_BODYLESS;
5494 }
5495 sl->flags |= flags;
5496
5497
5498 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
5499 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))) ||
5500 !htx_add_endof(htx, HTX_BLK_EOM))
5501 goto fail;
5502
5503 /* Now, forward the response and terminate the transaction */
5504 s->txn->status = code;
5505 htx_to_buf(htx, &s->res.buf);
5506 if (!http_forward_proxy_resp(s, 1))
5507 goto fail;
5508
5509 return 1;
5510
5511 fail:
5512 channel_htx_truncate(&s->res, htx);
5513 return 0;
5514}
5515
5516/* Terminate a transaction if called from a lua action. For TCP streams,
5517 * processing is just aborted. Nothing is returned to the client and all
5518 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
5519 * is forwarded to the client before terminating the transaction. On success,
5520 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
5521 * with ACT_RET_ERR code. If this function is not called from a lua action, it
5522 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005523 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005524__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005525{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005526 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01005527 struct stream *s;
5528 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005529
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005530 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005531
Christopher Faulet700d9e82020-01-31 12:21:52 +01005532 /* If the flags NOTERM is set, we cannot terminate the session, so we
5533 * just end the execution of the current lua code. */
5534 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005535 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005536
Christopher Faulet700d9e82020-01-31 12:21:52 +01005537 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005538 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01005539 struct channel *req = &s->req;
5540 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005541
Christopher Faulet700d9e82020-01-31 12:21:52 +01005542 channel_auto_read(req);
5543 channel_abort(req);
5544 channel_auto_close(req);
5545 channel_erase(req);
5546
5547 res->wex = tick_add_ifset(now_ms, res->wto);
5548 channel_auto_read(res);
5549 channel_auto_close(res);
5550 channel_shutr_now(res);
5551
5552 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
5553 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02005554 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005555
Christopher Faulet700d9e82020-01-31 12:21:52 +01005556 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
5557 /* No reply or invalid reply */
5558 s->txn->status = 0;
5559 http_reply_and_close(s, 0, NULL);
5560 }
5561 else {
5562 /* Remove extra args to have the reply on top of the stack */
5563 if (lua_gettop(L) > 2)
5564 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005565
Christopher Faulet700d9e82020-01-31 12:21:52 +01005566 if (!hlua_txn_forward_reply(L, s)) {
5567 if (!(s->flags & SF_ERR_MASK))
5568 s->flags |= SF_ERR_PRXCOND;
5569 lua_pushinteger(L, ACT_RET_ERR);
5570 WILL_LJMP(hlua_done(L));
5571 return 0; /* Never reached */
5572 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02005573 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005574
Christopher Faulet700d9e82020-01-31 12:21:52 +01005575 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
5576 if (htxn->dir == SMP_OPT_DIR_REQ) {
5577 /* let's log the request time */
5578 s->logs.tv_request = now;
5579 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
5580 _HA_ATOMIC_ADD(&s->sess->fe->fe_counters.intercepted_req, 1);
5581 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02005582
Christopher Faulet700d9e82020-01-31 12:21:52 +01005583 done:
5584 if (!(s->flags & SF_ERR_MASK))
5585 s->flags |= SF_ERR_LOCAL;
5586 if (!(s->flags & SF_FINST_MASK))
5587 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02005588
Christopher Faulet4ad73102020-03-05 11:07:31 +01005589 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005590 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005591 return 0;
5592}
5593
Christopher Faulet700d9e82020-01-31 12:21:52 +01005594/*
5595 *
5596 *
5597 * Class REPLY
5598 *
5599 *
5600 */
5601
5602/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
5603 * free slots, the function fails and returns 0;
5604 */
5605static int hlua_txn_reply_new(lua_State *L)
5606{
5607 struct hlua_txn *htxn;
5608 const char *reason, *body = NULL;
5609 int ret, status;
5610
5611 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005612 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01005613 hlua_pusherror(L, "txn object is not an HTTP transaction.");
5614 WILL_LJMP(lua_error(L));
5615 }
5616
5617 /* Default value */
5618 status = 200;
5619 reason = http_get_reason(status);
5620
5621 if (lua_istable(L, 2)) {
5622 /* load status and reason from the table argument at index 2 */
5623 ret = lua_getfield(L, 2, "status");
5624 if (ret == LUA_TNIL)
5625 goto reason;
5626 else if (ret != LUA_TNUMBER) {
5627 /* invalid status: ignore the reason */
5628 goto body;
5629 }
5630 status = lua_tointeger(L, -1);
5631
5632 reason:
5633 lua_pop(L, 1); /* restore the stack: remove status */
5634 ret = lua_getfield(L, 2, "reason");
5635 if (ret == LUA_TSTRING)
5636 reason = lua_tostring(L, -1);
5637
5638 body:
5639 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
5640 ret = lua_getfield(L, 2, "body");
5641 if (ret == LUA_TSTRING)
5642 body = lua_tostring(L, -1);
5643 lua_pop(L, 1); /* restore the stack: remove body */
5644 }
5645
5646 /* Create the Reply table */
5647 lua_newtable(L);
5648
5649 /* Add status element */
5650 lua_pushstring(L, "status");
5651 lua_pushinteger(L, status);
5652 lua_settable(L, -3);
5653
5654 /* Add reason element */
5655 reason = http_get_reason(status);
5656 lua_pushstring(L, "reason");
5657 lua_pushstring(L, reason);
5658 lua_settable(L, -3);
5659
5660 /* Add body element, nil if undefined */
5661 lua_pushstring(L, "body");
5662 if (body)
5663 lua_pushstring(L, body);
5664 else
5665 lua_pushnil(L);
5666 lua_settable(L, -3);
5667
5668 /* Add headers element */
5669 lua_pushstring(L, "headers");
5670 lua_newtable(L);
5671
5672 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
5673 if (lua_istable(L, 2)) {
5674 /* load headers from the table argument at index 2. If it is a table, copy it. */
5675 ret = lua_getfield(L, 2, "headers");
5676 if (ret == LUA_TTABLE) {
5677 /* stack: [ ... <headers:table>, <table> ] */
5678 lua_pushnil(L);
5679 while (lua_next(L, -2) != 0) {
5680 /* stack: [ ... <headers:table>, <table>, k, v] */
5681 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
5682 /* invalid value type, skip it */
5683 lua_pop(L, 1);
5684 continue;
5685 }
5686
5687
5688 /* Duplicate the key and swap it with the value. */
5689 lua_pushvalue(L, -2);
5690 lua_insert(L, -2);
5691 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
5692
5693 lua_newtable(L);
5694 lua_insert(L, -2);
5695 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
5696
5697 if (lua_isstring(L, -1)) {
5698 /* push the value in the inner table */
5699 lua_rawseti(L, -2, 1);
5700 }
5701 else { /* table */
5702 lua_pushnil(L);
5703 while (lua_next(L, -2) != 0) {
5704 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
5705 if (!lua_isstring(L, -1)) {
5706 /* invalid value type, skip it*/
5707 lua_pop(L, 1);
5708 continue;
5709 }
5710 /* push the value in the inner table */
5711 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
5712 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
5713 }
5714 lua_pop(L, 1);
5715 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
5716 }
5717
5718 /* push (k,v) on the stack in the headers table:
5719 * stack: [ ... <headers:table>, <table>, k, k, v ]
5720 */
5721 lua_settable(L, -5);
5722 /* stack: [ ... <headers:table>, <table>, k ] */
5723 }
5724 }
5725 lua_pop(L, 1);
5726 }
5727 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
5728 lua_settable(L, -3);
5729 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
5730
5731 /* Pop a class sesison metatable and affect it to the userdata. */
5732 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
5733 lua_setmetatable(L, -2);
5734 return 1;
5735}
5736
5737/* Set the reply status code, and optionally the reason. If no reason is
5738 * provided, the default one corresponding to the status code is used.
5739 */
5740__LJMP static int hlua_txn_reply_set_status(lua_State *L)
5741{
5742 int status = MAY_LJMP(luaL_checkinteger(L, 2));
5743 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5744
5745 /* First argument (self) must be a table */
5746 luaL_checktype(L, 1, LUA_TTABLE);
5747
5748 if (status < 100 || status > 599) {
5749 lua_pushboolean(L, 0);
5750 return 1;
5751 }
5752 if (!reason)
5753 reason = http_get_reason(status);
5754
5755 lua_pushinteger(L, status);
5756 lua_setfield(L, 1, "status");
5757
5758 lua_pushstring(L, reason);
5759 lua_setfield(L, 1, "reason");
5760
5761 lua_pushboolean(L, 1);
5762 return 1;
5763}
5764
5765/* Add a header into the reply object. Each header name is associated to an
5766 * array of values in the "headers" table. If the header name is not found, a
5767 * new entry is created.
5768 */
5769__LJMP static int hlua_txn_reply_add_header(lua_State *L)
5770{
5771 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
5772 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
5773 int ret;
5774
5775 /* First argument (self) must be a table */
5776 luaL_checktype(L, 1, LUA_TTABLE);
5777
5778 /* Push in the stack the "headers" entry. */
5779 ret = lua_getfield(L, 1, "headers");
5780 if (ret != LUA_TTABLE) {
5781 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
5782 WILL_LJMP(lua_error(L));
5783 }
5784
5785 /* check if the header is already registered. If not, register it. */
5786 ret = lua_getfield(L, -1, name);
5787 if (ret == LUA_TNIL) {
5788 /* Entry not found. */
5789 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
5790
5791 /* Insert the new header name in the array in the top of the stack.
5792 * It left the new array in the top of the stack.
5793 */
5794 lua_newtable(L);
5795 lua_pushstring(L, name);
5796 lua_pushvalue(L, -2);
5797 lua_settable(L, -4);
5798 }
5799 else if (ret != LUA_TTABLE) {
5800 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
5801 WILL_LJMP(lua_error(L));
5802 }
5803
5804 /* Now the top od thestack is an array of values. We push
5805 * the header value as new entry.
5806 */
5807 lua_pushstring(L, value);
5808 ret = lua_rawlen(L, -2);
5809 lua_rawseti(L, -2, ret + 1);
5810
5811 lua_pushboolean(L, 1);
5812 return 1;
5813}
5814
5815/* Remove all occurrences of a given header name. */
5816__LJMP static int hlua_txn_reply_del_header(lua_State *L)
5817{
5818 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
5819 int ret;
5820
5821 /* First argument (self) must be a table */
5822 luaL_checktype(L, 1, LUA_TTABLE);
5823
5824 /* Push in the stack the "headers" entry. */
5825 ret = lua_getfield(L, 1, "headers");
5826 if (ret != LUA_TTABLE) {
5827 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
5828 WILL_LJMP(lua_error(L));
5829 }
5830
5831 lua_pushstring(L, name);
5832 lua_pushnil(L);
5833 lua_settable(L, -3);
5834
5835 lua_pushboolean(L, 1);
5836 return 1;
5837}
5838
5839/* Set the reply's body. Overwrite any existing entry. */
5840__LJMP static int hlua_txn_reply_set_body(lua_State *L)
5841{
5842 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
5843
5844 /* First argument (self) must be a table */
5845 luaL_checktype(L, 1, LUA_TTABLE);
5846
5847 lua_pushstring(L, payload);
5848 lua_setfield(L, 1, "body");
5849
5850 lua_pushboolean(L, 1);
5851 return 1;
5852}
5853
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005854__LJMP static int hlua_log(lua_State *L)
5855{
5856 int level;
5857 const char *msg;
5858
5859 MAY_LJMP(check_args(L, 2, "log"));
5860 level = MAY_LJMP(luaL_checkinteger(L, 1));
5861 msg = MAY_LJMP(luaL_checkstring(L, 2));
5862
5863 if (level < 0 || level >= NB_LOG_LEVELS)
5864 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5865
5866 hlua_sendlog(NULL, level, msg);
5867 return 0;
5868}
5869
5870__LJMP static int hlua_log_debug(lua_State *L)
5871{
5872 const char *msg;
5873
5874 MAY_LJMP(check_args(L, 1, "debug"));
5875 msg = MAY_LJMP(luaL_checkstring(L, 1));
5876 hlua_sendlog(NULL, LOG_DEBUG, msg);
5877 return 0;
5878}
5879
5880__LJMP static int hlua_log_info(lua_State *L)
5881{
5882 const char *msg;
5883
5884 MAY_LJMP(check_args(L, 1, "info"));
5885 msg = MAY_LJMP(luaL_checkstring(L, 1));
5886 hlua_sendlog(NULL, LOG_INFO, msg);
5887 return 0;
5888}
5889
5890__LJMP static int hlua_log_warning(lua_State *L)
5891{
5892 const char *msg;
5893
5894 MAY_LJMP(check_args(L, 1, "warning"));
5895 msg = MAY_LJMP(luaL_checkstring(L, 1));
5896 hlua_sendlog(NULL, LOG_WARNING, msg);
5897 return 0;
5898}
5899
5900__LJMP static int hlua_log_alert(lua_State *L)
5901{
5902 const char *msg;
5903
5904 MAY_LJMP(check_args(L, 1, "alert"));
5905 msg = MAY_LJMP(luaL_checkstring(L, 1));
5906 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005907 return 0;
5908}
5909
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005910__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005911{
5912 int wakeup_ms = lua_tointeger(L, -1);
5913 if (now_ms < wakeup_ms)
Willy Tarreau9635e032018-10-16 17:52:55 +02005914 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005915 return 0;
5916}
5917
5918__LJMP static int hlua_sleep(lua_State *L)
5919{
5920 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005921 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005922
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005923 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005924
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005925 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005926 wakeup_ms = tick_add(now_ms, delay);
5927 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005928
Willy Tarreau9635e032018-10-16 17:52:55 +02005929 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005930 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005931}
5932
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005933__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005934{
5935 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005936 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005937
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005938 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005939
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005940 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005941 wakeup_ms = tick_add(now_ms, delay);
5942 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005943
Willy Tarreau9635e032018-10-16 17:52:55 +02005944 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005945 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005946}
5947
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005948/* This functionis an LUA binding. it permits to give back
5949 * the hand at the HAProxy scheduler. It is used when the
5950 * LUA processing consumes a lot of time.
5951 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005952__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005953{
5954 return 0;
5955}
5956
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005957__LJMP static int hlua_yield(lua_State *L)
5958{
Willy Tarreau9635e032018-10-16 17:52:55 +02005959 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005960 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005961}
5962
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005963/* This function change the nice of the currently executed
5964 * task. It is used set low or high priority at the current
5965 * task.
5966 */
Willy Tarreau59551662015-03-10 14:23:13 +01005967__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005968{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005969 struct hlua *hlua;
5970 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005971
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005972 MAY_LJMP(check_args(L, 1, "set_nice"));
5973 hlua = hlua_gethlua(L);
5974 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005975
5976 /* If he task is not set, I'm in a start mode. */
5977 if (!hlua || !hlua->task)
5978 return 0;
5979
5980 if (nice < -1024)
5981 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005982 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005983 nice = 1024;
5984
5985 hlua->task->nice = nice;
5986 return 0;
5987}
5988
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005989/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005990 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5991 * return an E_AGAIN signal, the emmiter of this signal must set a
5992 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005993 *
5994 * Task wrapper are longjmp safe because the only one Lua code
5995 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005996 */
Willy Tarreau60409db2019-08-21 14:14:50 +02005997struct task *hlua_process_task(struct task *task, void *context, unsigned short state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005998{
Olivier Houchard9f6af332018-05-25 14:04:04 +02005999 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006000 enum hlua_exec status;
6001
Christopher Faulet5bc99722018-04-25 10:34:45 +02006002 if (task->thread_mask == MAX_THREADS_MASK)
6003 task_set_affinity(task, tid_bit);
6004
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006005 /* If it is the first call to the task, we must initialize the
6006 * execution timeouts.
6007 */
6008 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006009 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006010
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006011 /* Execute the Lua code. */
6012 status = hlua_ctx_resume(hlua, 1);
6013
6014 switch (status) {
6015 /* finished or yield */
6016 case HLUA_E_OK:
6017 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006018 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02006019 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006020 break;
6021
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006022 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01006023 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02006024 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006025 break;
6026
6027 /* finished with error. */
6028 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006029 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006030 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006031 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006032 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006033 break;
6034
6035 case HLUA_E_ERR:
6036 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006037 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006038 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006039 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006040 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006041 break;
6042 }
Emeric Brun253e53e2017-10-17 18:58:40 +02006043 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006044}
6045
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006046/* This function is an LUA binding that register LUA function to be
6047 * executed after the HAProxy configuration parsing and before the
6048 * HAProxy scheduler starts. This function expect only one LUA
6049 * argument that is a function. This function returns nothing, but
6050 * throws if an error is encountered.
6051 */
6052__LJMP static int hlua_register_init(lua_State *L)
6053{
6054 struct hlua_init_function *init;
6055 int ref;
6056
6057 MAY_LJMP(check_args(L, 1, "register_init"));
6058
6059 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6060
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006061 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006062 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006063 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006064
6065 init->function_ref = ref;
6066 LIST_ADDQ(&hlua_init_functions, &init->l);
6067 return 0;
6068}
6069
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006070/* This functio is an LUA binding. It permits to register a task
6071 * executed in parallel of the main HAroxy activity. The task is
6072 * created and it is set in the HAProxy scheduler. It can be called
6073 * from the "init" section, "post init" or during the runtime.
6074 *
6075 * Lua prototype:
6076 *
6077 * <none> core.register_task(<function>)
6078 */
6079static int hlua_register_task(lua_State *L)
6080{
6081 struct hlua *hlua;
6082 struct task *task;
6083 int ref;
6084
6085 MAY_LJMP(check_args(L, 1, "register_task"));
6086
6087 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6088
Willy Tarreaubafbe012017-11-24 17:34:44 +01006089 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006090 if (!hlua)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006091 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006092
Emeric Brunc60def82017-09-27 14:59:38 +02006093 task = task_new(MAX_THREADS_MASK);
Willy Tarreaue09101e2018-10-16 17:37:12 +02006094 if (!task)
6095 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
6096
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006097 task->context = hlua;
6098 task->process = hlua_process_task;
6099
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006100 if (!hlua_ctx_init(hlua, task, 1))
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006101 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006102
6103 /* Restore the function in the stack. */
6104 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
6105 hlua->nargs = 0;
6106
6107 /* Schedule task. */
6108 task_schedule(task, now_ms);
6109
6110 return 0;
6111}
6112
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006113/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
6114 * doesn't allow "yield" functions because the HAProxy engine cannot
6115 * resume converters.
6116 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006117static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006118{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006119 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006120 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006121 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006122
Willy Tarreaube508f12016-03-10 11:47:01 +01006123 if (!stream)
6124 return 0;
6125
Willy Tarreau87b09662015-04-03 00:22:06 +02006126 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006127 * Lua context can be not initialized. This behavior
6128 * permits to save performances because a systematic
6129 * Lua initialization cause 5% performances loss.
6130 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006131 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006132 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006133 if (!stream->hlua) {
6134 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6135 return 0;
6136 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006137 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006138 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6139 return 0;
6140 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006141 }
6142
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006143 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006144 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006145
6146 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006147 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6148 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6149 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006150 else
6151 error = "critical error";
6152 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006153 return 0;
6154 }
6155
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006156 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006157 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006158 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006159 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006160 return 0;
6161 }
6162
6163 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006164 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006165
6166 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006167 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006168 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006169 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006170 return 0;
6171 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006172 hlua_smp2lua(stream->hlua->T, smp);
6173 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006174
6175 /* push keywords in the stack. */
6176 if (arg_p) {
6177 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006178 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006179 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006180 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006181 return 0;
6182 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006183 hlua_arg2lua(stream->hlua->T, arg_p);
6184 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006185 }
6186 }
6187
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006188 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006189 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006190
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006191 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006192 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006193 }
6194
6195 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006196 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006197 /* finished. */
6198 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006199 /* If the stack is empty, the function fails. */
6200 if (lua_gettop(stream->hlua->T) <= 0)
6201 return 0;
6202
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006203 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006204 hlua_lua2smp(stream->hlua->T, -1, smp);
6205 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006206 return 1;
6207
6208 /* yield. */
6209 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006210 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006211 return 0;
6212
6213 /* finished with error. */
6214 case HLUA_E_ERRMSG:
6215 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006216 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006217 fcn->name, lua_tostring(stream->hlua->T, -1));
6218 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006219 return 0;
6220
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006221 case HLUA_E_ETMOUT:
6222 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
6223 return 0;
6224
6225 case HLUA_E_NOMEM:
6226 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
6227 return 0;
6228
6229 case HLUA_E_YIELD:
6230 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
6231 return 0;
6232
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006233 case HLUA_E_ERR:
6234 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006235 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006236
6237 default:
6238 return 0;
6239 }
6240}
6241
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006242/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
6243 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01006244 * resume sample-fetches. This function will be called by the sample
6245 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006246 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02006247static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
6248 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006249{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006250 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006251 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006252 const char *error;
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006253 unsigned int hflags = HLUA_TXN_NOTERM;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006254
Willy Tarreaube508f12016-03-10 11:47:01 +01006255 if (!stream)
6256 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01006257
Willy Tarreau87b09662015-04-03 00:22:06 +02006258 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006259 * Lua context can be not initialized. This behavior
6260 * permits to save performances because a systematic
6261 * Lua initialization cause 5% performances loss.
6262 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006263 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006264 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006265 if (!stream->hlua) {
6266 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6267 return 0;
6268 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006269 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006270 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6271 return 0;
6272 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006273 }
6274
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006275 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006276 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006277
6278 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006279 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6280 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6281 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006282 else
6283 error = "critical error";
6284 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006285 return 0;
6286 }
6287
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006288 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006289 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006290 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006291 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006292 return 0;
6293 }
6294
6295 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006296 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006297
6298 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006299 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006300 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006301 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006302 return 0;
6303 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006304 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006305
6306 /* push keywords in the stack. */
6307 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
6308 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006309 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006310 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006311 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006312 return 0;
6313 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006314 hlua_arg2lua(stream->hlua->T, arg_p);
6315 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006316 }
6317
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006318 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006319 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006320
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006321 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006322 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006323 }
6324
6325 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006326 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006327 /* finished. */
6328 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006329 /* If the stack is empty, the function fails. */
6330 if (lua_gettop(stream->hlua->T) <= 0)
6331 return 0;
6332
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006333 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006334 hlua_lua2smp(stream->hlua->T, -1, smp);
6335 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006336
6337 /* Set the end of execution flag. */
6338 smp->flags &= ~SMP_F_MAY_CHANGE;
6339 return 1;
6340
6341 /* yield. */
6342 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006343 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006344 return 0;
6345
6346 /* finished with error. */
6347 case HLUA_E_ERRMSG:
6348 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006349 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006350 fcn->name, lua_tostring(stream->hlua->T, -1));
6351 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006352 return 0;
6353
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006354 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006355 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
6356 return 0;
6357
6358 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006359 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
6360 return 0;
6361
6362 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006363 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
6364 return 0;
6365
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006366 case HLUA_E_ERR:
6367 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006368 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006369
6370 default:
6371 return 0;
6372 }
6373}
6374
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006375/* This function is an LUA binding used for registering
6376 * "sample-conv" functions. It expects a converter name used
6377 * in the haproxy configuration file, and an LUA function.
6378 */
6379__LJMP static int hlua_register_converters(lua_State *L)
6380{
6381 struct sample_conv_kw_list *sck;
6382 const char *name;
6383 int ref;
6384 int len;
6385 struct hlua_function *fcn;
6386
6387 MAY_LJMP(check_args(L, 2, "register_converters"));
6388
6389 /* First argument : converter name. */
6390 name = MAY_LJMP(luaL_checkstring(L, 1));
6391
6392 /* Second argument : lua function. */
6393 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6394
6395 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006396 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006397 if (!sck)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006398 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006399 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006400 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006401 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006402
6403 /* Fill fcn. */
6404 fcn->name = strdup(name);
6405 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006406 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006407 fcn->function_ref = ref;
6408
6409 /* List head */
6410 sck->list.n = sck->list.p = NULL;
6411
6412 /* converter keyword. */
6413 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006414 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006415 if (!sck->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006416 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006417
6418 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
6419 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006420 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 +01006421 sck->kw[0].val_args = NULL;
6422 sck->kw[0].in_type = SMP_T_STR;
6423 sck->kw[0].out_type = SMP_T_STR;
6424 sck->kw[0].private = fcn;
6425
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006426 /* Register this new converter */
6427 sample_register_convs(sck);
6428
6429 return 0;
6430}
6431
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006432/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006433 * "sample-fetch" functions. It expects a converter name used
6434 * in the haproxy configuration file, and an LUA function.
6435 */
6436__LJMP static int hlua_register_fetches(lua_State *L)
6437{
6438 const char *name;
6439 int ref;
6440 int len;
6441 struct sample_fetch_kw_list *sfk;
6442 struct hlua_function *fcn;
6443
6444 MAY_LJMP(check_args(L, 2, "register_fetches"));
6445
6446 /* First argument : sample-fetch name. */
6447 name = MAY_LJMP(luaL_checkstring(L, 1));
6448
6449 /* Second argument : lua function. */
6450 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6451
6452 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006453 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006454 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006455 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006456 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006457 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006458 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006459
6460 /* Fill fcn. */
6461 fcn->name = strdup(name);
6462 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006463 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006464 fcn->function_ref = ref;
6465
6466 /* List head */
6467 sfk->list.n = sfk->list.p = NULL;
6468
6469 /* sample-fetch keyword. */
6470 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006471 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006472 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006473 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006474
6475 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
6476 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006477 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 +01006478 sfk->kw[0].val_args = NULL;
6479 sfk->kw[0].out_type = SMP_T_STR;
6480 sfk->kw[0].use = SMP_USE_HTTP_ANY;
6481 sfk->kw[0].val = 0;
6482 sfk->kw[0].private = fcn;
6483
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006484 /* Register this new fetch. */
6485 sample_register_fetches(sfk);
6486
6487 return 0;
6488}
6489
Christopher Faulet501465d2020-02-26 14:54:16 +01006490/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01006491 */
Christopher Faulet501465d2020-02-26 14:54:16 +01006492__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01006493{
6494 struct hlua *hlua = hlua_gethlua(L);
6495 unsigned int delay;
6496 unsigned int wakeup_ms;
6497
6498 MAY_LJMP(check_args(L, 1, "wake_time"));
6499
6500 delay = MAY_LJMP(luaL_checkinteger(L, 1));
6501 wakeup_ms = tick_add(now_ms, delay);
6502 hlua->wake_time = wakeup_ms;
6503 return 0;
6504}
6505
6506
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006507/* This function is a wrapper to execute each LUA function declared as an action
6508 * wrapper during the initialisation period. This function may return any
6509 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
6510 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
6511 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006512 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006513static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006514 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006515{
6516 char **arg;
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006517 unsigned int hflags = 0;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006518 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006519 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006520
6521 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006522 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
6523 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
6524 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
6525 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006526 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006527 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006528 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006529 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006530
Willy Tarreau87b09662015-04-03 00:22:06 +02006531 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006532 * Lua context can be not initialized. This behavior
6533 * permits to save performances because a systematic
6534 * Lua initialization cause 5% performances loss.
6535 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006536 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006537 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006538 if (!s->hlua) {
6539 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6540 rule->arg.hlua_rule->fcn.name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006541 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006542 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006543 if (!hlua_ctx_init(s->hlua, s->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006544 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6545 rule->arg.hlua_rule->fcn.name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006546 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006547 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006548 }
6549
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006550 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006551 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006552
6553 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006554 if (!SET_SAFE_LJMP(s->hlua->T)) {
6555 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6556 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006557 else
6558 error = "critical error";
6559 SEND_ERR(px, "Lua function '%s': %s.\n",
6560 rule->arg.hlua_rule->fcn.name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006561 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006562 }
6563
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006564 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006565 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006566 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006567 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006568 RESET_SAFE_LJMP(s->hlua->T);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006569 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006570 }
6571
6572 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006573 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006574
Willy Tarreau87b09662015-04-03 00:22:06 +02006575 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006576 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006577 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006578 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006579 RESET_SAFE_LJMP(s->hlua->T);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006580 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006581 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006582 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006583
6584 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006585 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006586 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006587 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006588 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006589 RESET_SAFE_LJMP(s->hlua->T);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006590 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006591 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006592 lua_pushstring(s->hlua->T, *arg);
6593 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006594 }
6595
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006596 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006597 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006598
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006599 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006600 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006601 }
6602
6603 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01006604 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006605 /* finished. */
6606 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006607 /* Catch the return value */
6608 if (lua_gettop(s->hlua->T) > 0)
6609 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006610
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01006611 /* Set timeout in the required channel. */
6612 if (act_ret == ACT_RET_YIELD && s->hlua->wake_time != TICK_ETERNITY) {
6613 if (dir == SMP_OPT_DIR_REQ)
6614 s->req.analyse_exp = s->hlua->wake_time;
6615 else
6616 s->res.analyse_exp = s->hlua->wake_time;
6617 }
6618 goto end;
6619
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006620 /* yield. */
6621 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006622 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006623 if (s->hlua->wake_time != TICK_ETERNITY) {
Christopher Faulet81921b12019-08-14 23:19:45 +02006624 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006625 s->req.analyse_exp = s->hlua->wake_time;
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006626 else
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006627 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006628 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006629 /* Some actions can be wake up when a "write" event
6630 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006631 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006632 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02006633 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006634 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006635 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006636 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006637 act_ret = ACT_RET_YIELD;
6638 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006639
6640 /* finished with error. */
6641 case HLUA_E_ERRMSG:
6642 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006643 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006644 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6645 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006646 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006647
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006648 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006649 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn.name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006650 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006651
6652 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006653 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn.name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006654 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006655
6656 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006657 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
6658 rule->arg.hlua_rule->fcn.name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006659 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006660
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006661 case HLUA_E_ERR:
6662 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006663 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006664 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006665
6666 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006667 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006668 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006669
6670 end:
6671 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006672}
6673
Olivier Houchard9f6af332018-05-25 14:04:04 +02006674struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned short state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006675{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006676 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006677
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006678 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006679 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006680 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006681}
6682
6683static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6684{
6685 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006686 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006687 struct task *task;
6688 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006689 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006690
Willy Tarreaubafbe012017-11-24 17:34:44 +01006691 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006692 if (!hlua) {
6693 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6694 ctx->rule->arg.hlua_rule->fcn.name);
6695 return 0;
6696 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006697 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006698 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006699 ctx->ctx.hlua_apptcp.flags = 0;
6700
6701 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006702 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006703 if (!task) {
6704 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6705 ctx->rule->arg.hlua_rule->fcn.name);
6706 return 0;
6707 }
6708 task->nice = 0;
6709 task->context = ctx;
6710 task->process = hlua_applet_wakeup;
6711 ctx->ctx.hlua_apptcp.task = task;
6712
6713 /* In the execution wrappers linked with a stream, the
6714 * Lua context can be not initialized. This behavior
6715 * permits to save performances because a systematic
6716 * Lua initialization cause 5% performances loss.
6717 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006718 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006719 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6720 ctx->rule->arg.hlua_rule->fcn.name);
6721 return 0;
6722 }
6723
6724 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006725 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006726
6727 /* The following Lua calls can fail. */
6728 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006729 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6730 error = lua_tostring(hlua->T, -1);
6731 else
6732 error = "critical error";
6733 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6734 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006735 return 0;
6736 }
6737
6738 /* Check stack available size. */
6739 if (!lua_checkstack(hlua->T, 1)) {
6740 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6741 ctx->rule->arg.hlua_rule->fcn.name);
6742 RESET_SAFE_LJMP(hlua->T);
6743 return 0;
6744 }
6745
6746 /* Restore the function in the stack. */
6747 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6748
6749 /* Create and and push object stream in the stack. */
6750 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
6751 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6752 ctx->rule->arg.hlua_rule->fcn.name);
6753 RESET_SAFE_LJMP(hlua->T);
6754 return 0;
6755 }
6756 hlua->nargs = 1;
6757
6758 /* push keywords in the stack. */
6759 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6760 if (!lua_checkstack(hlua->T, 1)) {
6761 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6762 ctx->rule->arg.hlua_rule->fcn.name);
6763 RESET_SAFE_LJMP(hlua->T);
6764 return 0;
6765 }
6766 lua_pushstring(hlua->T, *arg);
6767 hlua->nargs++;
6768 }
6769
6770 RESET_SAFE_LJMP(hlua->T);
6771
6772 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01006773 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01006774 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006775
6776 return 1;
6777}
6778
Willy Tarreau60409db2019-08-21 14:14:50 +02006779void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006780{
6781 struct stream_interface *si = ctx->owner;
6782 struct stream *strm = si_strm(si);
6783 struct channel *res = si_ic(si);
6784 struct act_rule *rule = ctx->rule;
6785 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006786 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006787
6788 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02006789 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
6790 /* eat the whole request */
6791 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006792 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02006793 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006794
6795 /* If the stream is disconnect or closed, ldo nothing. */
6796 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6797 return;
6798
6799 /* Execute the function. */
6800 switch (hlua_ctx_resume(hlua, 1)) {
6801 /* finished. */
6802 case HLUA_E_OK:
6803 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6804
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006805 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02006806 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006807 res->flags |= CF_READ_NULL;
6808 si_shutr(si);
6809 return;
6810
6811 /* yield. */
6812 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006813 if (hlua->wake_time != TICK_ETERNITY)
6814 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006815 return;
6816
6817 /* finished with error. */
6818 case HLUA_E_ERRMSG:
6819 /* Display log. */
6820 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6821 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6822 lua_pop(hlua->T, 1);
6823 goto error;
6824
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006825 case HLUA_E_ETMOUT:
6826 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
6827 rule->arg.hlua_rule->fcn.name);
6828 goto error;
6829
6830 case HLUA_E_NOMEM:
6831 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
6832 rule->arg.hlua_rule->fcn.name);
6833 goto error;
6834
6835 case HLUA_E_YIELD: /* unexpected */
6836 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
6837 rule->arg.hlua_rule->fcn.name);
6838 goto error;
6839
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006840 case HLUA_E_ERR:
6841 /* Display log. */
6842 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6843 rule->arg.hlua_rule->fcn.name);
6844 goto error;
6845
6846 default:
6847 goto error;
6848 }
6849
6850error:
6851
6852 /* For all other cases, just close the stream. */
6853 si_shutw(si);
6854 si_shutr(si);
6855 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6856}
6857
6858static void hlua_applet_tcp_release(struct appctx *ctx)
6859{
Olivier Houchard3f795f72019-04-17 22:51:06 +02006860 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006861 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006862 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006863 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006864}
6865
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006866/* The function returns 1 if the initialisation is complete, 0 if
6867 * an errors occurs and -1 if more data are required for initializing
6868 * the applet.
6869 */
6870static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6871{
6872 struct stream_interface *si = ctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006873 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006874 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006875 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006876 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006877 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006878
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006879 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01006880 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006881 if (!hlua) {
6882 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6883 ctx->rule->arg.hlua_rule->fcn.name);
6884 return 0;
6885 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006886 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006887 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006888 ctx->ctx.hlua_apphttp.left_bytes = -1;
6889 ctx->ctx.hlua_apphttp.flags = 0;
6890
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006891 if (txn->req.flags & HTTP_MSGF_VER_11)
6892 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6893
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006894 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006895 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006896 if (!task) {
6897 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6898 ctx->rule->arg.hlua_rule->fcn.name);
6899 return 0;
6900 }
6901 task->nice = 0;
6902 task->context = ctx;
6903 task->process = hlua_applet_wakeup;
6904 ctx->ctx.hlua_apphttp.task = task;
6905
6906 /* In the execution wrappers linked with a stream, the
6907 * Lua context can be not initialized. This behavior
6908 * permits to save performances because a systematic
6909 * Lua initialization cause 5% performances loss.
6910 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006911 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006912 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6913 ctx->rule->arg.hlua_rule->fcn.name);
6914 return 0;
6915 }
6916
6917 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006918 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006919
6920 /* The following Lua calls can fail. */
6921 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006922 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6923 error = lua_tostring(hlua->T, -1);
6924 else
6925 error = "critical error";
6926 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6927 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006928 return 0;
6929 }
6930
6931 /* Check stack available size. */
6932 if (!lua_checkstack(hlua->T, 1)) {
6933 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6934 ctx->rule->arg.hlua_rule->fcn.name);
6935 RESET_SAFE_LJMP(hlua->T);
6936 return 0;
6937 }
6938
6939 /* Restore the function in the stack. */
6940 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6941
6942 /* Create and and push object stream in the stack. */
6943 if (!hlua_applet_http_new(hlua->T, ctx)) {
6944 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6945 ctx->rule->arg.hlua_rule->fcn.name);
6946 RESET_SAFE_LJMP(hlua->T);
6947 return 0;
6948 }
6949 hlua->nargs = 1;
6950
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006951 /* push keywords in the stack. */
6952 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6953 if (!lua_checkstack(hlua->T, 1)) {
6954 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6955 ctx->rule->arg.hlua_rule->fcn.name);
6956 RESET_SAFE_LJMP(hlua->T);
6957 return 0;
6958 }
6959 lua_pushstring(hlua->T, *arg);
6960 hlua->nargs++;
6961 }
6962
6963 RESET_SAFE_LJMP(hlua->T);
6964
6965 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01006966 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006967
6968 return 1;
6969}
6970
Willy Tarreau60409db2019-08-21 14:14:50 +02006971void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006972{
6973 struct stream_interface *si = ctx->owner;
6974 struct stream *strm = si_strm(si);
6975 struct channel *req = si_oc(si);
6976 struct channel *res = si_ic(si);
6977 struct act_rule *rule = ctx->rule;
6978 struct proxy *px = strm->be;
6979 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
6980 struct htx *req_htx, *res_htx;
6981
6982 res_htx = htx_from_buf(&res->buf);
6983
6984 /* If the stream is disconnect or closed, ldo nothing. */
6985 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6986 goto out;
6987
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05006988 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006989 if (!b_size(&res->buf)) {
6990 si_rx_room_blk(si);
6991 goto out;
6992 }
6993 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01006994 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006995 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6996
6997 /* Set the currently running flag. */
6998 if (!HLUA_IS_RUNNING(hlua) &&
6999 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7000 struct htx_blk *blk;
7001 size_t count = co_data(req);
7002
7003 if (!count) {
7004 si_cant_get(si);
7005 goto out;
7006 }
7007
7008 /* We need to flush the request header. This left the body for
7009 * the Lua.
7010 */
7011 req_htx = htx_from_buf(&req->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02007012 blk = htx_get_first_blk(req_htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007013 while (count && blk) {
7014 enum htx_blk_type type = htx_get_blk_type(blk);
7015 uint32_t sz = htx_get_blksz(blk);
7016
7017 if (sz > count) {
7018 si_cant_get(si);
Christopher Faulet0ae79d02019-02-27 21:36:59 +01007019 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007020 goto out;
7021 }
7022
7023 count -= sz;
7024 co_set_data(req, co_data(req) - sz);
7025 blk = htx_remove_blk(req_htx, blk);
7026
7027 if (type == HTX_BLK_EOH)
7028 break;
7029 }
Christopher Faulet0ae79d02019-02-27 21:36:59 +01007030 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007031 }
7032
7033 /* Executes The applet if it is not done. */
7034 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7035
7036 /* Execute the function. */
7037 switch (hlua_ctx_resume(hlua, 1)) {
7038 /* finished. */
7039 case HLUA_E_OK:
7040 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7041 break;
7042
7043 /* yield. */
7044 case HLUA_E_AGAIN:
7045 if (hlua->wake_time != TICK_ETERNITY)
7046 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007047 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007048
7049 /* finished with error. */
7050 case HLUA_E_ERRMSG:
7051 /* Display log. */
7052 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7053 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7054 lua_pop(hlua->T, 1);
7055 goto error;
7056
7057 case HLUA_E_ETMOUT:
7058 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
7059 rule->arg.hlua_rule->fcn.name);
7060 goto error;
7061
7062 case HLUA_E_NOMEM:
7063 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
7064 rule->arg.hlua_rule->fcn.name);
7065 goto error;
7066
7067 case HLUA_E_YIELD: /* unexpected */
7068 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
7069 rule->arg.hlua_rule->fcn.name);
7070 goto error;
7071
7072 case HLUA_E_ERR:
7073 /* Display log. */
7074 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
7075 rule->arg.hlua_rule->fcn.name);
7076 goto error;
7077
7078 default:
7079 goto error;
7080 }
7081 }
7082
7083 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007084 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
7085 goto done;
7086
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007087 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7088 goto error;
7089
Christopher Faulet54b5e212019-06-04 10:08:28 +02007090 /* Don't add TLR because mux-h1 will take care of it */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007091 if (!htx_add_endof(res_htx, HTX_BLK_EOM)) {
7092 si_rx_room_blk(si);
7093 goto out;
7094 }
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007095 channel_add_input(res, 1);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007096 strm->txn->status = ctx->ctx.hlua_apphttp.status;
7097 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007098 }
7099
7100 done:
7101 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007102 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007103 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007104 si_shutr(si);
7105 }
7106
7107 /* eat the whole request */
7108 if (co_data(req)) {
7109 req_htx = htx_from_buf(&req->buf);
7110 co_htx_skip(req, req_htx, co_data(req));
7111 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007112 }
7113 }
7114
7115 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007116 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007117 return;
7118
7119 error:
7120
7121 /* If we are in HTTP mode, and we are not send any
7122 * data, return a 500 server error in best effort:
7123 * if there is no room available in the buffer,
7124 * just close the connection.
7125 */
7126 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02007127 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007128
7129 channel_erase(res);
7130 res->buf.data = b_data(err);
7131 memcpy(res->buf.area, b_head(err), b_data(err));
7132 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007133 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007134 }
7135 if (!(strm->flags & SF_ERR_MASK))
7136 strm->flags |= SF_ERR_RESOURCE;
7137 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7138 goto done;
7139}
7140
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007141static void hlua_applet_http_release(struct appctx *ctx)
7142{
Olivier Houchard3f795f72019-04-17 22:51:06 +02007143 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007144 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007145 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007146 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007147}
7148
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007149/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007150 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007151 *
7152 * This function can fail with an abort() due to an Lua critical error.
7153 * We are in the configuration parsing process of HAProxy, this abort() is
7154 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007155 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007156static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
7157 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007158{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007159 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007160 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007161
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007162 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007163 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007164 if (!rule->arg.hlua_rule) {
7165 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007166 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007167 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007168
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007169 /* Memory for arguments. */
7170 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
7171 if (!rule->arg.hlua_rule->args) {
7172 memprintf(err, "out of memory error");
7173 return ACT_RET_PRS_ERR;
7174 }
7175
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007176 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007177 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007178
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007179 /* Expect some arguments */
7180 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007181 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007182 memprintf(err, "expect %d arguments", fcn->nargs);
7183 return ACT_RET_PRS_ERR;
7184 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007185 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007186 if (!rule->arg.hlua_rule->args[i]) {
7187 memprintf(err, "out of memory error");
7188 return ACT_RET_PRS_ERR;
7189 }
7190 (*cur_arg)++;
7191 }
7192 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007193
Thierry FOURNIER42148732015-09-02 17:17:33 +02007194 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007195 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007196 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007197}
7198
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007199static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
7200 struct act_rule *rule, char **err)
7201{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007202 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007203
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007204 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007205 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007206 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007207 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007208 * the call of this analyzer.
7209 */
7210 if (rule->from != ACT_F_HTTP_REQ) {
7211 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
7212 return ACT_RET_PRS_ERR;
7213 }
7214
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007215 /* Memory for the rule. */
7216 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7217 if (!rule->arg.hlua_rule) {
7218 memprintf(err, "out of memory error");
7219 return ACT_RET_PRS_ERR;
7220 }
7221
7222 /* Reference the Lua function and store the reference. */
7223 rule->arg.hlua_rule->fcn = *fcn;
7224
7225 /* TODO: later accept arguments. */
7226 rule->arg.hlua_rule->args = NULL;
7227
7228 /* Add applet pointer in the rule. */
7229 rule->applet.obj_type = OBJ_TYPE_APPLET;
7230 rule->applet.name = fcn->name;
7231 rule->applet.init = hlua_applet_http_init;
7232 rule->applet.fct = hlua_applet_http_fct;
7233 rule->applet.release = hlua_applet_http_release;
7234 rule->applet.timeout = hlua_timeout_applet;
7235
7236 return ACT_RET_PRS_OK;
7237}
7238
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007239/* This function is an LUA binding used for registering
7240 * "sample-conv" functions. It expects a converter name used
7241 * in the haproxy configuration file, and an LUA function.
7242 */
7243__LJMP static int hlua_register_action(lua_State *L)
7244{
7245 struct action_kw_list *akl;
7246 const char *name;
7247 int ref;
7248 int len;
7249 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007250 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007251
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007252 /* Initialise the number of expected arguments at 0. */
7253 nargs = 0;
7254
7255 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7256 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007257
7258 /* First argument : converter name. */
7259 name = MAY_LJMP(luaL_checkstring(L, 1));
7260
7261 /* Second argument : environment. */
7262 if (lua_type(L, 2) != LUA_TTABLE)
7263 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7264
7265 /* Third argument : lua function. */
7266 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7267
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007268 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007269 if (lua_gettop(L) >= 4)
7270 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
7271
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007272 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007273 lua_pushnil(L);
7274 while (lua_next(L, 2) != 0) {
7275 if (lua_type(L, -1) != LUA_TSTRING)
7276 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7277
7278 /* Check required environment. Only accepted "http" or "tcp". */
7279 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007280 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007281 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007282 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007283 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007284 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007285 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007286
7287 /* Fill fcn. */
7288 fcn->name = strdup(name);
7289 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007290 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007291 fcn->function_ref = ref;
7292
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007293 /* Set the expected number od arguments. */
7294 fcn->nargs = nargs;
7295
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007296 /* List head */
7297 akl->list.n = akl->list.p = NULL;
7298
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007299 /* action keyword. */
7300 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007301 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007302 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007303 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007304
7305 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7306
7307 akl->kw[0].match_pfx = 0;
7308 akl->kw[0].private = fcn;
7309 akl->kw[0].parse = action_register_lua;
7310
7311 /* select the action registering point. */
7312 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
7313 tcp_req_cont_keywords_register(akl);
7314 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
7315 tcp_res_cont_keywords_register(akl);
7316 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
7317 http_req_keywords_register(akl);
7318 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
7319 http_res_keywords_register(akl);
7320 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007321 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007322 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
7323 "are expected.", lua_tostring(L, -1)));
7324
7325 /* pop the environment string. */
7326 lua_pop(L, 1);
7327 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007328 return ACT_RET_PRS_OK;
7329}
7330
7331static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
7332 struct act_rule *rule, char **err)
7333{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007334 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007335
Christopher Faulet280f85b2019-07-15 15:02:04 +02007336 if (px->mode == PR_MODE_HTTP) {
7337 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01007338 return ACT_RET_PRS_ERR;
7339 }
7340
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007341 /* Memory for the rule. */
7342 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7343 if (!rule->arg.hlua_rule) {
7344 memprintf(err, "out of memory error");
7345 return ACT_RET_PRS_ERR;
7346 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007347
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007348 /* Reference the Lua function and store the reference. */
7349 rule->arg.hlua_rule->fcn = *fcn;
7350
7351 /* TODO: later accept arguments. */
7352 rule->arg.hlua_rule->args = NULL;
7353
7354 /* Add applet pointer in the rule. */
7355 rule->applet.obj_type = OBJ_TYPE_APPLET;
7356 rule->applet.name = fcn->name;
7357 rule->applet.init = hlua_applet_tcp_init;
7358 rule->applet.fct = hlua_applet_tcp_fct;
7359 rule->applet.release = hlua_applet_tcp_release;
7360 rule->applet.timeout = hlua_timeout_applet;
7361
7362 return 0;
7363}
7364
7365/* This function is an LUA binding used for registering
7366 * "sample-conv" functions. It expects a converter name used
7367 * in the haproxy configuration file, and an LUA function.
7368 */
7369__LJMP static int hlua_register_service(lua_State *L)
7370{
7371 struct action_kw_list *akl;
7372 const char *name;
7373 const char *env;
7374 int ref;
7375 int len;
7376 struct hlua_function *fcn;
7377
7378 MAY_LJMP(check_args(L, 3, "register_service"));
7379
7380 /* First argument : converter name. */
7381 name = MAY_LJMP(luaL_checkstring(L, 1));
7382
7383 /* Second argument : environment. */
7384 env = MAY_LJMP(luaL_checkstring(L, 2));
7385
7386 /* Third argument : lua function. */
7387 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7388
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007389 /* Allocate and fill the sample fetch keyword struct. */
7390 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
7391 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007392 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007393 fcn = calloc(1, sizeof(*fcn));
7394 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007395 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007396
7397 /* Fill fcn. */
7398 len = strlen("<lua.>") + strlen(name) + 1;
7399 fcn->name = calloc(1, len);
7400 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007401 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007402 snprintf((char *)fcn->name, len, "<lua.%s>", name);
7403 fcn->function_ref = ref;
7404
7405 /* List head */
7406 akl->list.n = akl->list.p = NULL;
7407
7408 /* converter keyword. */
7409 len = strlen("lua.") + strlen(name) + 1;
7410 akl->kw[0].kw = calloc(1, len);
7411 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007412 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007413
7414 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7415
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01007416 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007417 if (strcmp(env, "tcp") == 0)
7418 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007419 else if (strcmp(env, "http") == 0)
7420 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007421 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007422 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01007423 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007424
7425 akl->kw[0].match_pfx = 0;
7426 akl->kw[0].private = fcn;
7427
7428 /* End of array. */
7429 memset(&akl->kw[1], 0, sizeof(*akl->kw));
7430
7431 /* Register this new converter */
7432 service_keywords_register(akl);
7433
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007434 return 0;
7435}
7436
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007437/* This function initialises Lua cli handler. It copies the
7438 * arguments in the Lua stack and create channel IO objects.
7439 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007440static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007441{
7442 struct hlua *hlua;
7443 struct hlua_function *fcn;
7444 int i;
7445 const char *error;
7446
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007447 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007448 appctx->ctx.hlua_cli.fcn = private;
7449
Willy Tarreaubafbe012017-11-24 17:34:44 +01007450 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007451 if (!hlua) {
7452 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007453 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007454 }
7455 HLUA_INIT(hlua);
7456 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007457
7458 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +05007459 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007460 * applet_http. It is absolutely compatible.
7461 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007462 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007463 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01007464 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007465 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007466 }
7467 appctx->ctx.hlua_cli.task->nice = 0;
7468 appctx->ctx.hlua_cli.task->context = appctx;
7469 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
7470
7471 /* Initialises the Lua context */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007472 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007473 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007474 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007475 }
7476
7477 /* The following Lua calls can fail. */
7478 if (!SET_SAFE_LJMP(hlua->T)) {
7479 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7480 error = lua_tostring(hlua->T, -1);
7481 else
7482 error = "critical error";
7483 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
7484 goto error;
7485 }
7486
7487 /* Check stack available size. */
7488 if (!lua_checkstack(hlua->T, 2)) {
7489 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7490 goto error;
7491 }
7492
7493 /* Restore the function in the stack. */
7494 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
7495
7496 /* Once the arguments parsed, the CLI is like an AppletTCP,
7497 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007498 */
7499 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
7500 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7501 goto error;
7502 }
7503 hlua->nargs = 1;
7504
7505 /* push keywords in the stack. */
7506 for (i = 0; *args[i]; i++) {
7507 /* Check stack available size. */
7508 if (!lua_checkstack(hlua->T, 1)) {
7509 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7510 goto error;
7511 }
7512 lua_pushstring(hlua->T, args[i]);
7513 hlua->nargs++;
7514 }
7515
7516 /* We must initialize the execution timeouts. */
7517 hlua->max_time = hlua_timeout_session;
7518
7519 /* At this point the execution is safe. */
7520 RESET_SAFE_LJMP(hlua->T);
7521
7522 /* It's ok */
7523 return 0;
7524
7525 /* It's not ok. */
7526error:
7527 RESET_SAFE_LJMP(hlua->T);
7528 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007529 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007530 return 1;
7531}
7532
7533static int hlua_cli_io_handler_fct(struct appctx *appctx)
7534{
7535 struct hlua *hlua;
7536 struct stream_interface *si;
7537 struct hlua_function *fcn;
7538
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007539 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007540 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01007541 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007542
7543 /* If the stream is disconnect or closed, ldo nothing. */
7544 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7545 return 1;
7546
7547 /* Execute the function. */
7548 switch (hlua_ctx_resume(hlua, 1)) {
7549
7550 /* finished. */
7551 case HLUA_E_OK:
7552 return 1;
7553
7554 /* yield. */
7555 case HLUA_E_AGAIN:
7556 /* We want write. */
7557 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01007558 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007559 /* Set the timeout. */
7560 if (hlua->wake_time != TICK_ETERNITY)
7561 task_schedule(hlua->task, hlua->wake_time);
7562 return 0;
7563
7564 /* finished with error. */
7565 case HLUA_E_ERRMSG:
7566 /* Display log. */
7567 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
7568 fcn->name, lua_tostring(hlua->T, -1));
7569 lua_pop(hlua->T, 1);
7570 return 1;
7571
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007572 case HLUA_E_ETMOUT:
7573 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
7574 fcn->name);
7575 return 1;
7576
7577 case HLUA_E_NOMEM:
7578 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
7579 fcn->name);
7580 return 1;
7581
7582 case HLUA_E_YIELD: /* unexpected */
7583 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
7584 fcn->name);
7585 return 1;
7586
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007587 case HLUA_E_ERR:
7588 /* Display log. */
7589 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
7590 fcn->name);
7591 return 1;
7592
7593 default:
7594 return 1;
7595 }
7596
7597 return 1;
7598}
7599
7600static void hlua_cli_io_release_fct(struct appctx *appctx)
7601{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007602 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007603 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007604}
7605
7606/* This function is an LUA binding used for registering
7607 * new keywords in the cli. It expects a list of keywords
7608 * which are the "path". It is limited to 5 keywords. A
7609 * description of the command, a function to be executed
7610 * for the parsing and a function for io handlers.
7611 */
7612__LJMP static int hlua_register_cli(lua_State *L)
7613{
7614 struct cli_kw_list *cli_kws;
7615 const char *message;
7616 int ref_io;
7617 int len;
7618 struct hlua_function *fcn;
7619 int index;
7620 int i;
7621
7622 MAY_LJMP(check_args(L, 3, "register_cli"));
7623
7624 /* First argument : an array of maximum 5 keywords. */
7625 if (!lua_istable(L, 1))
7626 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
7627
7628 /* Second argument : string with contextual message. */
7629 message = MAY_LJMP(luaL_checkstring(L, 2));
7630
7631 /* Third and fourth argument : lua function. */
7632 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
7633
7634 /* Allocate and fill the sample fetch keyword struct. */
7635 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
7636 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007637 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007638 fcn = calloc(1, sizeof(*fcn));
7639 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007640 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007641
7642 /* Fill path. */
7643 index = 0;
7644 lua_pushnil(L);
7645 while(lua_next(L, 1) != 0) {
7646 if (index >= 5)
7647 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
7648 if (lua_type(L, -1) != LUA_TSTRING)
7649 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
7650 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
7651 if (!cli_kws->kw[0].str_kw[index])
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007652 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007653 index++;
7654 lua_pop(L, 1);
7655 }
7656
7657 /* Copy help message. */
7658 cli_kws->kw[0].usage = strdup(message);
7659 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007660 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007661
7662 /* Fill fcn io handler. */
7663 len = strlen("<lua.cli>") + 1;
7664 for (i = 0; i < index; i++)
7665 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
7666 fcn->name = calloc(1, len);
7667 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007668 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007669 strncat((char *)fcn->name, "<lua.cli", len);
7670 for (i = 0; i < index; i++) {
7671 strncat((char *)fcn->name, ".", len);
7672 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
7673 }
7674 strncat((char *)fcn->name, ">", len);
7675 fcn->function_ref = ref_io;
7676
7677 /* Fill last entries. */
7678 cli_kws->kw[0].private = fcn;
7679 cli_kws->kw[0].parse = hlua_cli_parse_fct;
7680 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
7681 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
7682
7683 /* Register this new converter */
7684 cli_register_kw(cli_kws);
7685
7686 return 0;
7687}
7688
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007689static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
7690 struct proxy *defpx, const char *file, int line,
7691 char **err, unsigned int *timeout)
7692{
7693 const char *error;
7694
7695 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +02007696 if (error == PARSE_TIME_OVER) {
7697 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
7698 args[1], args[0]);
7699 return -1;
7700 }
7701 else if (error == PARSE_TIME_UNDER) {
7702 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
7703 args[1], args[0]);
7704 return -1;
7705 }
7706 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007707 memprintf(err, "%s: invalid timeout", args[0]);
7708 return -1;
7709 }
7710 return 0;
7711}
7712
7713static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
7714 struct proxy *defpx, const char *file, int line,
7715 char **err)
7716{
7717 return hlua_read_timeout(args, section_type, curpx, defpx,
7718 file, line, err, &hlua_timeout_session);
7719}
7720
7721static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
7722 struct proxy *defpx, const char *file, int line,
7723 char **err)
7724{
7725 return hlua_read_timeout(args, section_type, curpx, defpx,
7726 file, line, err, &hlua_timeout_task);
7727}
7728
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007729static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
7730 struct proxy *defpx, const char *file, int line,
7731 char **err)
7732{
7733 return hlua_read_timeout(args, section_type, curpx, defpx,
7734 file, line, err, &hlua_timeout_applet);
7735}
7736
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007737static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
7738 struct proxy *defpx, const char *file, int line,
7739 char **err)
7740{
7741 char *error;
7742
7743 hlua_nb_instruction = strtoll(args[1], &error, 10);
7744 if (*error != '\0') {
7745 memprintf(err, "%s: invalid number", args[0]);
7746 return -1;
7747 }
7748 return 0;
7749}
7750
Willy Tarreau32f61e22015-03-18 17:54:59 +01007751static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
7752 struct proxy *defpx, const char *file, int line,
7753 char **err)
7754{
7755 char *error;
7756
7757 if (*(args[1]) == 0) {
7758 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
7759 return -1;
7760 }
7761 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
7762 if (*error != '\0') {
7763 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
7764 return -1;
7765 }
7766 return 0;
7767}
7768
7769
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007770/* This function is called by the main configuration key "lua-load". It loads and
7771 * execute an lua file during the parsing of the HAProxy configuration file. It is
7772 * the main lua entry point.
7773 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007774 * This function runs with the HAProxy keywords API. It returns -1 if an error
7775 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007776 *
7777 * In some error case, LUA set an error message in top of the stack. This function
7778 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007779 *
7780 * This function can fail with an abort() due to an Lua critical error.
7781 * We are in the configuration parsing process of HAProxy, this abort() is
7782 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007783 */
7784static int hlua_load(char **args, int section_type, struct proxy *curpx,
7785 struct proxy *defpx, const char *file, int line,
7786 char **err)
7787{
7788 int error;
7789
7790 /* Just load and compile the file. */
7791 error = luaL_loadfile(gL.T, args[1]);
7792 if (error) {
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007793 memprintf(err, "error in Lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007794 lua_pop(gL.T, 1);
7795 return -1;
7796 }
7797
7798 /* If no syntax error where detected, execute the code. */
7799 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
7800 switch (error) {
7801 case LUA_OK:
7802 break;
7803 case LUA_ERRRUN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007804 memprintf(err, "Lua runtime error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007805 lua_pop(gL.T, 1);
7806 return -1;
7807 case LUA_ERRMEM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007808 memprintf(err, "Lua out of memory error.n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007809 return -1;
7810 case LUA_ERRERR:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007811 memprintf(err, "Lua message handler error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007812 lua_pop(gL.T, 1);
7813 return -1;
7814 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007815 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007816 lua_pop(gL.T, 1);
7817 return -1;
7818 default:
Ilya Shipitsind4259502020-04-08 01:07:56 +05007819 memprintf(err, "Lua unknown error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007820 lua_pop(gL.T, 1);
7821 return -1;
7822 }
7823
7824 return 0;
7825}
7826
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +01007827/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
7828 * in the given <ctx>.
7829 */
7830static int hlua_prepend_path(struct hlua ctx, char *type, char *path)
7831{
7832 lua_getglobal(ctx.T, "package"); /* push package variable */
7833 lua_pushstring(ctx.T, path); /* push given path */
7834 lua_pushstring(ctx.T, ";"); /* push semicolon */
7835 lua_getfield(ctx.T, -3, type); /* push old path */
7836 lua_concat(ctx.T, 3); /* concatenate to new path */
7837 lua_setfield(ctx.T, -2, type); /* store new path */
7838 lua_pop(ctx.T, 1); /* pop package variable */
7839
7840 return 0;
7841}
7842
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01007843static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
7844 struct proxy *defpx, const char *file, int line,
7845 char **err)
7846{
7847 char *path;
7848 char *type = "path";
7849 if (too_many_args(2, args, err, NULL)) {
7850 return -1;
7851 }
7852
7853 if (!(*args[1])) {
7854 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
7855 return -1;
7856 }
7857 path = args[1];
7858
7859 if (*args[2]) {
7860 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
7861 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
7862 return -1;
7863 }
7864 type = args[2];
7865 }
7866
7867 return hlua_prepend_path(gL, type, path);
7868}
7869
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007870/* configuration keywords declaration */
7871static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01007872 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007873 { CFG_GLOBAL, "lua-load", hlua_load },
7874 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
7875 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02007876 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007877 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01007878 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007879 { 0, NULL, NULL },
7880}};
7881
Willy Tarreau0108d902018-11-25 19:14:37 +01007882INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
7883
Christopher Fauletafd8f102018-11-08 11:34:21 +01007884
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007885/* This function can fail with an abort() due to an Lua critical error.
7886 * We are in the initialisation process of HAProxy, this abort() is
7887 * tolerated.
7888 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007889int hlua_post_init()
7890{
7891 struct hlua_init_function *init;
7892 const char *msg;
7893 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007894 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007895
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007896 /* Call post initialisation function in safe environment. */
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007897 if (!SET_SAFE_LJMP(gL.T)) {
7898 if (lua_type(gL.T, -1) == LUA_TSTRING)
7899 error = lua_tostring(gL.T, -1);
7900 else
7901 error = "critical error";
7902 fprintf(stderr, "Lua post-init: %s.\n", error);
7903 exit(1);
7904 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +02007905
7906#if USE_OPENSSL
7907 /* Initialize SSL server. */
7908 if (socket_ssl.xprt->prepare_srv) {
7909 int saved_used_backed = global.ssl_used_backend;
7910 // don't affect maxconn automatic computation
7911 socket_ssl.xprt->prepare_srv(&socket_ssl);
7912 global.ssl_used_backend = saved_used_backed;
7913 }
7914#endif
7915
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007916 hlua_fcn_post_init(gL.T);
7917 RESET_SAFE_LJMP(gL.T);
7918
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007919 list_for_each_entry(init, &hlua_init_functions, l) {
7920 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7921 ret = hlua_ctx_resume(&gL, 0);
7922 switch (ret) {
7923 case HLUA_E_OK:
7924 lua_pop(gL.T, -1);
7925 return 1;
7926 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007927 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007928 return 0;
7929 case HLUA_E_ERRMSG:
7930 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01007931 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007932 return 0;
7933 case HLUA_E_ERR:
7934 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007935 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007936 return 0;
7937 }
7938 }
7939 return 1;
7940}
7941
Willy Tarreau32f61e22015-03-18 17:54:59 +01007942/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7943 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7944 * is the previously allocated size or the kind of object in case of a new
7945 * allocation. <nsize> is the requested new size.
7946 */
7947static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7948{
7949 struct hlua_mem_allocator *zone = ud;
7950
7951 if (nsize == 0) {
7952 /* it's a free */
7953 if (ptr)
7954 zone->allocated -= osize;
7955 free(ptr);
7956 return NULL;
7957 }
7958
7959 if (!ptr) {
7960 /* it's a new allocation */
7961 if (zone->limit && zone->allocated + nsize > zone->limit)
7962 return NULL;
7963
7964 ptr = malloc(nsize);
7965 if (ptr)
7966 zone->allocated += nsize;
7967 return ptr;
7968 }
7969
7970 /* it's a realloc */
7971 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7972 return NULL;
7973
7974 ptr = realloc(ptr, nsize);
7975 if (ptr)
7976 zone->allocated += nsize - osize;
7977 return ptr;
7978}
7979
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007980/* Ithis function can fail with an abort() due to an Lua critical error.
7981 * We are in the initialisation process of HAProxy, this abort() is
7982 * tolerated.
7983 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007984void hlua_init(void)
7985{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007986 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007987 int idx;
7988 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007989 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007990 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007991 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007992#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007993 struct srv_kw *kw;
7994 int tmp_error;
7995 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007996 char *args[] = { /* SSL client configuration. */
7997 "ssl",
7998 "verify",
7999 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008000 NULL
8001 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008002#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008003
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008004 /* Init main lua stack. */
8005 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01008006 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01008007 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02008008 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008009 hlua_sethlua(&gL);
8010 gL.Tref = LUA_REFNIL;
8011 gL.task = NULL;
8012
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008013 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008014 * the Lua function can fail with an abort. We are in the initialisation
8015 * process of HAProxy, this abort() is tolerated.
8016 */
8017
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008018 /* Initialise lua. */
8019 luaL_openlibs(gL.T);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +01008020#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
8021#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
8022#ifdef HLUA_PREPEND_PATH
8023 hlua_prepend_path(gL, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
8024#endif
8025#ifdef HLUA_PREPEND_CPATH
8026 hlua_prepend_path(gL, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
8027#endif
8028#undef HLUA_PREPEND_PATH_TOSTRING
8029#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008030
Thierry Fournier75933d42016-01-21 09:30:18 +01008031 /* Set safe environment for the initialisation. */
8032 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008033 if (lua_type(gL.T, -1) == LUA_TSTRING)
8034 error_msg = lua_tostring(gL.T, -1);
8035 else
8036 error_msg = "critical error";
8037 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01008038 exit(1);
8039 }
8040
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008041 /*
8042 *
8043 * Create "core" object.
8044 *
8045 */
8046
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01008047 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008048 lua_newtable(gL.T);
8049
8050 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008051 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008052 hlua_class_const_int(gL.T, log_levels[i], i);
8053
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008054 /* Register special functions. */
8055 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008056 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008057 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008058 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008059 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008060 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008061 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008062 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01008063 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008064 hlua_class_function(gL.T, "sleep", hlua_sleep);
8065 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01008066 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
8067 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
8068 hlua_class_function(gL.T, "set_map", hlua_set_map);
8069 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008070 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008071 hlua_class_function(gL.T, "log", hlua_log);
8072 hlua_class_function(gL.T, "Debug", hlua_log_debug);
8073 hlua_class_function(gL.T, "Info", hlua_log_info);
8074 hlua_class_function(gL.T, "Warning", hlua_log_warning);
8075 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02008076 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01008077 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008078
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008079 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008080
8081 /*
8082 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +01008083 * Create "act" object.
8084 *
8085 */
8086
8087 /* This table entry is the object "act" base. */
8088 lua_newtable(gL.T);
8089
8090 /* push action return constants */
8091 hlua_class_const_int(gL.T, "CONTINUE", ACT_RET_CONT);
8092 hlua_class_const_int(gL.T, "STOP", ACT_RET_STOP);
8093 hlua_class_const_int(gL.T, "YIELD", ACT_RET_YIELD);
8094 hlua_class_const_int(gL.T, "ERROR", ACT_RET_ERR);
8095 hlua_class_const_int(gL.T, "DONE", ACT_RET_DONE);
8096 hlua_class_const_int(gL.T, "DENY", ACT_RET_DENY);
8097 hlua_class_const_int(gL.T, "ABORT", ACT_RET_ABRT);
8098 hlua_class_const_int(gL.T, "INVALID", ACT_RET_INV);
8099
Christopher Faulet501465d2020-02-26 14:54:16 +01008100 hlua_class_function(gL.T, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008101
Christopher Faulet0f3c8902020-01-31 18:57:12 +01008102 lua_setglobal(gL.T, "act");
8103
8104 /*
8105 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008106 * Register class Map
8107 *
8108 */
8109
8110 /* This table entry is the object "Map" base. */
8111 lua_newtable(gL.T);
8112
8113 /* register pattern types. */
8114 for (i=0; i<PAT_MATCH_NUM; i++)
8115 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008116 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008117 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
8118 hlua_class_const_int(gL.T, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008119 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008120
8121 /* register constructor. */
8122 hlua_class_function(gL.T, "new", hlua_map_new);
8123
8124 /* Create and fill the metatable. */
8125 lua_newtable(gL.T);
8126
Ilya Shipitsind4259502020-04-08 01:07:56 +05008127 /* Create and fill the __index entry. */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008128 lua_pushstring(gL.T, "__index");
8129 lua_newtable(gL.T);
8130
8131 /* Register . */
8132 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
8133 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
8134
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008135 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008136
Thierry Fournier45e78d72016-02-19 18:34:46 +01008137 /* Register previous table in the registry with reference and named entry.
8138 * The function hlua_register_metatable() pops the stack, so we
8139 * previously create a copy of the table.
8140 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008141 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008142 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008143
8144 /* Assign the metatable to the mai Map object. */
8145 lua_setmetatable(gL.T, -2);
8146
8147 /* Set a name to the table. */
8148 lua_setglobal(gL.T, "Map");
8149
8150 /*
8151 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008152 * Register class Channel
8153 *
8154 */
8155
8156 /* Create and fill the metatable. */
8157 lua_newtable(gL.T);
8158
Ilya Shipitsind4259502020-04-08 01:07:56 +05008159 /* Create and fill the __index entry. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008160 lua_pushstring(gL.T, "__index");
8161 lua_newtable(gL.T);
8162
8163 /* Register . */
8164 hlua_class_function(gL.T, "get", hlua_channel_get);
8165 hlua_class_function(gL.T, "dup", hlua_channel_dup);
8166 hlua_class_function(gL.T, "getline", hlua_channel_getline);
8167 hlua_class_function(gL.T, "set", hlua_channel_set);
8168 hlua_class_function(gL.T, "append", hlua_channel_append);
8169 hlua_class_function(gL.T, "send", hlua_channel_send);
8170 hlua_class_function(gL.T, "forward", hlua_channel_forward);
8171 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
8172 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01008173 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01008174 hlua_class_function(gL.T, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008175
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008176 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008177
8178 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008179 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008180
8181 /*
8182 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008183 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008184 *
8185 */
8186
8187 /* Create and fill the metatable. */
8188 lua_newtable(gL.T);
8189
Ilya Shipitsind4259502020-04-08 01:07:56 +05008190 /* Create and fill the __index entry. */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008191 lua_pushstring(gL.T, "__index");
8192 lua_newtable(gL.T);
8193
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008194 /* Browse existing fetches and create the associated
8195 * object method.
8196 */
8197 sf = NULL;
8198 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
8199
8200 /* Dont register the keywork if the arguments check function are
8201 * not safe during the runtime.
8202 */
8203 if ((sf->val_args != NULL) &&
8204 (sf->val_args != val_payload_lv) &&
8205 (sf->val_args != val_hdr))
8206 continue;
8207
8208 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8209 * by an underscore.
8210 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008211 strncpy(trash.area, sf->kw, trash.size);
8212 trash.area[trash.size - 1] = '\0';
8213 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008214 if (*p == '.' || *p == '-' || *p == '+')
8215 *p = '_';
8216
8217 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008218 lua_pushstring(gL.T, trash.area);
Willy Tarreau2ec22742015-03-10 14:27:20 +01008219 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008220 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008221 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008222 }
8223
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008224 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008225
8226 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008227 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008228
8229 /*
8230 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008231 * Register class Converters
8232 *
8233 */
8234
8235 /* Create and fill the metatable. */
8236 lua_newtable(gL.T);
8237
8238 /* Create and fill the __index entry. */
8239 lua_pushstring(gL.T, "__index");
8240 lua_newtable(gL.T);
8241
8242 /* Browse existing converters and create the associated
8243 * object method.
8244 */
8245 sc = NULL;
8246 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
8247 /* Dont register the keywork if the arguments check function are
8248 * not safe during the runtime.
8249 */
8250 if (sc->val_args != NULL)
8251 continue;
8252
8253 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8254 * by an underscore.
8255 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008256 strncpy(trash.area, sc->kw, trash.size);
8257 trash.area[trash.size - 1] = '\0';
8258 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008259 if (*p == '.' || *p == '-' || *p == '+')
8260 *p = '_';
8261
8262 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008263 lua_pushstring(gL.T, trash.area);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008264 lua_pushlightuserdata(gL.T, sc);
8265 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008266 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008267 }
8268
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008269 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008270
8271 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008272 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008273
8274 /*
8275 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008276 * Register class HTTP
8277 *
8278 */
8279
8280 /* Create and fill the metatable. */
8281 lua_newtable(gL.T);
8282
Ilya Shipitsind4259502020-04-08 01:07:56 +05008283 /* Create and fill the __index entry. */
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008284 lua_pushstring(gL.T, "__index");
8285 lua_newtable(gL.T);
8286
8287 /* Register Lua functions. */
8288 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
8289 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
8290 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
8291 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
8292 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
8293 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
8294 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
8295 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
8296 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
8297 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
8298
8299 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
8300 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
8301 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
8302 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
8303 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
8304 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02008305 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008306
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008307 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008308
8309 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008310 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008311
8312 /*
8313 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008314 * Register class AppletTCP
8315 *
8316 */
8317
8318 /* Create and fill the metatable. */
8319 lua_newtable(gL.T);
8320
Ilya Shipitsind4259502020-04-08 01:07:56 +05008321 /* Create and fill the __index entry. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008322 lua_pushstring(gL.T, "__index");
8323 lua_newtable(gL.T);
8324
8325 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01008326 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
8327 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
8328 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
8329 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
8330 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008331 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
8332 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
8333 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008334
8335 lua_settable(gL.T, -3);
8336
8337 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008338 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008339
8340 /*
8341 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008342 * Register class AppletHTTP
8343 *
8344 */
8345
8346 /* Create and fill the metatable. */
8347 lua_newtable(gL.T);
8348
Ilya Shipitsind4259502020-04-08 01:07:56 +05008349 /* Create and fill the __index entry. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008350 lua_pushstring(gL.T, "__index");
8351 lua_newtable(gL.T);
8352
8353 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01008354 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
8355 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008356 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
8357 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
8358 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008359 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
8360 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
8361 hlua_class_function(gL.T, "send", hlua_applet_http_send);
8362 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
8363 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
8364 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
8365
8366 lua_settable(gL.T, -3);
8367
8368 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008369 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008370
8371 /*
8372 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008373 * Register class TXN
8374 *
8375 */
8376
8377 /* Create and fill the metatable. */
8378 lua_newtable(gL.T);
8379
Ilya Shipitsind4259502020-04-08 01:07:56 +05008380 /* Create and fill the __index entry. */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008381 lua_pushstring(gL.T, "__index");
8382 lua_newtable(gL.T);
8383
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008384 /* Register Lua functions. */
Patrick Hemmer268a7072018-05-11 12:52:31 -04008385 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
8386 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
8387 hlua_class_function(gL.T, "set_var", hlua_set_var);
8388 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
8389 hlua_class_function(gL.T, "get_var", hlua_get_var);
8390 hlua_class_function(gL.T, "done", hlua_txn_done);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008391 hlua_class_function(gL.T, "reply", hlua_txn_reply_new);
Patrick Hemmer268a7072018-05-11 12:52:31 -04008392 hlua_class_function(gL.T, "set_loglevel", hlua_txn_set_loglevel);
8393 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
8394 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
8395 hlua_class_function(gL.T, "set_priority_class", hlua_txn_set_priority_class);
8396 hlua_class_function(gL.T, "set_priority_offset", hlua_txn_set_priority_offset);
8397 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
8398 hlua_class_function(gL.T, "log", hlua_txn_log);
8399 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
8400 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
8401 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
8402 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008403
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008404 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008405
8406 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008407 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008408
8409 /*
8410 *
Christopher Faulet700d9e82020-01-31 12:21:52 +01008411 * Register class reply
8412 *
8413 */
8414 lua_newtable(gL.T);
8415 lua_pushstring(gL.T, "__index");
8416 lua_newtable(gL.T);
8417 hlua_class_function(gL.T, "set_status", hlua_txn_reply_set_status);
8418 hlua_class_function(gL.T, "add_header", hlua_txn_reply_add_header);
8419 hlua_class_function(gL.T, "del_header", hlua_txn_reply_del_header);
8420 hlua_class_function(gL.T, "set_body", hlua_txn_reply_set_body);
8421 lua_settable(gL.T, -3); /* Sets the __index entry. */
8422 class_txn_reply_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
8423
8424
8425 /*
8426 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008427 * Register class Socket
8428 *
8429 */
8430
8431 /* Create and fill the metatable. */
8432 lua_newtable(gL.T);
8433
Ilya Shipitsind4259502020-04-08 01:07:56 +05008434 /* Create and fill the __index entry. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008435 lua_pushstring(gL.T, "__index");
8436 lua_newtable(gL.T);
8437
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008438#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008439 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008440#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008441 hlua_class_function(gL.T, "connect", hlua_socket_connect);
8442 hlua_class_function(gL.T, "send", hlua_socket_send);
8443 hlua_class_function(gL.T, "receive", hlua_socket_receive);
8444 hlua_class_function(gL.T, "close", hlua_socket_close);
8445 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
8446 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
8447 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
8448 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
8449
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008450 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008451
8452 /* Register the garbage collector entry. */
8453 lua_pushstring(gL.T, "__gc");
8454 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008455 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008456
8457 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008458 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008459
8460 /* Proxy and server configuration initialisation. */
8461 memset(&socket_proxy, 0, sizeof(socket_proxy));
8462 init_new_proxy(&socket_proxy);
8463 socket_proxy.parent = NULL;
8464 socket_proxy.last_change = now.tv_sec;
8465 socket_proxy.id = "LUA-SOCKET";
8466 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
8467 socket_proxy.maxconn = 0;
8468 socket_proxy.accept = NULL;
8469 socket_proxy.options2 |= PR_O2_INDEPSTR;
8470 socket_proxy.srv = NULL;
8471 socket_proxy.conn_retries = 0;
8472 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
8473
8474 /* Init TCP server: unchanged parameters */
8475 memset(&socket_tcp, 0, sizeof(socket_tcp));
8476 socket_tcp.next = NULL;
8477 socket_tcp.proxy = &socket_proxy;
8478 socket_tcp.obj_type = OBJ_TYPE_SERVER;
8479 LIST_INIT(&socket_tcp.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008480 socket_tcp.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008481 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.idle_conns = NULL;
8527 socket_ssl.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008528 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008529 socket_ssl.last_change = 0;
8530 socket_ssl.id = "LUA-SSL-CONN";
8531 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8532 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8533 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
8534
8535 /* XXX: Copy default parameter from default server,
8536 * but the default server is not initialized.
8537 */
8538 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
8539 socket_ssl.minconn = socket_proxy.defsrv.minconn;
8540 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
8541 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
8542 socket_ssl.onerror = socket_proxy.defsrv.onerror;
8543 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8544 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
8545 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8546 socket_ssl.uweight = socket_proxy.defsrv.iweight;
8547 socket_ssl.iweight = socket_proxy.defsrv.iweight;
8548
8549 socket_ssl.check.status = HCHK_STATUS_INI;
8550 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
8551 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
8552 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
8553 socket_ssl.check.server = &socket_ssl;
8554
8555 socket_ssl.agent.status = HCHK_STATUS_INI;
8556 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
8557 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
8558 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
8559 socket_ssl.agent.server = &socket_ssl;
8560
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008561 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008562 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008563
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008564 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008565 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
8566 /*
8567 *
8568 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008569 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008570 * features like client certificates and ssl_verify.
8571 *
8572 */
8573 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
8574 if (tmp_error != 0) {
8575 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
8576 abort(); /* This must be never arrives because the command line
8577 not editable by the user. */
8578 }
8579 idx += kw->skip;
8580 }
8581 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008582#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01008583
8584 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008585}
Willy Tarreaubb57d942016-12-21 19:04:56 +01008586
Willy Tarreau80713382018-11-26 10:19:54 +01008587static void hlua_register_build_options(void)
8588{
Willy Tarreaubb57d942016-12-21 19:04:56 +01008589 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +01008590
Willy Tarreaubb57d942016-12-21 19:04:56 +01008591 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
8592 hap_register_build_opts(ptr, 1);
8593}
Willy Tarreau80713382018-11-26 10:19:54 +01008594
8595INITCALL0(STG_REGISTER, hlua_register_build_options);