blob: e7cac654757592efef1724948b6bc1d20b762ebf [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>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020014#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010015
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010016#include <lauxlib.h>
17#include <lua.h>
18#include <lualib.h>
19
Thierry FOURNIER463119c2015-03-10 00:35:36 +010020#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
21#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010022#endif
23
Willy Tarreau8d2b7772020-05-27 10:58:19 +020024#include <import/ebpttree.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010025
Willy Tarreaub2551052020-06-09 09:07:15 +020026#include <haproxy/api.h>
27#include <haproxy/applet.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020028#include <haproxy/arg.h>
Christopher Fauletd25d9262020-08-06 11:04:46 +020029#include <haproxy/auth.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020030#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020031#include <haproxy/channel.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020032#include <haproxy/cli.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020033#include <haproxy/connection.h>
Willy Tarreau5413a872020-06-02 19:33:08 +020034#include <haproxy/h1.h>
Willy Tarreau86416052020-06-04 09:20:54 +020035#include <haproxy/hlua.h>
Willy Tarreau8c794002020-06-04 10:05:25 +020036#include <haproxy/hlua_fcn.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020037#include <haproxy/http_ana.h>
Willy Tarreau126ba3a2020-06-04 18:26:43 +020038#include <haproxy/http_fetch.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020039#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020040#include <haproxy/http_rules.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020041#include <haproxy/log.h>
Willy Tarreau2cd58092020-06-04 15:10:43 +020042#include <haproxy/map.h>
Willy Tarreau8efbdfb2020-06-04 11:29:21 +020043#include <haproxy/obj_type.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020044#include <haproxy/pattern.h>
Willy Tarreau469509b2020-06-04 15:13:30 +020045#include <haproxy/payload.h>
Willy Tarreaua264d962020-06-04 22:29:18 +020046#include <haproxy/proxy-t.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020047#include <haproxy/regex.h>
Willy Tarreaue6ce10b2020-06-04 15:33:47 +020048#include <haproxy/sample.h>
Willy Tarreau1e56f922020-06-04 23:20:13 +020049#include <haproxy/server-t.h>
Willy Tarreau48d25b32020-06-04 18:58:52 +020050#include <haproxy/session.h>
Willy Tarreau2eec9b52020-06-04 19:58:55 +020051#include <haproxy/stats-t.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020052#include <haproxy/stream.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020053#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020054#include <haproxy/task.h>
Willy Tarreau8b550af2020-06-04 17:42:48 +020055#include <haproxy/tcp_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020056#include <haproxy/thread.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020057#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020058#include <haproxy/vars.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020059#include <haproxy/xref.h>
60
Thierry FOURNIER380d0932015-01-23 14:27:52 +010061
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010062/* Lua uses longjmp to perform yield or throwing errors. This
63 * macro is used only for identifying the function that can
64 * not return because a longjmp is executed.
65 * __LJMP marks a prototype of hlua file that can use longjmp.
66 * WILL_LJMP() marks an lua function that will use longjmp.
67 * MAY_LJMP() marks an lua function that may use longjmp.
68 */
69#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020070#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010071#define MAY_LJMP(func) func
72
Thierry FOURNIERbabae282015-09-17 11:36:37 +020073/* This couple of function executes securely some Lua calls outside of
74 * the lua runtime environment. Each Lua call can return a longjmp
75 * if it encounter a memory error.
76 *
77 * Lua documentation extract:
78 *
79 * If an error happens outside any protected environment, Lua calls
80 * a panic function (see lua_atpanic) and then calls abort, thus
81 * exiting the host application. Your panic function can avoid this
82 * exit by never returning (e.g., doing a long jump to your own
83 * recovery point outside Lua).
84 *
85 * The panic function runs as if it were a message handler (see
86 * §2.3); in particular, the error message is at the top of the
87 * stack. However, there is no guarantee about stack space. To push
88 * anything on the stack, the panic function must first check the
89 * available space (see §4.2).
90 *
91 * We must check all the Lua entry point. This includes:
92 * - The include/proto/hlua.h exported functions
93 * - the task wrapper function
94 * - The action wrapper function
95 * - The converters wrapper function
96 * - The sample-fetch wrapper functions
97 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +050098 * It is tolerated that the initialisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -080099 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200100 *
101 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
102 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
103 * because they must be exists in the program stack when the longjmp
104 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200105 *
106 * Note that the Lua processing is not really thread safe. It provides
107 * heavy system which consists to add our own lock function in the Lua
108 * code and recompile the library. This system will probably not accepted
109 * by maintainers of various distribs.
110 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500111 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200112 * quick looking on the Lua sources displays a lua_lock() a the start
113 * of function and a lua_unlock() at the end of the function. So I
114 * conclude that the Lua thread safe mode just perform a mutex around
115 * all execution. So I prefer to do this in the HAProxy code, it will be
116 * easier for distro maintainers.
117 *
118 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
119 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
120 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200121 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100122__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200123THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200124static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau9d6bb5a2020-02-06 15:55:41 +0100125static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200126
127#define SET_SAFE_LJMP(__L) \
128 ({ \
129 int ret; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100130 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200131 if (setjmp(safe_ljmp_env) != 0) { \
132 lua_atpanic(__L, hlua_panic_safe); \
133 ret = 0; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100134 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200135 } else { \
136 lua_atpanic(__L, hlua_panic_ljmp); \
137 ret = 1; \
138 } \
139 ret; \
140 })
141
142/* If we are the last function catching Lua errors, we
143 * must reset the panic function.
144 */
145#define RESET_SAFE_LJMP(__L) \
146 do { \
147 lua_atpanic(__L, hlua_panic_safe); \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100148 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200149 } while(0)
150
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200151/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200152#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100153/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200154#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200155/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100156#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100157#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200158
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100159/* The main Lua execution context. */
160struct hlua gL;
161
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100162/* This is the memory pool containing struct lua for applets
163 * (including cli).
164 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100165DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100166
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100167/* Used for Socket connection. */
168static struct proxy socket_proxy;
169static struct server socket_tcp;
170#ifdef USE_OPENSSL
171static struct server socket_ssl;
172#endif
173
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100174/* List head of the function called at the initialisation time. */
175struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
176
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100177/* The following variables contains the reference of the different
178 * Lua classes. These references are useful for identify metadata
179 * associated with an object.
180 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100181static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100182static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100183static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100184static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100185static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100186static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200187static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200188static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200189static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100190static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100191
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100192/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200193 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100194 * short timeout. Lua linked with tasks doesn't have a timeout
195 * because a task may remain alive during all the haproxy execution.
196 */
197static unsigned int hlua_timeout_session = 4000; /* session timeout. */
198static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200199static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100200
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100201/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
202 * it is used for preventing infinite loops.
203 *
204 * I test the scheer with an infinite loop containing one incrementation
205 * and one test. I run this loop between 10 seconds, I raise a ceil of
206 * 710M loops from one interrupt each 9000 instructions, so I fix the value
207 * to one interrupt each 10 000 instructions.
208 *
209 * configured | Number of
210 * instructions | loops executed
211 * between two | in milions
212 * forced yields |
213 * ---------------+---------------
214 * 10 | 160
215 * 500 | 670
216 * 1000 | 680
217 * 5000 | 700
218 * 7000 | 700
219 * 8000 | 700
220 * 9000 | 710 <- ceil
221 * 10000 | 710
222 * 100000 | 710
223 * 1000000 | 710
224 *
225 */
226static unsigned int hlua_nb_instruction = 10000;
227
Willy Tarreau32f61e22015-03-18 17:54:59 +0100228/* Descriptor for the memory allocation state. If limit is not null, it will
229 * be enforced on any memory allocation.
230 */
231struct hlua_mem_allocator {
232 size_t allocated;
233 size_t limit;
234};
235
236static struct hlua_mem_allocator hlua_global_allocator;
237
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100238/* These functions converts types between HAProxy internal args or
239 * sample and LUA types. Another function permits to check if the
240 * LUA stack contains arguments according with an required ARG_T
241 * format.
242 */
243static int hlua_arg2lua(lua_State *L, const struct arg *arg);
244static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100245__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100246 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100247static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100248static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100249static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
250
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100251__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200252
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200253#define SEND_ERR(__be, __fmt, __args...) \
254 do { \
255 send_log(__be, LOG_ERR, __fmt, ## __args); \
256 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100257 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200258 } while (0)
259
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100260/* Used to check an Lua function type in the stack. It creates and
261 * returns a reference of the function. This function throws an
262 * error if the rgument is not a "function".
263 */
264__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
265{
266 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100267 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100268 WILL_LJMP(luaL_argerror(L, argno, msg));
269 }
270 lua_pushvalue(L, argno);
271 return luaL_ref(L, LUA_REGISTRYINDEX);
272}
273
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200274/* Return the string that is of the top of the stack. */
275const char *hlua_get_top_error_string(lua_State *L)
276{
277 if (lua_gettop(L) < 1)
278 return "unknown error";
279 if (lua_type(L, -1) != LUA_TSTRING)
280 return "unknown error";
281 return lua_tostring(L, -1);
282}
283
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200284__LJMP static const char *hlua_traceback(lua_State *L)
285{
286 lua_Debug ar;
287 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200288 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200289 int filled = 0;
290
291 while (lua_getstack(L, level++, &ar)) {
292
293 /* Add separator */
294 if (filled)
295 chunk_appendf(msg, ", ");
296 filled = 1;
297
298 /* Fill fields:
299 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
300 * 'l': fills in the field currentline;
301 * 'n': fills in the field name and namewhat;
302 * 't': fills in the field istailcall;
303 */
304 lua_getinfo(L, "Slnt", &ar);
305
306 /* Append code localisation */
307 if (ar.currentline > 0)
308 chunk_appendf(msg, "%s:%d ", ar.short_src, ar.currentline);
309 else
310 chunk_appendf(msg, "%s ", ar.short_src);
311
312 /*
313 * Get function name
314 *
315 * if namewhat is no empty, name is defined.
316 * what contains "Lua" for Lua function, "C" for C function,
317 * or "main" for main code.
318 */
319 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
320 chunk_appendf(msg, "%s '%s'", ar.namewhat, ar.name); /* use it */
321
322 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
323 chunk_appendf(msg, "main chunk");
324
325 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
326 chunk_appendf(msg, "C function line %d", ar.linedefined);
327
328 else /* nothing left... */
329 chunk_appendf(msg, "?");
330
331
332 /* Display tailed call */
333 if (ar.istailcall)
334 chunk_appendf(msg, " ...");
335 }
336
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200337 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200338}
339
340
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100341/* This function check the number of arguments available in the
342 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500343 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100344 */
345__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
346{
347 if (lua_gettop(L) == nb)
348 return;
349 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
350}
351
Mark Lakes22154b42018-01-29 14:38:40 -0800352/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100353 * and the line number where the error is encountered.
354 */
355static int hlua_pusherror(lua_State *L, const char *fmt, ...)
356{
357 va_list argp;
358 va_start(argp, fmt);
359 luaL_where(L, 1);
360 lua_pushvfstring(L, fmt, argp);
361 va_end(argp);
362 lua_concat(L, 2);
363 return 1;
364}
365
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100366/* This functions is used with sample fetch and converters. It
367 * converts the HAProxy configuration argument in a lua stack
368 * values.
369 *
370 * It takes an array of "arg", and each entry of the array is
371 * converted and pushed in the LUA stack.
372 */
373static int hlua_arg2lua(lua_State *L, const struct arg *arg)
374{
375 switch (arg->type) {
376 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100377 case ARGT_TIME:
378 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100379 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100380 break;
381
382 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200383 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100384 break;
385
386 case ARGT_IPV4:
387 case ARGT_IPV6:
388 case ARGT_MSK4:
389 case ARGT_MSK6:
390 case ARGT_FE:
391 case ARGT_BE:
392 case ARGT_TAB:
393 case ARGT_SRV:
394 case ARGT_USR:
395 case ARGT_MAP:
396 default:
397 lua_pushnil(L);
398 break;
399 }
400 return 1;
401}
402
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500403/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100404 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500405 * with sample fetch wrappers. The input arguments are given to the
406 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100407 */
408static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
409{
410 switch (lua_type(L, ud)) {
411
412 case LUA_TNUMBER:
413 case LUA_TBOOLEAN:
414 arg->type = ARGT_SINT;
415 arg->data.sint = lua_tointeger(L, ud);
416 break;
417
418 case LUA_TSTRING:
419 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200420 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200421 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200422 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200423 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100424 break;
425
426 case LUA_TUSERDATA:
427 case LUA_TNIL:
428 case LUA_TTABLE:
429 case LUA_TFUNCTION:
430 case LUA_TTHREAD:
431 case LUA_TLIGHTUSERDATA:
432 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200433 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100434 break;
435 }
436 return 1;
437}
438
439/* the following functions are used to convert a struct sample
440 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500441 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100442 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100443static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100444{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200445 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100446 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100447 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200448 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100449 break;
450
451 case SMP_T_BIN:
452 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200453 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100454 break;
455
456 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200457 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100458 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
459 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
460 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
461 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
462 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
463 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
464 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
465 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
466 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200467 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100468 break;
469 default:
470 lua_pushnil(L);
471 break;
472 }
473 break;
474
475 case SMP_T_IPV4:
476 case SMP_T_IPV6:
477 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200478 if (sample_casts[smp->data.type][SMP_T_STR] &&
479 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200480 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100481 else
482 lua_pushnil(L);
483 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100484 default:
485 lua_pushnil(L);
486 break;
487 }
488 return 1;
489}
490
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100491/* the following functions are used to convert a struct sample
492 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500493 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100494 */
495static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
496{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200497 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100498
499 case SMP_T_BIN:
500 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200501 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100502 break;
503
504 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200505 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100506 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
507 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
508 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
509 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
510 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
511 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
512 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
513 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
514 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200515 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100516 break;
517 default:
518 lua_pushstring(L, "");
519 break;
520 }
521 break;
522
523 case SMP_T_SINT:
524 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100525 case SMP_T_IPV4:
526 case SMP_T_IPV6:
527 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200528 if (sample_casts[smp->data.type][SMP_T_STR] &&
529 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200530 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100531 else
532 lua_pushstring(L, "");
533 break;
534 default:
535 lua_pushstring(L, "");
536 break;
537 }
538 return 1;
539}
540
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100541/* the following functions are used to convert an Lua type in a
542 * struct sample. This is useful to provide data from a converter
543 * to the LUA code.
544 */
545static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
546{
547 switch (lua_type(L, ud)) {
548
549 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200550 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200551 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100552 break;
553
554
555 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200556 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200557 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100558 break;
559
560 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200561 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100562 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200563 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200564 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200565 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200566 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100567 break;
568
569 case LUA_TUSERDATA:
570 case LUA_TNIL:
571 case LUA_TTABLE:
572 case LUA_TFUNCTION:
573 case LUA_TTHREAD:
574 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200575 case LUA_TNONE:
576 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200577 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200578 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100579 break;
580 }
581 return 1;
582}
583
Ilya Shipitsind4259502020-04-08 01:07:56 +0500584/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800585 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100586 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100587 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500588 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100589 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100590 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100591__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100592 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100593{
594 int min_arg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200595 int i, idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100596 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200597 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200598 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200599 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200600 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100601
602 idx = 0;
603 min_arg = ARGM(mask);
604 mask >>= ARGM_BITS;
605
606 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200607 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100608
609 /* Check oversize. */
610 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200611 msg = "Malformed argument mask";
612 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100613 }
614
615 /* Check for mandatory arguments. */
616 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100617 if (idx < min_arg) {
618
619 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200620 if (idx > 0) {
621 msg = "Mandatory argument expected";
622 goto error;
623 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100624
625 /* If first argument have a certain type, some default values
626 * may be used. See the function smp_resolve_args().
627 */
628 switch (mask & ARGT_MASK) {
629
630 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200631 if (!(p->cap & PR_CAP_FE)) {
632 msg = "Mandatory argument expected";
633 goto error;
634 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100635 argp[idx].data.prx = p;
636 argp[idx].type = ARGT_FE;
637 argp[idx+1].type = ARGT_STOP;
638 break;
639
640 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200641 if (!(p->cap & PR_CAP_BE)) {
642 msg = "Mandatory argument expected";
643 goto error;
644 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100645 argp[idx].data.prx = p;
646 argp[idx].type = ARGT_BE;
647 argp[idx+1].type = ARGT_STOP;
648 break;
649
650 case ARGT_TAB:
651 argp[idx].data.prx = p;
652 argp[idx].type = ARGT_TAB;
653 argp[idx+1].type = ARGT_STOP;
654 break;
655
656 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200657 msg = "Mandatory argument expected";
658 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100659 break;
660 }
661 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200662 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100663 }
664
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500665 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100666 if ((mask & ARGT_MASK) == ARGT_STOP &&
667 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200668 msg = "Last argument expected";
669 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100670 }
671
672 if ((mask & ARGT_MASK) == ARGT_STOP &&
673 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200674 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100675 }
676
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200677 /* Convert some argument types. All string in argp[] are for not
678 * duplicated yet.
679 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100680 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100681 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200682 if (argp[idx].type != ARGT_SINT) {
683 msg = "integer expected";
684 goto error;
685 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100686 argp[idx].type = ARGT_SINT;
687 break;
688
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100689 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200690 if (argp[idx].type != ARGT_SINT) {
691 msg = "integer expected";
692 goto error;
693 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200694 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100695 break;
696
697 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200698 if (argp[idx].type != ARGT_SINT) {
699 msg = "integer expected";
700 goto error;
701 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200702 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100703 break;
704
705 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200706 if (argp[idx].type != ARGT_STR) {
707 msg = "string expected";
708 goto error;
709 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200710 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200711 if (!argp[idx].data.prx) {
712 msg = "frontend doesn't exist";
713 goto error;
714 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100715 argp[idx].type = ARGT_FE;
716 break;
717
718 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200719 if (argp[idx].type != ARGT_STR) {
720 msg = "string expected";
721 goto error;
722 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200723 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200724 if (!argp[idx].data.prx) {
725 msg = "backend doesn't exist";
726 goto error;
727 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100728 argp[idx].type = ARGT_BE;
729 break;
730
731 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200732 if (argp[idx].type != ARGT_STR) {
733 msg = "string expected";
734 goto error;
735 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200736 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200737 if (!argp[idx].data.t) {
738 msg = "table doesn't exist";
739 goto error;
740 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100741 argp[idx].type = ARGT_TAB;
742 break;
743
744 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200745 if (argp[idx].type != ARGT_STR) {
746 msg = "string expected";
747 goto error;
748 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200749 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100750 if (sname) {
751 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200752 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200753 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200754 if (!px) {
755 msg = "backend doesn't exist";
756 goto error;
757 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100758 }
759 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200760 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100761 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100762 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100763 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200764 if (!argp[idx].data.srv) {
765 msg = "server doesn't exist";
766 goto error;
767 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100768 argp[idx].type = ARGT_SRV;
769 break;
770
771 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200772 if (argp[idx].type != ARGT_STR) {
773 msg = "string expected";
774 goto error;
775 }
776 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
777 msg = "invalid IPv4 address";
778 goto error;
779 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100780 argp[idx].type = ARGT_IPV4;
781 break;
782
783 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +0200784 if (argp[idx].type == ARGT_SINT)
785 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
786 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200787 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
788 msg = "invalid IPv4 mask";
789 goto error;
790 }
791 }
792 else {
793 msg = "integer or string expected";
794 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +0200795 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100796 argp[idx].type = ARGT_MSK4;
797 break;
798
799 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200800 if (argp[idx].type != ARGT_STR) {
801 msg = "string expected";
802 goto error;
803 }
804 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
805 msg = "invalid IPv6 address";
806 goto error;
807 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100808 argp[idx].type = ARGT_IPV6;
809 break;
810
811 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +0200812 if (argp[idx].type == ARGT_SINT)
813 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
814 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200815 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
816 msg = "invalid IPv6 mask";
817 goto error;
818 }
819 }
820 else {
821 msg = "integer or string expected";
822 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +0200823 }
Tim Duesterhusb814da62018-01-25 16:24:50 +0100824 argp[idx].type = ARGT_MSK6;
825 break;
826
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200827 case ARGT_REG:
828 if (argp[idx].type != ARGT_STR) {
829 msg = "string expected";
830 goto error;
831 }
832 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
833 if (!reg) {
834 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
835 argp[idx].data.str.area, err);
836 free(err);
837 goto error;
838 }
839 argp[idx].type = ARGT_REG;
840 argp[idx].data.reg = reg;
841 break;
842
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100843 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +0200844 if (argp[idx].type != ARGT_STR) {
845 msg = "string expected";
846 goto error;
847 }
848 if (p->uri_auth && p->uri_auth->userlist &&
849 !strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area))
850 ul = p->uri_auth->userlist;
851 else
852 ul = auth_find_userlist(argp[idx].data.str.area);
853
854 if (!ul) {
855 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
856 goto error;
857 }
858 argp[idx].type = ARGT_USR;
859 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200860 break;
861
862 case ARGT_STR:
863 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
864 msg = "unable to duplicate string arg";
865 goto error;
866 }
867 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100868 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200869
Christopher Fauletd25d9262020-08-06 11:04:46 +0200870 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +0200871 msg = "type not yet supported";
872 goto error;
873 break;
874
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100875 }
876
877 /* Check for type of argument. */
878 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200879 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
880 arg_type_names[(mask & ARGT_MASK)],
881 arg_type_names[argp[idx].type & ARGT_MASK]);
882 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100883 }
884
885 /* Next argument. */
886 mask >>= ARGT_BITS;
887 idx++;
888 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200889 return 0;
890
891 error:
892 for (i = 0; i < idx; i++) {
893 if (argp[i].type == ARGT_STR)
894 chunk_destroy(&argp[i].data.str);
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200895 else if (argp[i].type == ARGT_REG)
896 regex_free(argp[i].data.reg);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200897 }
898 WILL_LJMP(luaL_argerror(L, first + idx, msg));
899 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100900}
901
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100902/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500903 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100904 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100905 *
906 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100907 * - hlua_sethlua : create the association between hlua context and lua_state.
908 */
909static inline struct hlua *hlua_gethlua(lua_State *L)
910{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100911 struct hlua **hlua = lua_getextraspace(L);
912 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100913}
914static inline void hlua_sethlua(struct hlua *hlua)
915{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100916 struct hlua **hlua_store = lua_getextraspace(hlua->T);
917 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100918}
919
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100920/* This function is used to send logs. It try to send on screen (stderr)
921 * and on the default syslog server.
922 */
923static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
924{
925 struct tm tm;
926 char *p;
927
928 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200929 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100930 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200931 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200932 /* Break the message if exceed the buffer size. */
933 *(p-4) = ' ';
934 *(p-3) = '.';
935 *(p-2) = '.';
936 *(p-1) = '.';
937 break;
938 }
Willy Tarreau90807112020-02-25 08:16:33 +0100939 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100940 *p = *msg;
941 else
942 *p = '.';
943 }
944 *p = '\0';
945
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200946 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100947 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +0200948 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
949 return;
950
Willy Tarreaua678b432015-08-28 10:14:59 +0200951 get_localtime(date.tv_sec, &tm);
952 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100953 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200954 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100955 fflush(stderr);
956 }
957}
958
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100959/* This function just ensure that the yield will be always
960 * returned with a timeout and permit to set some flags
961 */
962__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100963 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100964{
965 struct hlua *hlua = hlua_gethlua(L);
966
967 /* Set the wake timeout. If timeout is required, we set
968 * the expiration time.
969 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200970 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100971
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100972 hlua->flags |= flags;
973
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100974 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +0200975 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100976}
977
Willy Tarreau87b09662015-04-03 00:22:06 +0200978/* This function initialises the Lua environment stored in the stream.
979 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100980 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200981 *
982 * This function is particular. it initialises a new Lua thread. If the
983 * initialisation fails (example: out of memory error), the lua function
984 * throws an error (longjmp).
985 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100986 * In some case (at least one), this function can be called from safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500987 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100988 * threads appear, the safe environment set a lock to ensure only one
989 * Lua execution at a time. If we initialize safe environment in another
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500990 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100991 *
992 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500993 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100994 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800995 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200996 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800997 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500998 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100999 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001000int hlua_ctx_init(struct hlua *lua, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001001{
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001002 if (!already_safe) {
1003 if (!SET_SAFE_LJMP(gL.T)) {
1004 lua->Tref = LUA_REFNIL;
1005 return 0;
1006 }
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001007 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001008 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001009 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001010 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001011 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001012 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001013 lua->T = lua_newthread(gL.T);
1014 if (!lua->T) {
1015 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001016 if (!already_safe)
1017 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001018 return 0;
1019 }
1020 hlua_sethlua(lua);
1021 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
1022 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001023 if (!already_safe)
1024 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001025 return 1;
1026}
1027
Willy Tarreau87b09662015-04-03 00:22:06 +02001028/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001029 * is destroyed. The destroy also the memory context. The struct "lua"
1030 * is not freed.
1031 */
1032void hlua_ctx_destroy(struct hlua *lua)
1033{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001034 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001035 return;
1036
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001037 if (!lua->T)
1038 goto end;
1039
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001040 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001041 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001042
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001043 if (!SET_SAFE_LJMP(lua->T))
1044 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001045 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001046 RESET_SAFE_LJMP(lua->T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001047
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001048 if (!SET_SAFE_LJMP(gL.T))
1049 return;
1050 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
1051 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001052 /* Forces a garbage collecting process. If the Lua program is finished
1053 * without error, we run the GC on the thread pointer. Its freed all
1054 * the unused memory.
1055 * If the thread is finnish with an error or is currently yielded,
1056 * it seems that the GC applied on the thread doesn't clean anything,
1057 * so e run the GC on the main thread.
1058 * NOTE: maybe this action locks all the Lua threads untiml the en of
1059 * the garbage collection.
1060 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001061 if (lua->gc_count) {
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +02001062 if (!SET_SAFE_LJMP(gL.T))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001063 return;
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +02001064 lua_gc(gL.T, LUA_GCCOLLECT, 0);
1065 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001066 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001067
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001068 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001069
1070end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001071 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001072}
1073
1074/* This function is used to restore the Lua context when a coroutine
1075 * fails. This function copy the common memory between old coroutine
1076 * and the new coroutine. The old coroutine is destroyed, and its
1077 * replaced by the new coroutine.
1078 * If the flag "keep_msg" is set, the last entry of the old is assumed
1079 * as string error message and it is copied in the new stack.
1080 */
1081static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1082{
1083 lua_State *T;
1084 int new_ref;
1085
1086 /* Renew the main LUA stack doesn't have sense. */
1087 if (lua == &gL)
1088 return 0;
1089
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001090 /* New Lua coroutine. */
1091 T = lua_newthread(gL.T);
1092 if (!T)
1093 return 0;
1094
1095 /* Copy last error message. */
1096 if (keep_msg)
1097 lua_xmove(lua->T, T, 1);
1098
1099 /* Copy data between the coroutines. */
1100 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1101 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001102 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001103
1104 /* Destroy old data. */
1105 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1106
1107 /* The thread is garbage collected by Lua. */
1108 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
1109
1110 /* Fill the struct with the new coroutine values. */
1111 lua->Mref = new_ref;
1112 lua->T = T;
1113 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
1114
1115 /* Set context. */
1116 hlua_sethlua(lua);
1117
1118 return 1;
1119}
1120
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001121void hlua_hook(lua_State *L, lua_Debug *ar)
1122{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001123 struct hlua *hlua = hlua_gethlua(L);
1124
1125 /* Lua cannot yield when its returning from a function,
1126 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001127 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001128 */
1129 if (lua_gethookmask(L) & LUA_MASKRET) {
1130 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1131 return;
1132 }
1133
1134 /* restore the interrupt condition. */
1135 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1136
1137 /* If we interrupt the Lua processing in yieldable state, we yield.
1138 * If the state is not yieldable, trying yield causes an error.
1139 */
1140 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001141 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001142
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001143 /* If we cannot yield, update the clock and check the timeout. */
1144 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001145 hlua->run_time += now_ms - hlua->start_time;
1146 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001147 lua_pushfstring(L, "execution timeout");
1148 WILL_LJMP(lua_error(L));
1149 }
1150
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001151 /* Update the start time. */
1152 hlua->start_time = now_ms;
1153
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001154 /* Try to interrupt the process at the end of the current
1155 * unyieldable function.
1156 */
1157 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001158}
1159
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001160/* This function start or resumes the Lua stack execution. If the flag
1161 * "yield_allowed" if no set and the LUA stack execution returns a yield
1162 * The function return an error.
1163 *
1164 * The function can returns 4 values:
1165 * - HLUA_E_OK : The execution is terminated without any errors.
1166 * - HLUA_E_AGAIN : The execution must continue at the next associated
1167 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001168 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001169 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001170 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001171 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001172 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001173 * LUA code.
1174 */
1175static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1176{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001177#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1178 int nres;
1179#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001180 int ret;
1181 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001182 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001183
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001184 /* Initialise run time counter. */
1185 if (!HLUA_IS_RUNNING(lua))
1186 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001187
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001188 /* Lock the whole Lua execution. This lock must be before the
1189 * label "resume_execution".
1190 */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001191 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001192
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001193resume_execution:
1194
1195 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1196 * instructions. it is used for preventing infinite loops.
1197 */
1198 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1199
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001200 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001201 HLUA_SET_RUN(lua);
1202 HLUA_CLR_CTRLYIELD(lua);
1203 HLUA_CLR_WAKERESWR(lua);
1204 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001205
Christopher Fauletbc275a92020-02-26 14:55:16 +01001206 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001207 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001208 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001209
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001210 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001211#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1212 ret = lua_resume(lua->T, gL.T, lua->nargs, &nres);
1213#else
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001214 ret = lua_resume(lua->T, gL.T, lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001215#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001216 switch (ret) {
1217
1218 case LUA_OK:
1219 ret = HLUA_E_OK;
1220 break;
1221
1222 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001223 /* Check if the execution timeout is expired. It it is the case, we
1224 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001225 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001226 tv_update_date(0, 1);
1227 lua->run_time += now_ms - lua->start_time;
1228 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001229 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001230 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001231 break;
1232 }
1233 /* Process the forced yield. if the general yield is not allowed or
1234 * if no task were associated this the current Lua execution
1235 * coroutine, we resume the execution. Else we want to return in the
1236 * scheduler and we want to be waked up again, to continue the
1237 * current Lua execution. So we schedule our own task.
1238 */
1239 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001240 if (!yield_allowed || !lua->task)
1241 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001242 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001243 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001244 if (!yield_allowed) {
1245 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001246 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001247 break;
1248 }
1249 ret = HLUA_E_AGAIN;
1250 break;
1251
1252 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001253
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001254 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001255 * because the errors ares the only one mean to return immediately
1256 * from and lua execution.
1257 */
1258 if (lua->flags & HLUA_EXIT) {
1259 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001260 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001261 break;
1262 }
1263
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001264 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001265 if (!lua_checkstack(lua->T, 1)) {
1266 ret = HLUA_E_ERR;
1267 break;
1268 }
1269 msg = lua_tostring(lua->T, -1);
1270 lua_settop(lua->T, 0); /* Empty the stack. */
1271 lua_pop(lua->T, 1);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001272 trace = hlua_traceback(lua->T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001273 if (msg)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001274 lua_pushfstring(lua->T, "runtime error: %s from %s", msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001275 else
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001276 lua_pushfstring(lua->T, "unknown runtime error from %s", trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001277 ret = HLUA_E_ERRMSG;
1278 break;
1279
1280 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001281 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001282 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001283 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001284 break;
1285
1286 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001287 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001288 if (!lua_checkstack(lua->T, 1)) {
1289 ret = HLUA_E_ERR;
1290 break;
1291 }
1292 msg = lua_tostring(lua->T, -1);
1293 lua_settop(lua->T, 0); /* Empty the stack. */
1294 lua_pop(lua->T, 1);
1295 if (msg)
1296 lua_pushfstring(lua->T, "message handler error: %s", msg);
1297 else
1298 lua_pushfstring(lua->T, "message handler error");
1299 ret = HLUA_E_ERRMSG;
1300 break;
1301
1302 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001303 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001304 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001305 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001306 break;
1307 }
1308
1309 switch (ret) {
1310 case HLUA_E_AGAIN:
1311 break;
1312
1313 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001314 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001315 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001316 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001317 break;
1318
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001319 case HLUA_E_ETMOUT:
1320 case HLUA_E_NOMEM:
1321 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001322 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001323 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001324 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001325 hlua_ctx_renew(lua, 0);
1326 break;
1327
1328 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001329 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001330 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001331 break;
1332 }
1333
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001334 /* This is the main exit point, remove the Lua lock. */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001335 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001336
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001337 return ret;
1338}
1339
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001340/* This function exit the current code. */
1341__LJMP static int hlua_done(lua_State *L)
1342{
1343 struct hlua *hlua = hlua_gethlua(L);
1344
1345 hlua->flags |= HLUA_EXIT;
1346 WILL_LJMP(lua_error(L));
1347
1348 return 0;
1349}
1350
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001351/* This function is an LUA binding. It provides a function
1352 * for deleting ACL from a referenced ACL file.
1353 */
1354__LJMP static int hlua_del_acl(lua_State *L)
1355{
1356 const char *name;
1357 const char *key;
1358 struct pat_ref *ref;
1359
1360 MAY_LJMP(check_args(L, 2, "del_acl"));
1361
1362 name = MAY_LJMP(luaL_checkstring(L, 1));
1363 key = MAY_LJMP(luaL_checkstring(L, 2));
1364
1365 ref = pat_ref_lookup(name);
1366 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001367 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001368
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001369 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001370 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001371 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001372 return 0;
1373}
1374
1375/* This function is an LUA binding. It provides a function
1376 * for deleting map entry from a referenced map file.
1377 */
1378static int hlua_del_map(lua_State *L)
1379{
1380 const char *name;
1381 const char *key;
1382 struct pat_ref *ref;
1383
1384 MAY_LJMP(check_args(L, 2, "del_map"));
1385
1386 name = MAY_LJMP(luaL_checkstring(L, 1));
1387 key = MAY_LJMP(luaL_checkstring(L, 2));
1388
1389 ref = pat_ref_lookup(name);
1390 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001391 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001392
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001393 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001394 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001395 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001396 return 0;
1397}
1398
1399/* This function is an LUA binding. It provides a function
1400 * for adding ACL pattern from a referenced ACL file.
1401 */
1402static int hlua_add_acl(lua_State *L)
1403{
1404 const char *name;
1405 const char *key;
1406 struct pat_ref *ref;
1407
1408 MAY_LJMP(check_args(L, 2, "add_acl"));
1409
1410 name = MAY_LJMP(luaL_checkstring(L, 1));
1411 key = MAY_LJMP(luaL_checkstring(L, 2));
1412
1413 ref = pat_ref_lookup(name);
1414 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001415 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001416
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001417 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001418 if (pat_ref_find_elt(ref, key) == NULL)
1419 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001420 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001421 return 0;
1422}
1423
1424/* This function is an LUA binding. It provides a function
1425 * for setting map pattern and sample from a referenced map
1426 * file.
1427 */
1428static int hlua_set_map(lua_State *L)
1429{
1430 const char *name;
1431 const char *key;
1432 const char *value;
1433 struct pat_ref *ref;
1434
1435 MAY_LJMP(check_args(L, 3, "set_map"));
1436
1437 name = MAY_LJMP(luaL_checkstring(L, 1));
1438 key = MAY_LJMP(luaL_checkstring(L, 2));
1439 value = MAY_LJMP(luaL_checkstring(L, 3));
1440
1441 ref = pat_ref_lookup(name);
1442 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001443 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001444
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001445 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001446 if (pat_ref_find_elt(ref, key) != NULL)
1447 pat_ref_set(ref, key, value, NULL);
1448 else
1449 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001450 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001451 return 0;
1452}
1453
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001454/* A class is a lot of memory that contain data. This data can be a table,
1455 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001456 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001457 * the name of the object (_G[<name>] = <metable> ).
1458 *
1459 * A metable is a table that modify the standard behavior of a standard
1460 * access to the associated data. The entries of this new metatable are
1461 * defined as is:
1462 *
1463 * http://lua-users.org/wiki/MetatableEvents
1464 *
1465 * __index
1466 *
1467 * we access an absent field in a table, the result is nil. This is
1468 * true, but it is not the whole truth. Actually, such access triggers
1469 * the interpreter to look for an __index metamethod: If there is no
1470 * such method, as usually happens, then the access results in nil;
1471 * otherwise, the metamethod will provide the result.
1472 *
1473 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1474 * the key does not appear in the table, but the metatable has an __index
1475 * property:
1476 *
1477 * - if the value is a function, the function is called, passing in the
1478 * table and the key; the return value of that function is returned as
1479 * the result.
1480 *
1481 * - if the value is another table, the value of the key in that table is
1482 * asked for and returned (and if it doesn't exist in that table, but that
1483 * table's metatable has an __index property, then it continues on up)
1484 *
1485 * - Use "rawget(myTable,key)" to skip this metamethod.
1486 *
1487 * http://www.lua.org/pil/13.4.1.html
1488 *
1489 * __newindex
1490 *
1491 * Like __index, but control property assignment.
1492 *
1493 * __mode - Control weak references. A string value with one or both
1494 * of the characters 'k' and 'v' which specifies that the the
1495 * keys and/or values in the table are weak references.
1496 *
1497 * __call - Treat a table like a function. When a table is followed by
1498 * parenthesis such as "myTable( 'foo' )" and the metatable has
1499 * a __call key pointing to a function, that function is invoked
1500 * (passing any specified arguments) and the return value is
1501 * returned.
1502 *
1503 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1504 * called, if the metatable for myTable has a __metatable
1505 * key, the value of that key is returned instead of the
1506 * actual metatable.
1507 *
1508 * __tostring - Control string representation. When the builtin
1509 * "tostring( myTable )" function is called, if the metatable
1510 * for myTable has a __tostring property set to a function,
1511 * that function is invoked (passing myTable to it) and the
1512 * return value is used as the string representation.
1513 *
1514 * __len - Control table length. When the table length is requested using
1515 * the length operator ( '#' ), if the metatable for myTable has
1516 * a __len key pointing to a function, that function is invoked
1517 * (passing myTable to it) and the return value used as the value
1518 * of "#myTable".
1519 *
1520 * __gc - Userdata finalizer code. When userdata is set to be garbage
1521 * collected, if the metatable has a __gc field pointing to a
1522 * function, that function is first invoked, passing the userdata
1523 * to it. The __gc metamethod is not called for tables.
1524 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1525 *
1526 * Special metamethods for redefining standard operators:
1527 * http://www.lua.org/pil/13.1.html
1528 *
1529 * __add "+"
1530 * __sub "-"
1531 * __mul "*"
1532 * __div "/"
1533 * __unm "!"
1534 * __pow "^"
1535 * __concat ".."
1536 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001537 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001538 * http://www.lua.org/pil/13.2.html
1539 *
1540 * __eq "=="
1541 * __lt "<"
1542 * __le "<="
1543 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001544
1545/*
1546 *
1547 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001548 * Class Map
1549 *
1550 *
1551 */
1552
1553/* Returns a struct hlua_map if the stack entry "ud" is
1554 * a class session, otherwise it throws an error.
1555 */
1556__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1557{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001558 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001559}
1560
1561/* This function is the map constructor. It don't need
1562 * the class Map object. It creates and return a new Map
1563 * object. It must be called only during "body" or "init"
1564 * context because it process some filesystem accesses.
1565 */
1566__LJMP static int hlua_map_new(struct lua_State *L)
1567{
1568 const char *fn;
1569 int match = PAT_MATCH_STR;
1570 struct sample_conv conv;
1571 const char *file = "";
1572 int line = 0;
1573 lua_Debug ar;
1574 char *err = NULL;
1575 struct arg args[2];
1576
1577 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1578 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1579
1580 fn = MAY_LJMP(luaL_checkstring(L, 1));
1581
1582 if (lua_gettop(L) >= 2) {
1583 match = MAY_LJMP(luaL_checkinteger(L, 2));
1584 if (match < 0 || match >= PAT_MATCH_NUM)
1585 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1586 }
1587
1588 /* Get Lua filename and line number. */
1589 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1590 lua_getinfo(L, "Sl", &ar); /* get info about it */
1591 if (ar.currentline > 0) { /* is there info? */
1592 file = ar.short_src;
1593 line = ar.currentline;
1594 }
1595 }
1596
1597 /* fill fake sample_conv struct. */
1598 conv.kw = ""; /* unused. */
1599 conv.process = NULL; /* unused. */
1600 conv.arg_mask = 0; /* unused. */
1601 conv.val_args = NULL; /* unused. */
1602 conv.out_type = SMP_T_STR;
1603 conv.private = (void *)(long)match;
1604 switch (match) {
1605 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1606 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1607 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1608 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1609 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1610 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1611 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001612 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001613 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1614 default:
1615 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1616 }
1617
1618 /* fill fake args. */
1619 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001620 args[0].data.str.area = strdup(fn);
1621 args[0].data.str.data = strlen(fn);
1622 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001623 args[1].type = ARGT_STOP;
1624
1625 /* load the map. */
1626 if (!sample_load_map(args, &conv, file, line, &err)) {
1627 /* error case: we cant use luaL_error because we must
1628 * free the err variable.
1629 */
1630 luaL_where(L, 1);
1631 lua_pushfstring(L, "'new': %s.", err);
1632 lua_concat(L, 2);
1633 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001634 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001635 WILL_LJMP(lua_error(L));
1636 }
1637
1638 /* create the lua object. */
1639 lua_newtable(L);
1640 lua_pushlightuserdata(L, args[0].data.map);
1641 lua_rawseti(L, -2, 0);
1642
1643 /* Pop a class Map metatable and affect it to the userdata. */
1644 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1645 lua_setmetatable(L, -2);
1646
1647
1648 return 1;
1649}
1650
1651__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1652{
1653 struct map_descriptor *desc;
1654 struct pattern *pat;
1655 struct sample smp;
1656
1657 MAY_LJMP(check_args(L, 2, "lookup"));
1658 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001659 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001660 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001661 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001662 }
1663 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001664 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001665 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001666 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 +02001667 }
1668
1669 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001670 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001671 if (str)
1672 lua_pushstring(L, "");
1673 else
1674 lua_pushnil(L);
1675 return 1;
1676 }
1677
1678 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001679 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001680 return 1;
1681}
1682
1683__LJMP static int hlua_map_lookup(struct lua_State *L)
1684{
1685 return _hlua_map_lookup(L, 0);
1686}
1687
1688__LJMP static int hlua_map_slookup(struct lua_State *L)
1689{
1690 return _hlua_map_lookup(L, 1);
1691}
1692
1693/*
1694 *
1695 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001696 * Class Socket
1697 *
1698 *
1699 */
1700
1701__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1702{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001703 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001704}
1705
1706/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001707 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001708 * received.
1709 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001710static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001711{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001712 struct stream_interface *si = appctx->owner;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001713
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001714 if (appctx->ctx.hlua_cosocket.die) {
1715 si_shutw(si);
1716 si_shutr(si);
1717 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001718 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1719 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001720 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1721 }
1722
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001723 /* If we cant write, wakeup the pending write signals. */
1724 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001725 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001726
1727 /* If we cant read, wakeup the pending read signals. */
1728 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001729 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001730
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001731 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001732 * to be notified whenever the connection completes.
1733 */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001734 if (si_opposite(si)->state < SI_ST_EST) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01001735 si_cant_get(si);
Willy Tarreau12c24232018-12-06 15:29:50 +01001736 si_rx_conn_blk(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01001737 si_rx_endp_more(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001738 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001739 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001740
1741 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001742 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001743
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001744 /* Wake the tasks which wants to write if the buffer have available space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001745 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001746 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001747
1748 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001749 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001750 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001751
1752 /* Some data were injected in the buffer, notify the stream
1753 * interface.
1754 */
1755 if (!channel_is_empty(si_ic(si)))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001756 si_update(si);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001757
1758 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01001759 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001760 */
1761 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
Willy Tarreau3367d412018-11-15 10:57:41 +01001762 si_rx_endp_more(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001763}
1764
Willy Tarreau87b09662015-04-03 00:22:06 +02001765/* This function is called when the "struct stream" is destroyed.
1766 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001767 * Wake all the pending signals.
1768 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001769static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001770{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001771 struct xref *peer;
1772
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001773 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001774 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1775 if (peer)
1776 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001777
1778 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001779 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1780 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001781}
1782
1783/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001784 * uses this object. If the stream does not exists, just quit.
1785 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001786 * pending signal can rest in the read and write lists. destroy
1787 * it.
1788 */
1789__LJMP static int hlua_socket_gc(lua_State *L)
1790{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001791 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001792 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001793 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001794
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001795 MAY_LJMP(check_args(L, 1, "__gc"));
1796
1797 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001798 peer = xref_get_peer_and_lock(&socket->xref);
1799 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001800 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001801 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001802
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001803 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001804 appctx->ctx.hlua_cosocket.die = 1;
1805 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001806
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001807 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001808 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001809 return 0;
1810}
1811
1812/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001813 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001814 */
sada05ed3302018-05-11 11:48:18 -07001815__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001816{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001817 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001818 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001819 struct xref *peer;
Willy Tarreauf31af932020-01-14 09:59:38 +01001820 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001821
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001822 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001823
1824 /* Check if we run on the same thread than the xreator thread.
1825 * We cannot access to the socket if the thread is different.
1826 */
1827 if (socket->tid != tid)
1828 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1829
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001830 peer = xref_get_peer_and_lock(&socket->xref);
1831 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001832 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001833
1834 hlua->gc_count--;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001835 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001836
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001837 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001838 appctx->ctx.hlua_cosocket.die = 1;
1839 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001840
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001841 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001842 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001843 return 0;
1844}
1845
sada05ed3302018-05-11 11:48:18 -07001846/* The close function calls close_helper.
1847 */
1848__LJMP static int hlua_socket_close(lua_State *L)
1849{
1850 MAY_LJMP(check_args(L, 1, "close"));
1851 return hlua_socket_close_helper(L);
1852}
1853
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001854/* This Lua function assumes that the stack contain three parameters.
1855 * 1 - USERDATA containing a struct socket
1856 * 2 - INTEGER with values of the macro defined below
1857 * If the integer is -1, we must read at most one line.
1858 * If the integer is -2, we ust read all the data until the
1859 * end of the stream.
1860 * If the integer is positive value, we must read a number of
1861 * bytes corresponding to this value.
1862 */
1863#define HLSR_READ_LINE (-1)
1864#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001865__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001866{
1867 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1868 int wanted = lua_tointeger(L, 2);
1869 struct hlua *hlua = hlua_gethlua(L);
1870 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001871 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001872 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02001873 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001874 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02001875 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001876 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001877 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001878 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001879 struct stream_interface *si;
1880 struct stream *s;
1881 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001882 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001883
1884 /* Check if this lua stack is schedulable. */
1885 if (!hlua || !hlua->task)
1886 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1887 "'frontend', 'backend' or 'task'"));
1888
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001889 /* Check if we run on the same thread than the xreator thread.
1890 * We cannot access to the socket if the thread is different.
1891 */
1892 if (socket->tid != tid)
1893 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1894
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001895 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001896 peer = xref_get_peer_and_lock(&socket->xref);
1897 if (!peer)
1898 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001899 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1900 si = appctx->owner;
1901 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001902
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001903 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001904 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001905 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001906 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001907 if (nblk < 0) /* Connection close. */
1908 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001909 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001910 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001911
1912 /* remove final \r\n. */
1913 if (nblk == 1) {
1914 if (blk1[len1-1] == '\n') {
1915 len1--;
1916 skip_at_end++;
1917 if (blk1[len1-1] == '\r') {
1918 len1--;
1919 skip_at_end++;
1920 }
1921 }
1922 }
1923 else {
1924 if (blk2[len2-1] == '\n') {
1925 len2--;
1926 skip_at_end++;
1927 if (blk2[len2-1] == '\r') {
1928 len2--;
1929 skip_at_end++;
1930 }
1931 }
1932 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001933 }
1934
1935 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001936 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001937 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001938 if (nblk < 0) /* Connection close. */
1939 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001940 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001941 goto connection_empty;
1942 }
1943
1944 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001945 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001946 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001947 if (nblk < 0) /* Connection close. */
1948 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001949 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001950 goto connection_empty;
1951
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001952 missing_bytes = wanted - socket->b.n;
1953 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001954 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001955 len1 = missing_bytes;
1956 } if (nblk == 2 && len1 + len2 > missing_bytes)
1957 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001958 }
1959
1960 len = len1;
1961
1962 luaL_addlstring(&socket->b, blk1, len1);
1963 if (nblk == 2) {
1964 len += len2;
1965 luaL_addlstring(&socket->b, blk2, len2);
1966 }
1967
1968 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001969 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001970
1971 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02001972 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001973
1974 /* If the pattern reclaim to read all the data
1975 * in the connection, got out.
1976 */
1977 if (wanted == HLSR_READ_ALL)
1978 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001979 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001980 goto connection_empty;
1981
1982 /* Return result. */
1983 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001984 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001985 return 1;
1986
1987connection_closed:
1988
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001989 xref_unlock(&socket->xref, peer);
1990
1991no_peer:
1992
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001993 /* If the buffer containds data. */
1994 if (socket->b.n > 0) {
1995 luaL_pushresult(&socket->b);
1996 return 1;
1997 }
1998 lua_pushnil(L);
1999 lua_pushstring(L, "connection closed.");
2000 return 2;
2001
2002connection_empty:
2003
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002004 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
2005 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002006 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002007 }
2008 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002009 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002010 return 0;
2011}
2012
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002013/* This Lua function gets two parameters. The first one can be string
2014 * or a number. If the string is "*l", the user requires one line. If
2015 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002016 * If the value is a number, the user require a number of bytes equal
2017 * to the value. The default value is "*l" (a line).
2018 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002019 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002020 * integer takes this values:
2021 * -1 : read a line
2022 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002023 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002024 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002025 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002026 * concatenated with the read data.
2027 */
2028__LJMP static int hlua_socket_receive(struct lua_State *L)
2029{
2030 int wanted = HLSR_READ_LINE;
2031 const char *pattern;
2032 int type;
2033 char *error;
2034 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002035 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002036
2037 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2038 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2039
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002040 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002041
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002042 /* Check if we run on the same thread than the xreator thread.
2043 * We cannot access to the socket if the thread is different.
2044 */
2045 if (socket->tid != tid)
2046 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2047
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002048 /* check for pattern. */
2049 if (lua_gettop(L) >= 2) {
2050 type = lua_type(L, 2);
2051 if (type == LUA_TSTRING) {
2052 pattern = lua_tostring(L, 2);
2053 if (strcmp(pattern, "*a") == 0)
2054 wanted = HLSR_READ_ALL;
2055 else if (strcmp(pattern, "*l") == 0)
2056 wanted = HLSR_READ_LINE;
2057 else {
2058 wanted = strtoll(pattern, &error, 10);
2059 if (*error != '\0')
2060 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2061 }
2062 }
2063 else if (type == LUA_TNUMBER) {
2064 wanted = lua_tointeger(L, 2);
2065 if (wanted < 0)
2066 WILL_LJMP(luaL_error(L, "Unsupported size."));
2067 }
2068 }
2069
2070 /* Set pattern. */
2071 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002072
2073 /* Check if we would replace the top by itself. */
2074 if (lua_gettop(L) != 2)
2075 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002076
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002077 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002078 luaL_buffinit(L, &socket->b);
2079
2080 /* Check prefix. */
2081 if (lua_gettop(L) >= 3) {
2082 if (lua_type(L, 3) != LUA_TSTRING)
2083 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2084 pattern = lua_tolstring(L, 3, &len);
2085 luaL_addlstring(&socket->b, pattern, len);
2086 }
2087
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002088 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002089}
2090
2091/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002092 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002093 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002094static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002095{
2096 struct hlua_socket *socket;
2097 struct hlua *hlua = hlua_gethlua(L);
2098 struct appctx *appctx;
2099 size_t buf_len;
2100 const char *buf;
2101 int len;
2102 int send_len;
2103 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002104 struct xref *peer;
2105 struct stream_interface *si;
2106 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002107
2108 /* Check if this lua stack is schedulable. */
2109 if (!hlua || !hlua->task)
2110 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2111 "'frontend', 'backend' or 'task'"));
2112
2113 /* Get object */
2114 socket = MAY_LJMP(hlua_checksocket(L, 1));
2115 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002116 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002117
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002118 /* Check if we run on the same thread than the xreator thread.
2119 * We cannot access to the socket if the thread is different.
2120 */
2121 if (socket->tid != tid)
2122 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2123
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002124 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002125 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002126 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002127 lua_pushinteger(L, -1);
2128 return 1;
2129 }
2130 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2131 si = appctx->owner;
2132 s = si_strm(si);
2133
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002134 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002135 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002136 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002137 lua_pushinteger(L, -1);
2138 return 1;
2139 }
2140
2141 /* Update the input buffer data. */
2142 buf += sent;
2143 send_len = buf_len - sent;
2144
2145 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002146 if (sent >= buf_len) {
2147 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002148 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002149 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002150
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002151 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002152 * the request buffer if its not required.
2153 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002154 if (s->req.buf.size == 0) {
Willy Tarreau581abd32018-10-25 10:21:41 +02002155 if (!si_alloc_ibuf(si, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002156 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002157 }
2158
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002159 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002160 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002161 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002162 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002163 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002164
2165 /* send data */
2166 if (len < send_len)
2167 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002168 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002169
2170 /* "Not enough space" (-1), "Buffer too little to contain
2171 * the data" (-2) are not expected because the available length
2172 * is tested.
2173 * Other unknown error are also not expected.
2174 */
2175 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002176 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002177 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002178
sada05ed3302018-05-11 11:48:18 -07002179 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002180 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002181 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002182 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002183 return 1;
2184 }
2185
2186 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002187 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002188
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002189 s->req.rex = TICK_ETERNITY;
2190 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002191
2192 /* Update length sent. */
2193 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002194 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002195
2196 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002197 if (sent + len >= buf_len) {
2198 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002199 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002200 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002201
2202hlua_socket_write_yield_return:
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002203 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2204 xref_unlock(&socket->xref, peer);
2205 WILL_LJMP(luaL_error(L, "out of memory"));
2206 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002207 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002208 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002209 return 0;
2210}
2211
2212/* This function initiate the send of data. It just check the input
2213 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002214 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002215 * "hlua_socket_write_yield" that can yield.
2216 *
2217 * The Lua function gets between 3 and 4 parameters. The first one is
2218 * the associated object. The second is a string buffer. The third is
2219 * a facultative integer that represents where is the buffer position
2220 * of the start of the data that can send. The first byte is the
2221 * position "1". The default value is "1". The fourth argument is a
2222 * facultative integer that represents where is the buffer position
2223 * of the end of the data that can send. The default is the last byte.
2224 */
2225static int hlua_socket_send(struct lua_State *L)
2226{
2227 int i;
2228 int j;
2229 const char *buf;
2230 size_t buf_len;
2231
2232 /* Check number of arguments. */
2233 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2234 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2235
2236 /* Get the string. */
2237 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2238
2239 /* Get and check j. */
2240 if (lua_gettop(L) == 4) {
2241 j = MAY_LJMP(luaL_checkinteger(L, 4));
2242 if (j < 0)
2243 j = buf_len + j + 1;
2244 if (j > buf_len)
2245 j = buf_len + 1;
2246 lua_pop(L, 1);
2247 }
2248 else
2249 j = buf_len;
2250
2251 /* Get and check i. */
2252 if (lua_gettop(L) == 3) {
2253 i = MAY_LJMP(luaL_checkinteger(L, 3));
2254 if (i < 0)
2255 i = buf_len + i + 1;
2256 if (i > buf_len)
2257 i = buf_len + 1;
2258 lua_pop(L, 1);
2259 } else
2260 i = 1;
2261
2262 /* Check bth i and j. */
2263 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002264 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002265 return 1;
2266 }
2267 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002268 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002269 return 1;
2270 }
2271 if (i == 0)
2272 i = 1;
2273 if (j == 0)
2274 j = 1;
2275
2276 /* Pop the string. */
2277 lua_pop(L, 1);
2278
2279 /* Update the buffer length. */
2280 buf += i - 1;
2281 buf_len = j - i + 1;
2282 lua_pushlstring(L, buf, buf_len);
2283
2284 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002285 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002286
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002287 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002288}
2289
Willy Tarreau22b0a682015-06-17 19:43:49 +02002290#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002291__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2292{
2293 static char buffer[SOCKET_INFO_MAX_LEN];
2294 int ret;
2295 int len;
2296 char *p;
2297
2298 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2299 if (ret <= 0) {
2300 lua_pushnil(L);
2301 return 1;
2302 }
2303
2304 if (ret == AF_UNIX) {
2305 lua_pushstring(L, buffer+1);
2306 return 1;
2307 }
2308 else if (ret == AF_INET6) {
2309 buffer[0] = '[';
2310 len = strlen(buffer);
2311 buffer[len] = ']';
2312 len++;
2313 buffer[len] = ':';
2314 len++;
2315 p = buffer;
2316 }
2317 else if (ret == AF_INET) {
2318 p = buffer + 1;
2319 len = strlen(p);
2320 p[len] = ':';
2321 len++;
2322 }
2323 else {
2324 lua_pushnil(L);
2325 return 1;
2326 }
2327
2328 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2329 lua_pushnil(L);
2330 return 1;
2331 }
2332
2333 lua_pushstring(L, p);
2334 return 1;
2335}
2336
2337/* Returns information about the peer of the connection. */
2338__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2339{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002340 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002341 struct xref *peer;
2342 struct appctx *appctx;
2343 struct stream_interface *si;
2344 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002345 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002346
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002347 MAY_LJMP(check_args(L, 1, "getpeername"));
2348
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002349 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002350
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002351 /* Check if we run on the same thread than the xreator thread.
2352 * We cannot access to the socket if the thread is different.
2353 */
2354 if (socket->tid != tid)
2355 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2356
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002357 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002358 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002359 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002360 lua_pushnil(L);
2361 return 1;
2362 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002363 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2364 si = appctx->owner;
2365 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002366
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002367 if (!s->target_addr) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002368 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002369 lua_pushnil(L);
2370 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002371 }
2372
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002373 ret = MAY_LJMP(hlua_socket_info(L, s->target_addr));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002374 xref_unlock(&socket->xref, peer);
2375 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002376}
2377
2378/* Returns information about my connection side. */
2379static int hlua_socket_getsockname(struct lua_State *L)
2380{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002381 struct hlua_socket *socket;
2382 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002383 struct appctx *appctx;
2384 struct xref *peer;
2385 struct stream_interface *si;
2386 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002387 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002388
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002389 MAY_LJMP(check_args(L, 1, "getsockname"));
2390
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002391 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002392
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002393 /* Check if we run on the same thread than the xreator thread.
2394 * We cannot access to the socket if the thread is different.
2395 */
2396 if (socket->tid != tid)
2397 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2398
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002399 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002400 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002401 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002402 lua_pushnil(L);
2403 return 1;
2404 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002405 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2406 si = appctx->owner;
2407 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002408
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002409 conn = cs_conn(objt_cs(s->si[1].end));
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002410 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002411 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002412 lua_pushnil(L);
2413 return 1;
2414 }
2415
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002416 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002417 xref_unlock(&socket->xref, peer);
2418 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002419}
2420
2421/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002422static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002423 .obj_type = OBJ_TYPE_APPLET,
2424 .name = "<LUA_TCP>",
2425 .fct = hlua_socket_handler,
2426 .release = hlua_socket_release,
2427};
2428
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002429__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002430{
2431 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2432 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002433 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002434 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002435 struct stream_interface *si;
2436 struct stream *s;
2437
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002438 /* Check if we run on the same thread than the xreator thread.
2439 * We cannot access to the socket if the thread is different.
2440 */
2441 if (socket->tid != tid)
2442 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2443
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002444 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002445 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002446 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002447 lua_pushnil(L);
2448 lua_pushstring(L, "Can't connect");
2449 return 2;
2450 }
2451 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2452 si = appctx->owner;
2453 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002454
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002455 /* Check if we run on the same thread than the xreator thread.
2456 * We cannot access to the socket if the thread is different.
2457 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002458 if (socket->tid != tid) {
2459 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002460 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002461 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002462
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002463 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002464 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002465 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002466 lua_pushnil(L);
2467 lua_pushstring(L, "Can't connect");
2468 return 2;
2469 }
2470
Willy Tarreaue09101e2018-10-16 17:37:12 +02002471 appctx = __objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002472
2473 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002474 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002475 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002476 lua_pushinteger(L, 1);
2477 return 1;
2478 }
2479
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002480 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2481 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002482 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002483 }
2484 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002485 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002486 return 0;
2487}
2488
2489/* This function fail or initite the connection. */
2490__LJMP static int hlua_socket_connect(struct lua_State *L)
2491{
2492 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002493 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002494 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002495 struct hlua *hlua;
2496 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002497 int low, high;
2498 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002499 struct xref *peer;
2500 struct stream_interface *si;
2501 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002502
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002503 if (lua_gettop(L) < 2)
2504 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002505
2506 /* Get args. */
2507 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002508
2509 /* Check if we run on the same thread than the xreator thread.
2510 * We cannot access to the socket if the thread is different.
2511 */
2512 if (socket->tid != tid)
2513 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2514
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002515 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002516 if (lua_gettop(L) >= 3) {
2517 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002518 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002519
Tim Duesterhus6edab862018-01-06 19:04:45 +01002520 /* Force the ip to end with a colon, to support IPv6 addresses
2521 * that are not enclosed within square brackets.
2522 */
2523 if (port > 0) {
2524 luaL_buffinit(L, &b);
2525 luaL_addstring(&b, ip);
2526 luaL_addchar(&b, ':');
2527 luaL_pushresult(&b);
2528 ip = lua_tolstring(L, lua_gettop(L), NULL);
2529 }
2530 }
2531
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002532 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002533 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002534 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002535 lua_pushnil(L);
2536 return 1;
2537 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002538
2539 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002540 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, NULL, NULL, PA_O_PORT_OK | PA_O_STREAM);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002541 if (!addr) {
2542 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002543 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002544 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002545
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002546 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002547 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002548 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002549 if (port == -1) {
2550 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002551 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002552 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002553 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2554 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002555 if (port == -1) {
2556 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002557 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002558 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002559 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002560 }
2561 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002562
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002563 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2564 si = appctx->owner;
2565 s = si_strm(si);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002566
2567 if (!sockaddr_alloc(&s->target_addr)) {
2568 xref_unlock(&socket->xref, peer);
2569 WILL_LJMP(luaL_error(L, "connect: internal error"));
2570 }
2571 *s->target_addr = *addr;
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002572 s->flags |= SF_ADDR_SET;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002573
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002574 hlua = hlua_gethlua(L);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002575
2576 /* inform the stream that we want to be notified whenever the
2577 * connection completes.
2578 */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01002579 si_cant_get(&s->si[0]);
Willy Tarreau3367d412018-11-15 10:57:41 +01002580 si_rx_endp_more(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002581 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002582
Willy Tarreauf31af932020-01-14 09:59:38 +01002583 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002584
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002585 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2586 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002587 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002588 }
2589 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002590
2591 task_wakeup(s->task, TASK_WOKEN_INIT);
2592 /* Return yield waiting for connection. */
2593
Willy Tarreau9635e032018-10-16 17:52:55 +02002594 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002595
2596 return 0;
2597}
2598
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002599#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002600__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2601{
2602 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002603 struct xref *peer;
2604 struct appctx *appctx;
2605 struct stream_interface *si;
2606 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002607
2608 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2609 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002610
2611 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002612 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002613 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002614 lua_pushnil(L);
2615 return 1;
2616 }
2617 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2618 si = appctx->owner;
2619 s = si_strm(si);
2620
2621 s->target = &socket_ssl.obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002622 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002623 return MAY_LJMP(hlua_socket_connect(L));
2624}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002625#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002626
2627__LJMP static int hlua_socket_setoption(struct lua_State *L)
2628{
2629 return 0;
2630}
2631
2632__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2633{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002634 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002635 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002636 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002637 struct xref *peer;
2638 struct appctx *appctx;
2639 struct stream_interface *si;
2640 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002641
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002642 MAY_LJMP(check_args(L, 2, "settimeout"));
2643
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002644 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002645
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002646 /* convert the timeout to millis */
2647 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002648
Thierry Fournier17a921b2018-03-08 09:59:02 +01002649 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002650 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002651 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2652
Mark Lakes56cc1252018-03-27 09:48:06 +02002653 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002654 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002655
2656 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002657 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002658 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002659
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002660 /* Check if we run on the same thread than the xreator thread.
2661 * We cannot access to the socket if the thread is different.
2662 */
2663 if (socket->tid != tid)
2664 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2665
Mark Lakes56cc1252018-03-27 09:48:06 +02002666 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002667 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002668 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002669 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2670 WILL_LJMP(lua_error(L));
2671 return 0;
2672 }
2673 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2674 si = appctx->owner;
2675 s = si_strm(si);
2676
Cyril Bonté7bb63452018-08-17 23:51:02 +02002677 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002678 s->req.rto = tmout;
2679 s->req.wto = tmout;
2680 s->res.rto = tmout;
2681 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002682 s->req.rex = tick_add_ifset(now_ms, tmout);
2683 s->req.wex = tick_add_ifset(now_ms, tmout);
2684 s->res.rex = tick_add_ifset(now_ms, tmout);
2685 s->res.wex = tick_add_ifset(now_ms, tmout);
2686
2687 s->task->expire = tick_add_ifset(now_ms, tmout);
2688 task_queue(s->task);
2689
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002690 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002691
Thierry Fourniere9636f12018-03-08 09:54:32 +01002692 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002693 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002694}
2695
2696__LJMP static int hlua_socket_new(lua_State *L)
2697{
2698 struct hlua_socket *socket;
2699 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002700 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002701 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002702
2703 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002704 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002705 hlua_pusherror(L, "socket: full stack");
2706 goto out_fail_conf;
2707 }
2708
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002709 /* Create the object: obj[0] = userdata. */
2710 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002711 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002712 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002713 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002714 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002715
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002716 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002717 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002718 hlua_pusherror(L, "socket: uninitialized pools.");
2719 goto out_fail_conf;
2720 }
2721
Willy Tarreau87b09662015-04-03 00:22:06 +02002722 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002723 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2724 lua_setmetatable(L, -2);
2725
Willy Tarreaud420a972015-04-06 00:39:18 +02002726 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002727 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002728 if (!appctx) {
2729 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002730 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002731 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002732
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002733 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002734 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002735 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2736 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002737
Willy Tarreaud420a972015-04-06 00:39:18 +02002738 /* Now create a session, task and stream for this applet */
2739 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2740 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002741 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002742 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002743 }
2744
Willy Tarreau87787ac2017-08-28 16:22:54 +02002745 strm = stream_new(sess, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002746 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002747 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002748 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002749 }
2750
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002751 /* Initialise cross reference between stream and Lua socket object. */
2752 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002753
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002754 /* Configure "right" stream interface. this "si" is used to connect
2755 * and retrieve data from the server. The connection is initialized
2756 * with the "struct server".
2757 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002758 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002759
2760 /* Force destination server. */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002761 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002762 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002763
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002764 return 1;
2765
Willy Tarreaud420a972015-04-06 00:39:18 +02002766 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002767 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002768 out_fail_sess:
2769 appctx_free(appctx);
2770 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002771 WILL_LJMP(lua_error(L));
2772 return 0;
2773}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002774
2775/*
2776 *
2777 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002778 * Class Channel
2779 *
2780 *
2781 */
2782
2783/* Returns the struct hlua_channel join to the class channel in the
2784 * stack entry "ud" or throws an argument error.
2785 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002786__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002787{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002788 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002789}
2790
Willy Tarreau47860ed2015-03-10 14:07:50 +01002791/* Pushes the channel onto the top of the stack. If the stask does not have a
2792 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002793 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002794static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002795{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002796 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002797 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002798 return 0;
2799
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002800 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002801 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002802 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002803
2804 /* Pop a class sesison metatable and affect it to the userdata. */
2805 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2806 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002807 return 1;
2808}
2809
2810/* Duplicate all the data present in the input channel and put it
2811 * in a string LUA variables. Returns -1 and push a nil value in
2812 * the stack if the channel is closed and all the data are consumed,
2813 * returns 0 if no data are available, otherwise it returns the length
Ilya Shipitsind4259502020-04-08 01:07:56 +05002814 * of the built string.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002815 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002816static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002817{
2818 char *blk1;
2819 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002820 size_t len1;
2821 size_t len2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002822 int ret;
2823 luaL_Buffer b;
2824
Willy Tarreau06d80a92017-10-19 14:32:15 +02002825 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002826 if (unlikely(ret == 0))
2827 return 0;
2828
2829 if (unlikely(ret < 0)) {
2830 lua_pushnil(L);
2831 return -1;
2832 }
2833
2834 luaL_buffinit(L, &b);
2835 luaL_addlstring(&b, blk1, len1);
2836 if (unlikely(ret == 2))
2837 luaL_addlstring(&b, blk2, len2);
2838 luaL_pushresult(&b);
2839
2840 if (unlikely(ret == 2))
2841 return len1 + len2;
2842 return len1;
2843}
2844
2845/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2846 * a yield. This function keep the data in the buffer.
2847 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002848__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002849{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002850 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002851
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002852 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2853
Thierry Fournier77016da2020-08-15 14:35:51 +02002854 if (chn_strm(chn)->be->mode == PR_MODE_HTTP) {
2855 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01002856 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02002857 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01002858
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002859 if (_hlua_channel_dup(chn, L) == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002860 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002861 return 1;
2862}
2863
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002864/* Check arguments for the function "hlua_channel_dup_yield". */
2865__LJMP static int hlua_channel_dup(lua_State *L)
2866{
2867 MAY_LJMP(check_args(L, 1, "dup"));
2868 MAY_LJMP(hlua_checkchannel(L, 1));
2869 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2870}
2871
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002872/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2873 * a yield. This function consumes the data in the buffer. It returns
2874 * a string containing the data or a nil pointer if no data are available
2875 * and the channel is closed.
2876 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002877__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002878{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002879 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002880 int ret;
2881
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002882 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002883
Thierry Fournier77016da2020-08-15 14:35:51 +02002884 if (chn_strm(chn)->be->mode == PR_MODE_HTTP) {
2885 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01002886 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02002887 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01002888
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002889 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002890 if (unlikely(ret == 0))
Willy Tarreau9635e032018-10-16 17:52:55 +02002891 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002892
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002893 if (unlikely(ret == -1))
2894 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002895
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002896 b_sub(&chn->buf, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002897 return 1;
2898}
2899
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002900/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002901__LJMP static int hlua_channel_get(lua_State *L)
2902{
2903 MAY_LJMP(check_args(L, 1, "get"));
2904 MAY_LJMP(hlua_checkchannel(L, 1));
2905 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2906}
2907
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002908/* This functions consumes and returns one line. If the channel is closed,
2909 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002910 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002911 * value.
2912 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002913__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002914{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002915 char *blk1;
2916 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002917 size_t len1;
2918 size_t len2;
2919 size_t len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002920 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002921 int ret;
2922 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002923
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002924 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2925
Thierry Fournier77016da2020-08-15 14:35:51 +02002926 if (chn_strm(chn)->be->mode == PR_MODE_HTTP) {
2927 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01002928 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02002929 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01002930
Willy Tarreau06d80a92017-10-19 14:32:15 +02002931 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002932 if (ret == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002933 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002934
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002935 if (ret == -1) {
2936 lua_pushnil(L);
2937 return 1;
2938 }
2939
2940 luaL_buffinit(L, &b);
2941 luaL_addlstring(&b, blk1, len1);
2942 len = len1;
2943 if (unlikely(ret == 2)) {
2944 luaL_addlstring(&b, blk2, len2);
2945 len += len2;
2946 }
2947 luaL_pushresult(&b);
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002948 b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn) + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002949 return 1;
2950}
2951
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002952/* Check arguments for the function "hlua_channel_getline_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002953__LJMP static int hlua_channel_getline(lua_State *L)
2954{
2955 MAY_LJMP(check_args(L, 1, "getline"));
2956 MAY_LJMP(hlua_checkchannel(L, 1));
2957 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2958}
2959
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002960/* This function takes a string as input, and append it at the
2961 * input side of channel. If the data is too big, but a space
2962 * is probably available after sending some data, the function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002963 * yields. If the data is bigger than the buffer, or if the
2964 * channel is closed, it returns -1. Otherwise, it returns the
2965 * amount of data written.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002966 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002967__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002968{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002969 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002970 size_t len;
2971 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2972 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2973 int ret;
2974 int max;
2975
Thierry Fournier77016da2020-08-15 14:35:51 +02002976 if (chn_strm(chn)->be->mode == PR_MODE_HTTP) {
2977 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01002978 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02002979 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01002980
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002981 /* Check if the buffer is available because HAProxy doesn't allocate
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002982 * the request buffer if its not required.
2983 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002984 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01002985 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02002986 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002987 }
2988
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002989 max = channel_recv_limit(chn) - b_data(&chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002990 if (max > len - l)
2991 max = len - l;
2992
Willy Tarreau06d80a92017-10-19 14:32:15 +02002993 ret = ci_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002994 if (ret == -2 || ret == -3) {
2995 lua_pushinteger(L, -1);
2996 return 1;
2997 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002998 if (ret == -1) {
2999 chn->flags |= CF_WAKE_WRITE;
Willy Tarreau9635e032018-10-16 17:52:55 +02003000 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01003001 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003002 l += ret;
3003 lua_pop(L, 1);
3004 lua_pushinteger(L, l);
3005
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003006 max = channel_recv_limit(chn) - b_data(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02003007 if (max == 0 && co_data(chn) == 0) {
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003008 /* There are no space available, and the output buffer is empty.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003009 * in this case, we cannot add more data, so we cannot yield,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003010 * we return the amount of copied data.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003011 */
3012 return 1;
3013 }
3014 if (l < len)
Willy Tarreau9635e032018-10-16 17:52:55 +02003015 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003016 return 1;
3017}
3018
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003019/* Just a wrapper of "hlua_channel_append_yield". It returns the length
3020 * of the written string, or -1 if the channel is closed or if the
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003021 * buffer size is too little for the data.
3022 */
3023__LJMP static int hlua_channel_append(lua_State *L)
3024{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003025 size_t len;
3026
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003027 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003028 MAY_LJMP(hlua_checkchannel(L, 1));
3029 MAY_LJMP(luaL_checklstring(L, 2, &len));
3030 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003031 lua_pushinteger(L, 0);
3032
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003033 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003034}
3035
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003036/* Just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003037 * his process by cleaning the buffer. The result is a replacement
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003038 * of the current data. It returns the length of the written string,
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003039 * or -1 if the channel is closed or if the buffer size is too
3040 * little for the data.
3041 */
3042__LJMP static int hlua_channel_set(lua_State *L)
3043{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003044 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003045
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003046 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003047 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003048 lua_pushinteger(L, 0);
3049
Thierry Fournier77016da2020-08-15 14:35:51 +02003050 if (chn_strm(chn)->be->mode == PR_MODE_HTTP) {
3051 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003052 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003053 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003054
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003055 b_set_data(&chn->buf, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003056
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003057 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003058}
3059
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003060/* Append data in the output side of the buffer. This data is immediately
3061 * sent. The function returns the amount of data written. If the buffer
3062 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003063 * if the channel is closed.
3064 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003065__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003066{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003067 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003068 size_t len;
3069 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3070 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3071 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003072 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003073
Thierry Fournier77016da2020-08-15 14:35:51 +02003074 if (chn_strm(chn)->be->mode == PR_MODE_HTTP) {
3075 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003076 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003077 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003078
Willy Tarreau47860ed2015-03-10 14:07:50 +01003079 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003080 lua_pushinteger(L, -1);
3081 return 1;
3082 }
3083
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003084 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003085 * the request buffer if its not required.
3086 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003087 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01003088 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02003089 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003090 }
3091
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003092 /* The written data will be immediately sent, so we can check
3093 * the available space without taking in account the reserve.
3094 * The reserve is guaranteed for the processing of incoming
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003095 * data, because the buffer will be flushed.
3096 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003097 max = b_room(&chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003098
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003099 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003100 * in this case, we cannot add more data, so we cannot yield,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003101 * we return the amount of copied data.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003102 */
Willy Tarreaua79021a2018-06-15 18:07:57 +02003103 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003104 return 1;
3105
3106 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003107 if (max > len - l)
3108 max = len - l;
3109
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003110 /* The buffer available size may be not contiguous. This test
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003111 * detects a non contiguous buffer and realign it.
3112 */
Willy Tarreau3f679992018-06-15 15:06:42 +02003113 if (ci_space_for_replace(chn) < max)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003114 channel_slow_realign(chn, trash.area);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003115
3116 /* Copy input data in the buffer. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003117 max = b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn), str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003118
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003119 /* buffer replace considers that the input part is filled.
3120 * so, I must forward these new data in the output part.
3121 */
Willy Tarreaubcbd3932018-06-06 07:13:22 +02003122 c_adv(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003123
3124 l += max;
3125 lua_pop(L, 1);
3126 lua_pushinteger(L, l);
3127
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003128 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003129 * in this case, we cannot add more data, so we cannot yield,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003130 * we return the amount of copied data.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003131 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003132 max = b_room(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02003133 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003134 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003135
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003136 if (l < len) {
3137 /* If we are waiting for space in the response buffer, we
3138 * must set the flag WAKERESWR. This flag required the task
3139 * wake up if any activity is detected on the response buffer.
3140 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003141 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003142 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003143 else
3144 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003145 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003146 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003147
3148 return 1;
3149}
3150
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003151/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003152 * yield the LUA process, and resume it without checking the
3153 * input arguments.
3154 */
3155__LJMP static int hlua_channel_send(lua_State *L)
3156{
3157 MAY_LJMP(check_args(L, 2, "send"));
3158 lua_pushinteger(L, 0);
3159
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003160 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003161}
3162
3163/* This function forward and amount of butes. The data pass from
3164 * the input side of the buffer to the output side, and can be
3165 * forwarded. This function never fails.
3166 *
3167 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003168 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003169 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003170__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003171{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003172 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003173 int len;
3174 int l;
3175 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003176 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003177
3178 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003179
Thierry Fournier77016da2020-08-15 14:35:51 +02003180 if (chn_strm(chn)->be->mode == PR_MODE_HTTP) {
3181 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003182 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003183 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003184
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003185 len = MAY_LJMP(luaL_checkinteger(L, 2));
3186 l = MAY_LJMP(luaL_checkinteger(L, -1));
3187
3188 max = len - l;
Willy Tarreaua79021a2018-06-15 18:07:57 +02003189 if (max > ci_data(chn))
3190 max = ci_data(chn);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003191 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003192 l += max;
3193
3194 lua_pop(L, 1);
3195 lua_pushinteger(L, l);
3196
3197 /* Check if it miss bytes to forward. */
3198 if (l < len) {
3199 /* The the input channel or the output channel are closed, we
3200 * must return the amount of data forwarded.
3201 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003202 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003203 return 1;
3204
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003205 /* If we are waiting for space data in the response buffer, we
3206 * must set the flag WAKERESWR. This flag required the task
3207 * wake up if any activity is detected on the response buffer.
3208 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003209 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003210 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003211 else
3212 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003213
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003214 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003215 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003216 }
3217
3218 return 1;
3219}
3220
3221/* Just check the input and prepare the stack for the previous
3222 * function "hlua_channel_forward_yield"
3223 */
3224__LJMP static int hlua_channel_forward(lua_State *L)
3225{
3226 MAY_LJMP(check_args(L, 2, "forward"));
3227 MAY_LJMP(hlua_checkchannel(L, 1));
3228 MAY_LJMP(luaL_checkinteger(L, 2));
3229
3230 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003231 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003232}
3233
3234/* Just returns the number of bytes available in the input
3235 * side of the buffer. This function never fails.
3236 */
3237__LJMP static int hlua_channel_get_in_len(lua_State *L)
3238{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003239 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003240
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003241 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003242 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003243 if (IS_HTX_STRM(chn_strm(chn))) {
3244 struct htx *htx = htxbuf(&chn->buf);
3245 lua_pushinteger(L, htx->data - co_data(chn));
3246 }
3247 else
3248 lua_pushinteger(L, ci_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003249 return 1;
3250}
3251
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003252/* Returns true if the channel is full. */
3253__LJMP static int hlua_channel_is_full(lua_State *L)
3254{
3255 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003256
3257 MAY_LJMP(check_args(L, 1, "is_full"));
3258 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01003259 /* ignore the reserve, we are not on a producer side (ie in an
3260 * applet).
3261 */
3262 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003263 return 1;
3264}
3265
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01003266/* Returns true if the channel is the response channel. */
3267__LJMP static int hlua_channel_is_resp(lua_State *L)
3268{
3269 struct channel *chn;
3270
3271 MAY_LJMP(check_args(L, 1, "is_resp"));
3272 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3273
3274 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
3275 return 1;
3276}
3277
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003278/* Just returns the number of bytes available in the output
3279 * side of the buffer. This function never fails.
3280 */
3281__LJMP static int hlua_channel_get_out_len(lua_State *L)
3282{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003283 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003284
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003285 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003286 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreaua79021a2018-06-15 18:07:57 +02003287 lua_pushinteger(L, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003288 return 1;
3289}
3290
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003291/*
3292 *
3293 *
3294 * Class Fetches
3295 *
3296 *
3297 */
3298
3299/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003300 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003301 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003302__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003303{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003304 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003305}
3306
3307/* This function creates and push in the stack a fetch object according
3308 * with a current TXN.
3309 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003310static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003311{
Willy Tarreau7073c472015-04-06 11:15:40 +02003312 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003313
3314 /* Check stack size. */
3315 if (!lua_checkstack(L, 3))
3316 return 0;
3317
3318 /* Create the object: obj[0] = userdata.
3319 * Note that the base of the Fetches object is the
3320 * transaction object.
3321 */
3322 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003323 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003324 lua_rawseti(L, -2, 0);
3325
Willy Tarreau7073c472015-04-06 11:15:40 +02003326 hsmp->s = txn->s;
3327 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003328 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003329 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003330
3331 /* Pop a class sesison metatable and affect it to the userdata. */
3332 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3333 lua_setmetatable(L, -2);
3334
3335 return 1;
3336}
3337
3338/* This function is an LUA binding. It is called with each sample-fetch.
3339 * It uses closure argument to store the associated sample-fetch. It
3340 * returns only one argument or throws an error. An error is thrown
3341 * only if an error is encountered during the argument parsing. If
3342 * the "sample-fetch" function fails, nil is returned.
3343 */
3344__LJMP static int hlua_run_sample_fetch(lua_State *L)
3345{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003346 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003347 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003348 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003349 int i;
3350 struct sample smp;
3351
3352 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003353 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003354
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003355 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003356 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003357
Thierry FOURNIERca988662015-12-20 18:43:03 +01003358 /* Check execution authorization. */
3359 if (f->use & SMP_USE_HTTP_ANY &&
3360 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3361 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3362 "is not available in Lua services", f->kw);
3363 WILL_LJMP(lua_error(L));
3364 }
3365
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003366 /* Get extra arguments. */
3367 for (i = 0; i < lua_gettop(L) - 1; i++) {
3368 if (i >= ARGM_NBARGS)
3369 break;
3370 hlua_lua2arg(L, i + 2, &args[i]);
3371 }
3372 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003373 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003374
3375 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003376 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003377
3378 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003379 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003380 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003381 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003382 }
3383
3384 /* Initialise the sample. */
3385 memset(&smp, 0, sizeof(smp));
3386
3387 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003388 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003389 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003390 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003391 lua_pushstring(L, "");
3392 else
3393 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003394 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003395 }
3396
3397 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003398 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003399 hlua_smp2lua_str(L, &smp);
3400 else
3401 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003402
3403 end:
3404 for (i = 0; args[i].type != ARGT_STOP; i++) {
3405 if (args[i].type == ARGT_STR)
3406 chunk_destroy(&args[i].data.str);
Christopher Fauletfd2e9062020-08-06 11:10:57 +02003407 else if (args[i].type == ARGT_REG)
3408 regex_free(args[i].data.reg);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003409 }
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003410 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003411
3412 error:
3413 for (i = 0; args[i].type != ARGT_STOP; i++) {
3414 if (args[i].type == ARGT_STR)
3415 chunk_destroy(&args[i].data.str);
Christopher Fauletfd2e9062020-08-06 11:10:57 +02003416 else if (args[i].type == ARGT_REG)
3417 regex_free(args[i].data.reg);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003418 }
3419 WILL_LJMP(lua_error(L));
3420 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003421}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003422
3423/*
3424 *
3425 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003426 * Class Converters
3427 *
3428 *
3429 */
3430
3431/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003432 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003433 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003434__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003435{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003436 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003437}
3438
3439/* This function creates and push in the stack a Converters object
3440 * according with a current TXN.
3441 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003442static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003443{
Willy Tarreau7073c472015-04-06 11:15:40 +02003444 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003445
3446 /* Check stack size. */
3447 if (!lua_checkstack(L, 3))
3448 return 0;
3449
3450 /* Create the object: obj[0] = userdata.
3451 * Note that the base of the Converters object is the
3452 * same than the TXN object.
3453 */
3454 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003455 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003456 lua_rawseti(L, -2, 0);
3457
Willy Tarreau7073c472015-04-06 11:15:40 +02003458 hsmp->s = txn->s;
3459 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003460 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003461 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003462
Willy Tarreau87b09662015-04-03 00:22:06 +02003463 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003464 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3465 lua_setmetatable(L, -2);
3466
3467 return 1;
3468}
3469
3470/* This function is an LUA binding. It is called with each converter.
3471 * It uses closure argument to store the associated converter. It
3472 * returns only one argument or throws an error. An error is thrown
3473 * only if an error is encountered during the argument parsing. If
3474 * the converter function function fails, nil is returned.
3475 */
3476__LJMP static int hlua_run_sample_conv(lua_State *L)
3477{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003478 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003479 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003480 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003481 int i;
3482 struct sample smp;
3483
3484 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003485 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003486
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003487 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003488 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003489
3490 /* Get extra arguments. */
3491 for (i = 0; i < lua_gettop(L) - 2; i++) {
3492 if (i >= ARGM_NBARGS)
3493 break;
3494 hlua_lua2arg(L, i + 3, &args[i]);
3495 }
3496 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003497 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003498
3499 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003500 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003501
3502 /* Run the special args checker. */
3503 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3504 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003505 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003506 }
3507
3508 /* Initialise the sample. */
3509 if (!hlua_lua2smp(L, 2, &smp)) {
3510 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003511 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003512 }
3513
Willy Tarreau1777ea62016-03-10 16:15:46 +01003514 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3515
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003516 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003517 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003518 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003519 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003520 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003521 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003522 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3523 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003524 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003525 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003526 }
3527
3528 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003529 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003530 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003531 lua_pushstring(L, "");
3532 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003533 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003534 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003535 }
3536
3537 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003538 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003539 hlua_smp2lua_str(L, &smp);
3540 else
3541 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003542 end:
3543 for (i = 0; args[i].type != ARGT_STOP; i++) {
3544 if (args[i].type == ARGT_STR)
3545 chunk_destroy(&args[i].data.str);
Christopher Fauletfd2e9062020-08-06 11:10:57 +02003546 else if (args[i].type == ARGT_REG)
3547 regex_free(args[i].data.reg);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003548 }
Willy Tarreaua678b432015-08-28 10:14:59 +02003549 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003550
3551 error:
3552 for (i = 0; args[i].type != ARGT_STOP; i++) {
3553 if (args[i].type == ARGT_STR)
3554 chunk_destroy(&args[i].data.str);
Christopher Fauletfd2e9062020-08-06 11:10:57 +02003555 else if (args[i].type == ARGT_REG)
3556 regex_free(args[i].data.reg);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003557 }
3558 WILL_LJMP(lua_error(L));
3559 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003560}
3561
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003562/*
3563 *
3564 *
3565 * Class AppletTCP
3566 *
3567 *
3568 */
3569
3570/* Returns a struct hlua_txn if the stack entry "ud" is
3571 * a class stream, otherwise it throws an error.
3572 */
3573__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3574{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003575 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003576}
3577
3578/* This function creates and push in the stack an Applet object
3579 * according with a current TXN.
3580 */
3581static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3582{
3583 struct hlua_appctx *appctx;
3584 struct stream_interface *si = ctx->owner;
3585 struct stream *s = si_strm(si);
3586 struct proxy *p = s->be;
3587
3588 /* Check stack size. */
3589 if (!lua_checkstack(L, 3))
3590 return 0;
3591
3592 /* Create the object: obj[0] = userdata.
3593 * Note that the base of the Converters object is the
3594 * same than the TXN object.
3595 */
3596 lua_newtable(L);
3597 appctx = lua_newuserdata(L, sizeof(*appctx));
3598 lua_rawseti(L, -2, 0);
3599 appctx->appctx = ctx;
3600 appctx->htxn.s = s;
3601 appctx->htxn.p = p;
3602
3603 /* Create the "f" field that contains a list of fetches. */
3604 lua_pushstring(L, "f");
3605 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3606 return 0;
3607 lua_settable(L, -3);
3608
3609 /* Create the "sf" field that contains a list of stringsafe fetches. */
3610 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003611 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003612 return 0;
3613 lua_settable(L, -3);
3614
3615 /* Create the "c" field that contains a list of converters. */
3616 lua_pushstring(L, "c");
3617 if (!hlua_converters_new(L, &appctx->htxn, 0))
3618 return 0;
3619 lua_settable(L, -3);
3620
3621 /* Create the "sc" field that contains a list of stringsafe converters. */
3622 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003623 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003624 return 0;
3625 lua_settable(L, -3);
3626
3627 /* Pop a class stream metatable and affect it to the table. */
3628 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3629 lua_setmetatable(L, -2);
3630
3631 return 1;
3632}
3633
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003634__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3635{
3636 struct hlua_appctx *appctx;
3637 struct stream *s;
3638 const char *name;
3639 size_t len;
3640 struct sample smp;
3641
Tim Duesterhus4e172c92020-05-19 13:49:42 +02003642 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
3643 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003644
3645 /* It is useles to retrieve the stream, but this function
3646 * runs only in a stream context.
3647 */
3648 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3649 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3650 s = appctx->htxn.s;
3651
3652 /* Converts the third argument in a sample. */
3653 hlua_lua2smp(L, 3, &smp);
3654
3655 /* Store the sample in a variable. */
3656 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02003657
3658 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
3659 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
3660 else
3661 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
3662
Tim Duesterhus84ebc132020-05-19 13:49:41 +02003663 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003664}
3665
3666__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3667{
3668 struct hlua_appctx *appctx;
3669 struct stream *s;
3670 const char *name;
3671 size_t len;
3672 struct sample smp;
3673
3674 MAY_LJMP(check_args(L, 2, "unset_var"));
3675
3676 /* It is useles to retrieve the stream, but this function
3677 * runs only in a stream context.
3678 */
3679 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3680 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3681 s = appctx->htxn.s;
3682
3683 /* Unset the variable. */
3684 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02003685 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
3686 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003687}
3688
3689__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3690{
3691 struct hlua_appctx *appctx;
3692 struct stream *s;
3693 const char *name;
3694 size_t len;
3695 struct sample smp;
3696
3697 MAY_LJMP(check_args(L, 2, "get_var"));
3698
3699 /* It is useles to retrieve the stream, but this function
3700 * runs only in a stream context.
3701 */
3702 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3703 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3704 s = appctx->htxn.s;
3705
3706 smp_set_owner(&smp, s->be, s->sess, s, 0);
3707 if (!vars_get_by_name(name, len, &smp)) {
3708 lua_pushnil(L);
3709 return 1;
3710 }
3711
3712 return hlua_smp2lua(L, &smp);
3713}
3714
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003715__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3716{
3717 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3718 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003719 struct hlua *hlua;
3720
3721 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003722 if (!s->hlua)
3723 return 0;
3724 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003725
3726 MAY_LJMP(check_args(L, 2, "set_priv"));
3727
3728 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003729 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003730
3731 /* Get and store new value. */
3732 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3733 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3734
3735 return 0;
3736}
3737
3738__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3739{
3740 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3741 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003742 struct hlua *hlua;
3743
3744 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003745 if (!s->hlua) {
3746 lua_pushnil(L);
3747 return 1;
3748 }
3749 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003750
3751 /* Push configuration index in the stack. */
3752 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3753
3754 return 1;
3755}
3756
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003757/* If expected data not yet available, it returns a yield. This function
3758 * consumes the data in the buffer. It returns a string containing the
3759 * data. This string can be empty.
3760 */
3761__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3762{
3763 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3764 struct stream_interface *si = appctx->appctx->owner;
3765 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003766 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003767 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003768 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003769 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003770
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003771 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003772 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003773
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003774 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003775 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003776 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003777 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003778 }
3779
3780 /* End of data: commit the total strings and return. */
3781 if (ret < 0) {
3782 luaL_pushresult(&appctx->b);
3783 return 1;
3784 }
3785
3786 /* Ensure that the block 2 length is usable. */
3787 if (ret == 1)
3788 len2 = 0;
3789
3790 /* dont check the max length read and dont check. */
3791 luaL_addlstring(&appctx->b, blk1, len1);
3792 luaL_addlstring(&appctx->b, blk2, len2);
3793
3794 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003795 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003796 luaL_pushresult(&appctx->b);
3797 return 1;
3798}
3799
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003800/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003801__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3802{
3803 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3804
3805 /* Initialise the string catenation. */
3806 luaL_buffinit(L, &appctx->b);
3807
3808 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3809}
3810
3811/* If expected data not yet available, it returns a yield. This function
3812 * consumes the data in the buffer. It returns a string containing the
3813 * data. This string can be empty.
3814 */
3815__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3816{
3817 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3818 struct stream_interface *si = appctx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003819 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003820 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003821 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003822 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003823 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003824 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003825
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003826 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003827 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003828
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003829 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003830 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003831 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003832 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003833 }
3834
3835 /* End of data: commit the total strings and return. */
3836 if (ret < 0) {
3837 luaL_pushresult(&appctx->b);
3838 return 1;
3839 }
3840
3841 /* Ensure that the block 2 length is usable. */
3842 if (ret == 1)
3843 len2 = 0;
3844
3845 if (len == -1) {
3846
3847 /* If len == -1, catenate all the data avalaile and
3848 * yield because we want to get all the data until
3849 * the end of data stream.
3850 */
3851 luaL_addlstring(&appctx->b, blk1, len1);
3852 luaL_addlstring(&appctx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02003853 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003854 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003855 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003856
3857 } else {
3858
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003859 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003860 if (len1 > len)
3861 len1 = len;
3862 luaL_addlstring(&appctx->b, blk1, len1);
3863 len -= len1;
3864
3865 /* Copy the second block. */
3866 if (len2 > len)
3867 len2 = len;
3868 luaL_addlstring(&appctx->b, blk2, len2);
3869 len -= len2;
3870
3871 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003872 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003873
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003874 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003875 if (len > 0) {
3876 lua_pushinteger(L, len);
3877 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003878 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003879 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003880 }
3881
3882 /* return the result. */
3883 luaL_pushresult(&appctx->b);
3884 return 1;
3885 }
3886
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003887 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003888 hlua_pusherror(L, "Lua: internal error");
3889 WILL_LJMP(lua_error(L));
3890 return 0;
3891}
3892
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003893/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003894__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3895{
3896 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3897 int len = -1;
3898
3899 if (lua_gettop(L) > 2)
3900 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3901 if (lua_gettop(L) >= 2) {
3902 len = MAY_LJMP(luaL_checkinteger(L, 2));
3903 lua_pop(L, 1);
3904 }
3905
3906 /* Confirm or set the required length */
3907 lua_pushinteger(L, len);
3908
3909 /* Initialise the string catenation. */
3910 luaL_buffinit(L, &appctx->b);
3911
3912 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3913}
3914
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003915/* Append data in the output side of the buffer. This data is immediately
3916 * sent. The function returns the amount of data written. If the buffer
3917 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003918 * if the channel is closed.
3919 */
3920__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3921{
3922 size_t len;
3923 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3924 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3925 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3926 struct stream_interface *si = appctx->appctx->owner;
3927 struct channel *chn = si_ic(si);
3928 int max;
3929
3930 /* Get the max amount of data which can write as input in the channel. */
3931 max = channel_recv_max(chn);
3932 if (max > (len - l))
3933 max = len - l;
3934
3935 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003936 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003937
3938 /* update counters. */
3939 l += max;
3940 lua_pop(L, 1);
3941 lua_pushinteger(L, l);
3942
3943 /* If some data is not send, declares the situation to the
3944 * applet, and returns a yield.
3945 */
3946 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01003947 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003948 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003949 }
3950
3951 return 1;
3952}
3953
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003954/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003955 * yield the LUA process, and resume it without checking the
3956 * input arguments.
3957 */
3958__LJMP static int hlua_applet_tcp_send(lua_State *L)
3959{
3960 MAY_LJMP(check_args(L, 2, "send"));
3961 lua_pushinteger(L, 0);
3962
3963 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3964}
3965
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003966/*
3967 *
3968 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003969 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003970 *
3971 *
3972 */
3973
3974/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003975 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003976 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003977__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003978{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003979 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003980}
3981
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003982/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003983 * according with a current TXN.
3984 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003985static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003986{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003987 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003988 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003989 struct stream_interface *si = ctx->owner;
3990 struct stream *s = si_strm(si);
3991 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02003992 struct htx *htx;
3993 struct htx_blk *blk;
3994 struct htx_sl *sl;
3995 struct ist path;
3996 unsigned long long len = 0;
3997 int32_t pos;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003998
3999 /* Check stack size. */
4000 if (!lua_checkstack(L, 3))
4001 return 0;
4002
4003 /* Create the object: obj[0] = userdata.
4004 * Note that the base of the Converters object is the
4005 * same than the TXN object.
4006 */
4007 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004008 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004009 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004010 appctx->appctx = ctx;
4011 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004012 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004013 appctx->htxn.s = s;
4014 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004015
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004016 /* Create the "f" field that contains a list of fetches. */
4017 lua_pushstring(L, "f");
4018 if (!hlua_fetches_new(L, &appctx->htxn, 0))
4019 return 0;
4020 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004021
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004022 /* Create the "sf" field that contains a list of stringsafe fetches. */
4023 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004024 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004025 return 0;
4026 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004027
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004028 /* Create the "c" field that contains a list of converters. */
4029 lua_pushstring(L, "c");
4030 if (!hlua_converters_new(L, &appctx->htxn, 0))
4031 return 0;
4032 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004033
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004034 /* Create the "sc" field that contains a list of stringsafe converters. */
4035 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004036 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004037 return 0;
4038 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004039
Christopher Fauleta2097962019-07-15 16:25:33 +02004040 htx = htxbuf(&s->req.buf);
4041 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004042 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004043 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004044
Christopher Fauleta2097962019-07-15 16:25:33 +02004045 /* Stores the request method. */
4046 lua_pushstring(L, "method");
4047 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4048 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004049
Christopher Fauleta2097962019-07-15 16:25:33 +02004050 /* Stores the http version. */
4051 lua_pushstring(L, "version");
4052 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4053 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004054
Christopher Fauleta2097962019-07-15 16:25:33 +02004055 /* creates an array of headers. hlua_http_get_headers() crates and push
4056 * the array on the top of the stack.
4057 */
4058 lua_pushstring(L, "headers");
4059 htxn.s = s;
4060 htxn.p = px;
4061 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004062 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004063 return 0;
4064 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004065
Christopher Fauleta2097962019-07-15 16:25:33 +02004066 path = http_get_path(htx_sl_req_uri(sl));
Tim Duesterhused526372020-03-05 17:56:33 +01004067 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004068 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004069
Christopher Fauleta2097962019-07-15 16:25:33 +02004070 p = path.ptr;
4071 end = path.ptr + path.len;
4072 q = p;
4073 while (q < end && *q != '?')
4074 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004075
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004076 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004077 lua_pushstring(L, "path");
4078 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004079 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004080
Christopher Fauleta2097962019-07-15 16:25:33 +02004081 /* Stores the query string. */
4082 lua_pushstring(L, "qs");
4083 if (*q == '?')
4084 q++;
4085 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004086 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004087 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004088
Christopher Fauleta2097962019-07-15 16:25:33 +02004089 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4090 struct htx_blk *blk = htx_get_blk(htx, pos);
4091 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004092
Christopher Fauleta2097962019-07-15 16:25:33 +02004093 if (type == HTX_BLK_EOM || type == HTX_BLK_TLR || type == HTX_BLK_EOT)
4094 break;
4095 if (type == HTX_BLK_DATA)
4096 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004097 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004098 if (htx->extra != ULLONG_MAX)
4099 len += htx->extra;
4100
4101 /* Stores the request path. */
4102 lua_pushstring(L, "length");
4103 lua_pushinteger(L, len);
4104 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004105
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004106 /* Create an empty array of HTTP request headers. */
4107 lua_pushstring(L, "response");
4108 lua_newtable(L);
4109 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004110
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004111 /* Pop a class stream metatable and affect it to the table. */
4112 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4113 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004114
4115 return 1;
4116}
4117
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004118__LJMP static int hlua_applet_http_set_var(lua_State *L)
4119{
4120 struct hlua_appctx *appctx;
4121 struct stream *s;
4122 const char *name;
4123 size_t len;
4124 struct sample smp;
4125
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004126 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4127 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004128
4129 /* It is useles to retrieve the stream, but this function
4130 * runs only in a stream context.
4131 */
4132 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4133 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4134 s = appctx->htxn.s;
4135
4136 /* Converts the third argument in a sample. */
4137 hlua_lua2smp(L, 3, &smp);
4138
4139 /* Store the sample in a variable. */
4140 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004141
4142 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4143 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4144 else
4145 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4146
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004147 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004148}
4149
4150__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4151{
4152 struct hlua_appctx *appctx;
4153 struct stream *s;
4154 const char *name;
4155 size_t len;
4156 struct sample smp;
4157
4158 MAY_LJMP(check_args(L, 2, "unset_var"));
4159
4160 /* It is useles to retrieve the stream, but this function
4161 * runs only in a stream context.
4162 */
4163 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4164 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4165 s = appctx->htxn.s;
4166
4167 /* Unset the variable. */
4168 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004169 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4170 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004171}
4172
4173__LJMP static int hlua_applet_http_get_var(lua_State *L)
4174{
4175 struct hlua_appctx *appctx;
4176 struct stream *s;
4177 const char *name;
4178 size_t len;
4179 struct sample smp;
4180
4181 MAY_LJMP(check_args(L, 2, "get_var"));
4182
4183 /* It is useles to retrieve the stream, but this function
4184 * runs only in a stream context.
4185 */
4186 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4187 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4188 s = appctx->htxn.s;
4189
4190 smp_set_owner(&smp, s->be, s->sess, s, 0);
4191 if (!vars_get_by_name(name, len, &smp)) {
4192 lua_pushnil(L);
4193 return 1;
4194 }
4195
4196 return hlua_smp2lua(L, &smp);
4197}
4198
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004199__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4200{
4201 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4202 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004203 struct hlua *hlua;
4204
4205 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004206 if (!s->hlua)
4207 return 0;
4208 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004209
4210 MAY_LJMP(check_args(L, 2, "set_priv"));
4211
4212 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004213 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004214
4215 /* Get and store new value. */
4216 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4217 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4218
4219 return 0;
4220}
4221
4222__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4223{
4224 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4225 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004226 struct hlua *hlua;
4227
4228 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004229 if (!s->hlua) {
4230 lua_pushnil(L);
4231 return 1;
4232 }
4233 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004234
4235 /* Push configuration index in the stack. */
4236 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4237
4238 return 1;
4239}
4240
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004241/* If expected data not yet available, it returns a yield. This function
4242 * consumes the data in the buffer. It returns a string containing the
4243 * data. This string can be empty.
4244 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004245__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004246{
4247 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4248 struct stream_interface *si = appctx->appctx->owner;
4249 struct channel *req = si_oc(si);
4250 struct htx *htx;
4251 struct htx_blk *blk;
4252 size_t count;
4253 int stop = 0;
4254
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004255 htx = htx_from_buf(&req->buf);
4256 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004257 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004258
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004259 while (count && !stop && blk) {
4260 enum htx_blk_type type = htx_get_blk_type(blk);
4261 uint32_t sz = htx_get_blksz(blk);
4262 struct ist v;
4263 uint32_t vlen;
4264 char *nl;
4265
Christopher Faulete461e342018-12-18 16:43:35 +01004266 if (type == HTX_BLK_EOM) {
4267 stop = 1;
4268 break;
4269 }
4270
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004271 vlen = sz;
4272 if (vlen > count) {
4273 if (type != HTX_BLK_DATA)
4274 break;
4275 vlen = count;
4276 }
4277
4278 switch (type) {
4279 case HTX_BLK_UNUSED:
4280 break;
4281
4282 case HTX_BLK_DATA:
4283 v = htx_get_blk_value(htx, blk);
4284 v.len = vlen;
4285 nl = istchr(v, '\n');
4286 if (nl != NULL) {
4287 stop = 1;
4288 vlen = nl - v.ptr + 1;
4289 }
4290 luaL_addlstring(&appctx->b, v.ptr, vlen);
4291 break;
4292
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004293 case HTX_BLK_TLR:
4294 case HTX_BLK_EOM:
4295 stop = 1;
4296 break;
4297
4298 default:
4299 break;
4300 }
4301
4302 co_set_data(req, co_data(req) - vlen);
4303 count -= vlen;
4304 if (sz == vlen)
4305 blk = htx_remove_blk(htx, blk);
4306 else {
4307 htx_cut_data_blk(htx, blk, vlen);
4308 break;
4309 }
4310 }
4311
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004312 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004313 if (!stop) {
4314 si_cant_get(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02004315 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004316 }
4317
4318 /* return the result. */
4319 luaL_pushresult(&appctx->b);
4320 return 1;
4321}
4322
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004323
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004324/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004325__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004326{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004327 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004328
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004329 /* Initialise the string catenation. */
4330 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004331
Christopher Fauleta2097962019-07-15 16:25:33 +02004332 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004333}
4334
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004335/* If expected data not yet available, it returns a yield. This function
4336 * consumes the data in the buffer. It returns a string containing the
4337 * data. This string can be empty.
4338 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004339__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004340{
4341 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4342 struct stream_interface *si = appctx->appctx->owner;
4343 struct channel *req = si_oc(si);
4344 struct htx *htx;
4345 struct htx_blk *blk;
4346 size_t count;
4347 int len;
4348
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004349 htx = htx_from_buf(&req->buf);
4350 len = MAY_LJMP(luaL_checkinteger(L, 2));
4351 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02004352 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004353 while (count && len && blk) {
4354 enum htx_blk_type type = htx_get_blk_type(blk);
4355 uint32_t sz = htx_get_blksz(blk);
4356 struct ist v;
4357 uint32_t vlen;
4358
Christopher Faulete461e342018-12-18 16:43:35 +01004359 if (type == HTX_BLK_EOM) {
4360 len = 0;
4361 break;
4362 }
4363
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004364 vlen = sz;
4365 if (len > 0 && vlen > len)
4366 vlen = len;
4367 if (vlen > count) {
4368 if (type != HTX_BLK_DATA)
4369 break;
4370 vlen = count;
4371 }
4372
4373 switch (type) {
4374 case HTX_BLK_UNUSED:
4375 break;
4376
4377 case HTX_BLK_DATA:
4378 v = htx_get_blk_value(htx, blk);
4379 luaL_addlstring(&appctx->b, v.ptr, vlen);
4380 break;
4381
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004382 case HTX_BLK_TLR:
4383 case HTX_BLK_EOM:
4384 len = 0;
4385 break;
4386
4387 default:
4388 break;
4389 }
4390
4391 co_set_data(req, co_data(req) - vlen);
4392 count -= vlen;
4393 if (len > 0)
4394 len -= vlen;
4395 if (sz == vlen)
4396 blk = htx_remove_blk(htx, blk);
4397 else {
4398 htx_cut_data_blk(htx, blk, vlen);
4399 break;
4400 }
4401 }
4402
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004403 htx_to_buf(htx, &req->buf);
4404
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004405 /* If we are no other data available, yield waiting for new data. */
4406 if (len) {
4407 if (len > 0) {
4408 lua_pushinteger(L, len);
4409 lua_replace(L, 2);
4410 }
4411 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004412 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004413 }
4414
4415 /* return the result. */
4416 luaL_pushresult(&appctx->b);
4417 return 1;
4418}
4419
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004420/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004421__LJMP static int hlua_applet_http_recv(lua_State *L)
4422{
4423 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4424 int len = -1;
4425
4426 /* Check arguments. */
4427 if (lua_gettop(L) > 2)
4428 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4429 if (lua_gettop(L) >= 2) {
4430 len = MAY_LJMP(luaL_checkinteger(L, 2));
4431 lua_pop(L, 1);
4432 }
4433
Christopher Fauleta2097962019-07-15 16:25:33 +02004434 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004435
Christopher Fauleta2097962019-07-15 16:25:33 +02004436 /* Initialise the string catenation. */
4437 luaL_buffinit(L, &appctx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004438
Christopher Fauleta2097962019-07-15 16:25:33 +02004439 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004440}
4441
4442/* Append data in the output side of the buffer. This data is immediately
4443 * sent. The function returns the amount of data written. If the buffer
4444 * cannot contain the data, the function yields. The function returns -1
4445 * if the channel is closed.
4446 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004447__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004448{
4449 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4450 struct stream_interface *si = appctx->appctx->owner;
4451 struct channel *res = si_ic(si);
4452 struct htx *htx = htx_from_buf(&res->buf);
4453 const char *data;
4454 size_t len;
4455 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4456 int max;
4457
Christopher Faulet9060fc02019-07-03 11:39:30 +02004458 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004459 if (!max)
4460 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004461
4462 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
4463
4464 /* Get the max amount of data which can write as input in the channel. */
4465 if (max > (len - l))
4466 max = len - l;
4467
4468 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02004469 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004470 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004471
4472 /* update counters. */
4473 l += max;
4474 lua_pop(L, 1);
4475 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004476
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004477 /* If some data is not send, declares the situation to the
4478 * applet, and returns a yield.
4479 */
4480 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004481 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004482 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004483 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004484 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004485 }
4486
Christopher Fauleta2097962019-07-15 16:25:33 +02004487 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004488 return 1;
4489}
4490
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004491/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004492 * yield the LUA process, and resume it without checking the
4493 * input arguments.
4494 */
4495__LJMP static int hlua_applet_http_send(lua_State *L)
4496{
4497 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004498
4499 /* We want to send some data. Headers must be sent. */
4500 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4501 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4502 WILL_LJMP(lua_error(L));
4503 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004504
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004505 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004506 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004507
Christopher Fauleta2097962019-07-15 16:25:33 +02004508 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004509}
4510
4511__LJMP static int hlua_applet_http_addheader(lua_State *L)
4512{
4513 const char *name;
4514 int ret;
4515
4516 MAY_LJMP(hlua_checkapplet_http(L, 1));
4517 name = MAY_LJMP(luaL_checkstring(L, 2));
4518 MAY_LJMP(luaL_checkstring(L, 3));
4519
4520 /* Push in the stack the "response" entry. */
4521 ret = lua_getfield(L, 1, "response");
4522 if (ret != LUA_TTABLE) {
4523 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4524 "is expected as an array. %s found", lua_typename(L, ret));
4525 WILL_LJMP(lua_error(L));
4526 }
4527
4528 /* check if the header is already registered if it is not
4529 * the case, register it.
4530 */
4531 ret = lua_getfield(L, -1, name);
4532 if (ret == LUA_TNIL) {
4533
4534 /* Entry not found. */
4535 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4536
4537 /* Insert the new header name in the array in the top of the stack.
4538 * It left the new array in the top of the stack.
4539 */
4540 lua_newtable(L);
4541 lua_pushvalue(L, 2);
4542 lua_pushvalue(L, -2);
4543 lua_settable(L, -4);
4544
4545 } else if (ret != LUA_TTABLE) {
4546
4547 /* corruption error. */
4548 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4549 "is expected as an array. %s found", name, lua_typename(L, ret));
4550 WILL_LJMP(lua_error(L));
4551 }
4552
4553 /* Now the top od thestack is an array of values. We push
4554 * the header value as new entry.
4555 */
4556 lua_pushvalue(L, 3);
4557 ret = lua_rawlen(L, -2);
4558 lua_rawseti(L, -2, ret + 1);
4559 lua_pushboolean(L, 1);
4560 return 1;
4561}
4562
4563__LJMP static int hlua_applet_http_status(lua_State *L)
4564{
4565 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4566 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004567 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004568
4569 if (status < 100 || status > 599) {
4570 lua_pushboolean(L, 0);
4571 return 1;
4572 }
4573
4574 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004575 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004576 lua_pushboolean(L, 1);
4577 return 1;
4578}
4579
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004580
Christopher Fauleta2097962019-07-15 16:25:33 +02004581__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004582{
4583 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4584 struct stream_interface *si = appctx->appctx->owner;
4585 struct channel *res = si_ic(si);
4586 struct htx *htx;
4587 struct htx_sl *sl;
4588 struct h1m h1m;
4589 const char *status, *reason;
4590 const char *name, *value;
4591 size_t nlen, vlen;
4592 unsigned int flags;
4593
4594 /* Send the message at once. */
4595 htx = htx_from_buf(&res->buf);
4596 h1m_init_res(&h1m);
4597
4598 /* Use the same http version than the request. */
4599 status = ultoa_r(appctx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
4600 reason = appctx->appctx->ctx.hlua_apphttp.reason;
4601 if (reason == NULL)
4602 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
4603 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
4604 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
4605 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
4606 }
4607 else {
4608 flags = HTX_SL_F_IS_RESP;
4609 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
4610 }
4611 if (!sl) {
4612 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
4613 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4614 WILL_LJMP(lua_error(L));
4615 }
4616 sl->info.res.status = appctx->appctx->ctx.hlua_apphttp.status;
4617
4618 /* Get the array associated to the field "response" in the object AppletHTTP. */
4619 lua_pushvalue(L, 0);
4620 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4621 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4622 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4623 WILL_LJMP(lua_error(L));
4624 }
4625
4626 /* Browse the list of headers. */
4627 lua_pushnil(L);
4628 while(lua_next(L, -2) != 0) {
4629 /* We expect a string as -2. */
4630 if (lua_type(L, -2) != LUA_TSTRING) {
4631 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4632 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4633 lua_typename(L, lua_type(L, -2)));
4634 WILL_LJMP(lua_error(L));
4635 }
4636 name = lua_tolstring(L, -2, &nlen);
4637
4638 /* We expect an array as -1. */
4639 if (lua_type(L, -1) != LUA_TTABLE) {
4640 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4641 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4642 name,
4643 lua_typename(L, lua_type(L, -1)));
4644 WILL_LJMP(lua_error(L));
4645 }
4646
4647 /* Browse the table who is on the top of the stack. */
4648 lua_pushnil(L);
4649 while(lua_next(L, -2) != 0) {
4650 int id;
4651
4652 /* We expect a number as -2. */
4653 if (lua_type(L, -2) != LUA_TNUMBER) {
4654 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4655 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4656 name,
4657 lua_typename(L, lua_type(L, -2)));
4658 WILL_LJMP(lua_error(L));
4659 }
4660 id = lua_tointeger(L, -2);
4661
4662 /* We expect a string as -2. */
4663 if (lua_type(L, -1) != LUA_TSTRING) {
4664 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4665 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4666 name, id,
4667 lua_typename(L, lua_type(L, -1)));
4668 WILL_LJMP(lua_error(L));
4669 }
4670 value = lua_tolstring(L, -1, &vlen);
4671
4672 /* Simple Protocol checks. */
4673 if (isteqi(ist2(name, nlen), ist("transfer-encoding")))
Christopher Faulet700d9e82020-01-31 12:21:52 +01004674 h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004675 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
4676 struct ist v = ist2(value, vlen);
4677 int ret;
4678
4679 ret = h1_parse_cont_len_header(&h1m, &v);
4680 if (ret < 0) {
4681 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
4682 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4683 name);
4684 WILL_LJMP(lua_error(L));
4685 }
4686 else if (ret == 0)
4687 goto next; /* Skip it */
4688 }
4689
4690 /* Add a new header */
4691 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
4692 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
4693 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4694 name);
4695 WILL_LJMP(lua_error(L));
4696 }
4697 next:
4698 /* Remove the array from the stack, and get next element with a remaining string. */
4699 lua_pop(L, 1);
4700 }
4701
4702 /* Remove the array from the stack, and get next element with a remaining string. */
4703 lua_pop(L, 1);
4704 }
4705
4706 if (h1m.flags & H1_MF_CHNK)
4707 h1m.flags &= ~H1_MF_CLEN;
4708 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
4709 h1m.flags |= H1_MF_XFER_LEN;
4710
4711 /* Uset HTX start-line flags */
4712 if (h1m.flags & H1_MF_XFER_ENC)
4713 flags |= HTX_SL_F_XFER_ENC;
4714 if (h1m.flags & H1_MF_XFER_LEN) {
4715 flags |= HTX_SL_F_XFER_LEN;
4716 if (h1m.flags & H1_MF_CHNK)
4717 flags |= HTX_SL_F_CHNK;
4718 else if (h1m.flags & H1_MF_CLEN)
4719 flags |= HTX_SL_F_CLEN;
4720 if (h1m.body_len == 0)
4721 flags |= HTX_SL_F_BODYLESS;
4722 }
4723 sl->flags |= flags;
4724
4725 /* If we dont have a content-length set, and the HTTP version is 1.1
4726 * and the status code implies the presence of a message body, we must
4727 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004728 * for the keepalive compliance. If the applet announces a transfer-encoding
4729 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004730 */
4731 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
4732 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4733 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4734 appctx->appctx->ctx.hlua_apphttp.status != 304) {
4735 /* Add a new header */
4736 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
4737 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
4738 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
4739 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4740 WILL_LJMP(lua_error(L));
4741 }
4742 }
4743
4744 /* Finalize headers. */
4745 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
4746 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
4747 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4748 WILL_LJMP(lua_error(L));
4749 }
4750
4751 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
4752 b_reset(&res->buf);
4753 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4754 WILL_LJMP(lua_error(L));
4755 }
4756
4757 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004758 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004759
4760 /* Headers sent, set the flag. */
4761 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4762 return 0;
4763
4764}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004765/* We will build the status line and the headers of the HTTP response.
4766 * We will try send at once if its not possible, we give back the hand
4767 * waiting for more room.
4768 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004769__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004770{
4771 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4772 struct stream_interface *si = appctx->appctx->owner;
4773 struct channel *res = si_ic(si);
4774
4775 if (co_data(res)) {
4776 si_rx_room_blk(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02004777 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004778 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004779 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004780}
4781
4782
Christopher Fauleta2097962019-07-15 16:25:33 +02004783__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004784{
Christopher Fauleta2097962019-07-15 16:25:33 +02004785 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004786}
4787
Christopher Fauleta2097962019-07-15 16:25:33 +02004788/*
4789 *
4790 *
4791 * Class HTTP
4792 *
4793 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004794 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004795
4796/* Returns a struct hlua_txn if the stack entry "ud" is
4797 * a class stream, otherwise it throws an error.
4798 */
4799__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004800{
Christopher Fauleta2097962019-07-15 16:25:33 +02004801 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
4802}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004803
Christopher Fauleta2097962019-07-15 16:25:33 +02004804/* This function creates and push in the stack a HTTP object
4805 * according with a current TXN.
4806 */
4807static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4808{
4809 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004810
Christopher Fauleta2097962019-07-15 16:25:33 +02004811 /* Check stack size. */
4812 if (!lua_checkstack(L, 3))
4813 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004814
Christopher Fauleta2097962019-07-15 16:25:33 +02004815 /* Create the object: obj[0] = userdata.
4816 * Note that the base of the Converters object is the
4817 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004818 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004819 lua_newtable(L);
4820 htxn = lua_newuserdata(L, sizeof(*htxn));
4821 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004822
4823 htxn->s = txn->s;
4824 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02004825 htxn->dir = txn->dir;
4826 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004827
4828 /* Pop a class stream metatable and affect it to the table. */
4829 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4830 lua_setmetatable(L, -2);
4831
4832 return 1;
4833}
4834
4835/* This function creates ans returns an array of HTTP headers.
4836 * This function does not fails. It is used as wrapper with the
4837 * 2 following functions.
4838 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004839__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004840{
Christopher Fauleta2097962019-07-15 16:25:33 +02004841 struct htx *htx;
4842 int32_t pos;
4843
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004844 /* Create the table. */
4845 lua_newtable(L);
4846
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004847
Christopher Fauleta2097962019-07-15 16:25:33 +02004848 htx = htxbuf(&msg->chn->buf);
4849 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4850 struct htx_blk *blk = htx_get_blk(htx, pos);
4851 enum htx_blk_type type = htx_get_blk_type(blk);
4852 struct ist n, v;
4853 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01004854
Christopher Fauleta2097962019-07-15 16:25:33 +02004855 if (type == HTX_BLK_HDR) {
4856 n = htx_get_blk_name(htx,blk);
4857 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01004858 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004859 else if (type == HTX_BLK_EOH)
4860 break;
4861 else
4862 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01004863
Christopher Fauleta2097962019-07-15 16:25:33 +02004864 /* Check for existing entry:
4865 * assume that the table is on the top of the stack, and
4866 * push the key in the stack, the function lua_gettable()
4867 * perform the lookup.
4868 */
4869 lua_pushlstring(L, n.ptr, n.len);
4870 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01004871
Christopher Fauleta2097962019-07-15 16:25:33 +02004872 switch (lua_type(L, -1)) {
4873 case LUA_TNIL:
4874 /* Table not found, create it. */
4875 lua_pop(L, 1); /* remove the nil value. */
4876 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
4877 lua_newtable(L); /* create and push empty table. */
4878 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
4879 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4880 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01004881 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01004882
Christopher Fauleta2097962019-07-15 16:25:33 +02004883 case LUA_TTABLE:
4884 /* Entry found: push the value in the table. */
4885 len = lua_rawlen(L, -1);
4886 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
4887 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4888 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4889 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004890
Christopher Fauleta2097962019-07-15 16:25:33 +02004891 default:
4892 /* Other cases are errors. */
4893 hlua_pusherror(L, "internal error during the parsing of headers.");
4894 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004895 }
4896 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004897 return 1;
4898}
4899
4900__LJMP static int hlua_http_req_get_headers(lua_State *L)
4901{
4902 struct hlua_txn *htxn;
4903
4904 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4905 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4906
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004907 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004908 WILL_LJMP(lua_error(L));
4909
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004910 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004911}
4912
4913__LJMP static int hlua_http_res_get_headers(lua_State *L)
4914{
4915 struct hlua_txn *htxn;
4916
4917 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4918 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4919
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004920 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004921 WILL_LJMP(lua_error(L));
4922
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004923 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004924}
4925
4926/* This function replace full header, or just a value in
4927 * the request or in the response. It is a wrapper fir the
4928 * 4 following functions.
4929 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01004930__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004931{
4932 size_t name_len;
4933 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4934 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4935 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02004936 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02004937 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004938
Dragan Dosen26743032019-04-30 15:54:36 +02004939 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004940 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4941
Christopher Fauleta2097962019-07-15 16:25:33 +02004942 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01004943 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02004944 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004945 return 0;
4946}
4947
4948__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4949{
4950 struct hlua_txn *htxn;
4951
4952 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4953 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4954
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004955 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004956 WILL_LJMP(lua_error(L));
4957
Christopher Fauletd1914aa2020-02-24 16:52:46 +01004958 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004959}
4960
4961__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4962{
4963 struct hlua_txn *htxn;
4964
4965 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4966 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4967
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004968 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004969 WILL_LJMP(lua_error(L));
4970
Christopher Fauletd1914aa2020-02-24 16:52:46 +01004971 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004972}
4973
4974__LJMP static int hlua_http_req_rep_val(lua_State *L)
4975{
4976 struct hlua_txn *htxn;
4977
4978 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4979 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4980
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004981 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004982 WILL_LJMP(lua_error(L));
4983
Christopher Fauletd1914aa2020-02-24 16:52:46 +01004984 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004985}
4986
4987__LJMP static int hlua_http_res_rep_val(lua_State *L)
4988{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004989 struct hlua_txn *htxn;
4990
4991 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4992 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4993
Christopher Fauletd8f0e072020-02-25 09:45:51 +01004994 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004995 WILL_LJMP(lua_error(L));
4996
Christopher Fauletd1914aa2020-02-24 16:52:46 +01004997 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004998}
4999
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005000/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005001 * It is a wrapper for the 2 following functions.
5002 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005003__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005004{
5005 size_t len;
5006 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005007 struct htx *htx = htxbuf(&msg->chn->buf);
5008 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005009
Christopher Fauleta2097962019-07-15 16:25:33 +02005010 ctx.blk = NULL;
5011 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5012 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005013 return 0;
5014}
5015
5016__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5017{
5018 struct hlua_txn *htxn;
5019
5020 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5021 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5022
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005023 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005024 WILL_LJMP(lua_error(L));
5025
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005026 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005027}
5028
5029__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5030{
5031 struct hlua_txn *htxn;
5032
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005033 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005034 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5035
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005036 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005037 WILL_LJMP(lua_error(L));
5038
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005039 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005040}
5041
5042/* This function adds an header. It is a wrapper used by
5043 * the 2 following functions.
5044 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005045__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005046{
5047 size_t name_len;
5048 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5049 size_t value_len;
5050 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005051 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005052
Christopher Fauleta2097962019-07-15 16:25:33 +02005053 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5054 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005055 return 0;
5056}
5057
5058__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5059{
5060 struct hlua_txn *htxn;
5061
5062 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5063 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5064
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005065 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005066 WILL_LJMP(lua_error(L));
5067
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005068 return hlua_http_add_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005069}
5070
5071__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5072{
5073 struct hlua_txn *htxn;
5074
5075 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5076 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5077
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005078 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005079 WILL_LJMP(lua_error(L));
5080
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005081 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005082}
5083
5084static int hlua_http_req_set_hdr(lua_State *L)
5085{
5086 struct hlua_txn *htxn;
5087
5088 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5089 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5090
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005091 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005092 WILL_LJMP(lua_error(L));
5093
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005094 hlua_http_del_hdr(L, &htxn->s->txn->req);
5095 return hlua_http_add_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005096}
5097
5098static int hlua_http_res_set_hdr(lua_State *L)
5099{
5100 struct hlua_txn *htxn;
5101
5102 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5103 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5104
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005105 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005106 WILL_LJMP(lua_error(L));
5107
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005108 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5109 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005110}
5111
5112/* This function set the method. */
5113static int hlua_http_req_set_meth(lua_State *L)
5114{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005115 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005116 size_t name_len;
5117 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005118
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005119 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005120 WILL_LJMP(lua_error(L));
5121
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005122 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005123 return 1;
5124}
5125
5126/* This function set the method. */
5127static int hlua_http_req_set_path(lua_State *L)
5128{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005129 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005130 size_t name_len;
5131 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005132
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005133 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005134 WILL_LJMP(lua_error(L));
5135
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005136 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005137 return 1;
5138}
5139
5140/* This function set the query-string. */
5141static int hlua_http_req_set_query(lua_State *L)
5142{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005143 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005144 size_t name_len;
5145 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005146
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005147 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005148 WILL_LJMP(lua_error(L));
5149
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005150 /* Check length. */
5151 if (name_len > trash.size - 1) {
5152 lua_pushboolean(L, 0);
5153 return 1;
5154 }
5155
5156 /* Add the mark question as prefix. */
5157 chunk_reset(&trash);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005158 trash.area[trash.data++] = '?';
5159 memcpy(trash.area + trash.data, name, name_len);
5160 trash.data += name_len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005161
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005162 lua_pushboolean(L,
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005163 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005164 return 1;
5165}
5166
5167/* This function set the uri. */
5168static int hlua_http_req_set_uri(lua_State *L)
5169{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005170 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005171 size_t name_len;
5172 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005173
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005174 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005175 WILL_LJMP(lua_error(L));
5176
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005177 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005178 return 1;
5179}
5180
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005181/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005182static int hlua_http_res_set_status(lua_State *L)
5183{
5184 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5185 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Faulet96bff762019-12-17 13:46:18 +01005186 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5187 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005188
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005189 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005190 WILL_LJMP(lua_error(L));
5191
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005192 http_res_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005193 return 0;
5194}
5195
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005196/*
5197 *
5198 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005199 * Class TXN
5200 *
5201 *
5202 */
5203
5204/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005205 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005206 */
5207__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
5208{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005209 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005210}
5211
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005212__LJMP static int hlua_set_var(lua_State *L)
5213{
5214 struct hlua_txn *htxn;
5215 const char *name;
5216 size_t len;
5217 struct sample smp;
5218
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005219 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
5220 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005221
5222 /* It is useles to retrieve the stream, but this function
5223 * runs only in a stream context.
5224 */
5225 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5226 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5227
5228 /* Converts the third argument in a sample. */
5229 hlua_lua2smp(L, 3, &smp);
5230
5231 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005232 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005233
5234 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
5235 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
5236 else
5237 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
5238
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005239 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005240}
5241
Christopher Faulet85d79c92016-11-09 16:54:56 +01005242__LJMP static int hlua_unset_var(lua_State *L)
5243{
5244 struct hlua_txn *htxn;
5245 const char *name;
5246 size_t len;
5247 struct sample smp;
5248
5249 MAY_LJMP(check_args(L, 2, "unset_var"));
5250
5251 /* It is useles to retrieve the stream, but this function
5252 * runs only in a stream context.
5253 */
5254 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5255 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5256
5257 /* Unset the variable. */
5258 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005259 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
5260 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01005261}
5262
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005263__LJMP static int hlua_get_var(lua_State *L)
5264{
5265 struct hlua_txn *htxn;
5266 const char *name;
5267 size_t len;
5268 struct sample smp;
5269
5270 MAY_LJMP(check_args(L, 2, "get_var"));
5271
5272 /* It is useles to retrieve the stream, but this function
5273 * runs only in a stream context.
5274 */
5275 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5276 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5277
Willy Tarreau7560dd42016-03-10 16:28:58 +01005278 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005279 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005280 lua_pushnil(L);
5281 return 1;
5282 }
5283
5284 return hlua_smp2lua(L, &smp);
5285}
5286
Willy Tarreau59551662015-03-10 14:23:13 +01005287__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005288{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005289 struct hlua *hlua;
5290
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005291 MAY_LJMP(check_args(L, 2, "set_priv"));
5292
Willy Tarreau87b09662015-04-03 00:22:06 +02005293 /* It is useles to retrieve the stream, but this function
5294 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005295 */
5296 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005297 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005298
5299 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005300 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005301
5302 /* Get and store new value. */
5303 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5304 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5305
5306 return 0;
5307}
5308
Willy Tarreau59551662015-03-10 14:23:13 +01005309__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005310{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005311 struct hlua *hlua;
5312
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005313 MAY_LJMP(check_args(L, 1, "get_priv"));
5314
Willy Tarreau87b09662015-04-03 00:22:06 +02005315 /* It is useles to retrieve the stream, but this function
5316 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005317 */
5318 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005319 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005320
5321 /* Push configuration index in the stack. */
5322 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5323
5324 return 1;
5325}
5326
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005327/* Create stack entry containing a class TXN. This function
5328 * return 0 if the stack does not contains free slots,
5329 * otherwise it returns 1.
5330 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005331static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005332{
Willy Tarreaude491382015-04-06 11:04:28 +02005333 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005334
5335 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005336 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005337 return 0;
5338
5339 /* NOTE: The allocation never fails. The failure
5340 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005341 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005342 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005343 /* Create the object: obj[0] = userdata. */
5344 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005345 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005346 lua_rawseti(L, -2, 0);
5347
Willy Tarreaude491382015-04-06 11:04:28 +02005348 htxn->s = s;
5349 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005350 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005351 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005352
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005353 /* Create the "f" field that contains a list of fetches. */
5354 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005355 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005356 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005357 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005358
5359 /* Create the "sf" field that contains a list of stringsafe fetches. */
5360 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005361 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005362 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005363 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005364
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005365 /* Create the "c" field that contains a list of converters. */
5366 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005367 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005368 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005369 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005370
5371 /* Create the "sc" field that contains a list of stringsafe converters. */
5372 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005373 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005374 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005375 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005376
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005377 /* Create the "req" field that contains the request channel object. */
5378 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005379 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005380 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005381 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005382
5383 /* Create the "res" field that contains the response channel object. */
5384 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005385 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005386 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005387 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005388
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005389 /* Creates the HTTP object is the current proxy allows http. */
5390 lua_pushstring(L, "http");
5391 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005392 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005393 return 0;
5394 }
5395 else
5396 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005397 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005398
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005399 /* Pop a class sesison metatable and affect it to the userdata. */
5400 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5401 lua_setmetatable(L, -2);
5402
5403 return 1;
5404}
5405
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005406__LJMP static int hlua_txn_deflog(lua_State *L)
5407{
5408 const char *msg;
5409 struct hlua_txn *htxn;
5410
5411 MAY_LJMP(check_args(L, 2, "deflog"));
5412 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5413 msg = MAY_LJMP(luaL_checkstring(L, 2));
5414
5415 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5416 return 0;
5417}
5418
5419__LJMP static int hlua_txn_log(lua_State *L)
5420{
5421 int level;
5422 const char *msg;
5423 struct hlua_txn *htxn;
5424
5425 MAY_LJMP(check_args(L, 3, "log"));
5426 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5427 level = MAY_LJMP(luaL_checkinteger(L, 2));
5428 msg = MAY_LJMP(luaL_checkstring(L, 3));
5429
5430 if (level < 0 || level >= NB_LOG_LEVELS)
5431 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5432
5433 hlua_sendlog(htxn->s->be, level, msg);
5434 return 0;
5435}
5436
5437__LJMP static int hlua_txn_log_debug(lua_State *L)
5438{
5439 const char *msg;
5440 struct hlua_txn *htxn;
5441
5442 MAY_LJMP(check_args(L, 2, "Debug"));
5443 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5444 msg = MAY_LJMP(luaL_checkstring(L, 2));
5445 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5446 return 0;
5447}
5448
5449__LJMP static int hlua_txn_log_info(lua_State *L)
5450{
5451 const char *msg;
5452 struct hlua_txn *htxn;
5453
5454 MAY_LJMP(check_args(L, 2, "Info"));
5455 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5456 msg = MAY_LJMP(luaL_checkstring(L, 2));
5457 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5458 return 0;
5459}
5460
5461__LJMP static int hlua_txn_log_warning(lua_State *L)
5462{
5463 const char *msg;
5464 struct hlua_txn *htxn;
5465
5466 MAY_LJMP(check_args(L, 2, "Warning"));
5467 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5468 msg = MAY_LJMP(luaL_checkstring(L, 2));
5469 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5470 return 0;
5471}
5472
5473__LJMP static int hlua_txn_log_alert(lua_State *L)
5474{
5475 const char *msg;
5476 struct hlua_txn *htxn;
5477
5478 MAY_LJMP(check_args(L, 2, "Alert"));
5479 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5480 msg = MAY_LJMP(luaL_checkstring(L, 2));
5481 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5482 return 0;
5483}
5484
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005485__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5486{
5487 struct hlua_txn *htxn;
5488 int ll;
5489
5490 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5491 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5492 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5493
5494 if (ll < 0 || ll > 7)
5495 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5496
5497 htxn->s->logs.level = ll;
5498 return 0;
5499}
5500
5501__LJMP static int hlua_txn_set_tos(lua_State *L)
5502{
5503 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005504 int tos;
5505
5506 MAY_LJMP(check_args(L, 2, "set_tos"));
5507 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5508 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5509
Willy Tarreau1a18b542018-12-11 16:37:42 +01005510 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005511 return 0;
5512}
5513
5514__LJMP static int hlua_txn_set_mark(lua_State *L)
5515{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005516 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005517 int mark;
5518
5519 MAY_LJMP(check_args(L, 2, "set_mark"));
5520 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5521 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5522
Lukas Tribus579e3e32019-08-11 18:03:45 +02005523 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005524 return 0;
5525}
5526
Patrick Hemmer268a7072018-05-11 12:52:31 -04005527__LJMP static int hlua_txn_set_priority_class(lua_State *L)
5528{
5529 struct hlua_txn *htxn;
5530
5531 MAY_LJMP(check_args(L, 2, "set_priority_class"));
5532 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5533 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
5534 return 0;
5535}
5536
5537__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
5538{
5539 struct hlua_txn *htxn;
5540
5541 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
5542 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5543 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
5544 return 0;
5545}
5546
Christopher Faulet700d9e82020-01-31 12:21:52 +01005547/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005548 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01005549 * message and terminate the transaction. It returns 1 on success and 0 on
5550 * error. The Reply must be on top of the stack.
5551 */
5552__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
5553{
5554 struct htx *htx;
5555 struct htx_sl *sl;
5556 struct h1m h1m;
5557 const char *status, *reason, *body;
5558 size_t status_len, reason_len, body_len;
5559 int ret, code, flags;
5560
5561 code = 200;
5562 status = "200";
5563 status_len = 3;
5564 ret = lua_getfield(L, -1, "status");
5565 if (ret == LUA_TNUMBER) {
5566 code = lua_tointeger(L, -1);
5567 status = lua_tolstring(L, -1, &status_len);
5568 }
5569 lua_pop(L, 1);
5570
5571 reason = http_get_reason(code);
5572 reason_len = strlen(reason);
5573 ret = lua_getfield(L, -1, "reason");
5574 if (ret == LUA_TSTRING)
5575 reason = lua_tolstring(L, -1, &reason_len);
5576 lua_pop(L, 1);
5577
5578 body = NULL;
5579 body_len = 0;
5580 ret = lua_getfield(L, -1, "body");
5581 if (ret == LUA_TSTRING)
5582 body = lua_tolstring(L, -1, &body_len);
5583 lua_pop(L, 1);
5584
5585 /* Prepare the response before inserting the headers */
5586 h1m_init_res(&h1m);
5587 htx = htx_from_buf(&s->res.buf);
5588 channel_htx_truncate(&s->res, htx);
5589 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
5590 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5591 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
5592 ist2(status, status_len), ist2(reason, reason_len));
5593 }
5594 else {
5595 flags = HTX_SL_F_IS_RESP;
5596 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
5597 ist2(status, status_len), ist2(reason, reason_len));
5598 }
5599 if (!sl)
5600 goto fail;
5601 sl->info.res.status = code;
5602
5603 /* Push in the stack the "headers" entry. */
5604 ret = lua_getfield(L, -1, "headers");
5605 if (ret != LUA_TTABLE)
5606 goto skip_headers;
5607
5608 lua_pushnil(L);
5609 while (lua_next(L, -2) != 0) {
5610 struct ist name, value;
5611 const char *n, *v;
5612 size_t nlen, vlen;
5613
5614 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
5615 /* Skip element if the key is not a string or if the value is not a table */
5616 goto next_hdr;
5617 }
5618
5619 n = lua_tolstring(L, -2, &nlen);
5620 name = ist2(n, nlen);
5621 if (isteqi(name, ist("content-length"))) {
5622 /* Always skip content-length header. It will be added
5623 * later with the correct len
5624 */
5625 goto next_hdr;
5626 }
5627
5628 /* Loop on header's values */
5629 lua_pushnil(L);
5630 while (lua_next(L, -2)) {
5631 if (!lua_isstring(L, -1)) {
5632 /* Skip the value if it is not a string */
5633 goto next_value;
5634 }
5635
5636 v = lua_tolstring(L, -1, &vlen);
5637 value = ist2(v, vlen);
5638
5639 if (isteqi(name, ist("transfer-encoding")))
5640 h1_parse_xfer_enc_header(&h1m, value);
5641 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
5642 goto fail;
5643
5644 next_value:
5645 lua_pop(L, 1);
5646 }
5647
5648 next_hdr:
5649 lua_pop(L, 1);
5650 }
5651 skip_headers:
5652 lua_pop(L, 1);
5653
5654 /* Update h1m flags: CLEN is set if CHNK is not present */
5655 if (!(h1m.flags & H1_MF_CHNK)) {
5656 const char *clen = ultoa(body_len);
5657
5658 h1m.flags |= H1_MF_CLEN;
5659 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
5660 goto fail;
5661 }
5662 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5663 h1m.flags |= H1_MF_XFER_LEN;
5664
5665 /* Update HTX start-line flags */
5666 if (h1m.flags & H1_MF_XFER_ENC)
5667 flags |= HTX_SL_F_XFER_ENC;
5668 if (h1m.flags & H1_MF_XFER_LEN) {
5669 flags |= HTX_SL_F_XFER_LEN;
5670 if (h1m.flags & H1_MF_CHNK)
5671 flags |= HTX_SL_F_CHNK;
5672 else if (h1m.flags & H1_MF_CLEN)
5673 flags |= HTX_SL_F_CLEN;
5674 if (h1m.body_len == 0)
5675 flags |= HTX_SL_F_BODYLESS;
5676 }
5677 sl->flags |= flags;
5678
5679
5680 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
5681 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))) ||
5682 !htx_add_endof(htx, HTX_BLK_EOM))
5683 goto fail;
5684
5685 /* Now, forward the response and terminate the transaction */
5686 s->txn->status = code;
5687 htx_to_buf(htx, &s->res.buf);
5688 if (!http_forward_proxy_resp(s, 1))
5689 goto fail;
5690
5691 return 1;
5692
5693 fail:
5694 channel_htx_truncate(&s->res, htx);
5695 return 0;
5696}
5697
5698/* Terminate a transaction if called from a lua action. For TCP streams,
5699 * processing is just aborted. Nothing is returned to the client and all
5700 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
5701 * is forwarded to the client before terminating the transaction. On success,
5702 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
5703 * with ACT_RET_ERR code. If this function is not called from a lua action, it
5704 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005705 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005706__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005707{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005708 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01005709 struct stream *s;
5710 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005711
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005712 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005713
Christopher Faulet700d9e82020-01-31 12:21:52 +01005714 /* If the flags NOTERM is set, we cannot terminate the session, so we
5715 * just end the execution of the current lua code. */
5716 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005717 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005718
Christopher Faulet700d9e82020-01-31 12:21:52 +01005719 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005720 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01005721 struct channel *req = &s->req;
5722 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005723
Christopher Faulet700d9e82020-01-31 12:21:52 +01005724 channel_auto_read(req);
5725 channel_abort(req);
5726 channel_auto_close(req);
5727 channel_erase(req);
5728
5729 res->wex = tick_add_ifset(now_ms, res->wto);
5730 channel_auto_read(res);
5731 channel_auto_close(res);
5732 channel_shutr_now(res);
5733
5734 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
5735 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02005736 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005737
Christopher Faulet700d9e82020-01-31 12:21:52 +01005738 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
5739 /* No reply or invalid reply */
5740 s->txn->status = 0;
5741 http_reply_and_close(s, 0, NULL);
5742 }
5743 else {
5744 /* Remove extra args to have the reply on top of the stack */
5745 if (lua_gettop(L) > 2)
5746 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005747
Christopher Faulet700d9e82020-01-31 12:21:52 +01005748 if (!hlua_txn_forward_reply(L, s)) {
5749 if (!(s->flags & SF_ERR_MASK))
5750 s->flags |= SF_ERR_PRXCOND;
5751 lua_pushinteger(L, ACT_RET_ERR);
5752 WILL_LJMP(hlua_done(L));
5753 return 0; /* Never reached */
5754 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02005755 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005756
Christopher Faulet700d9e82020-01-31 12:21:52 +01005757 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
5758 if (htxn->dir == SMP_OPT_DIR_REQ) {
5759 /* let's log the request time */
5760 s->logs.tv_request = now;
5761 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
5762 _HA_ATOMIC_ADD(&s->sess->fe->fe_counters.intercepted_req, 1);
5763 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02005764
Christopher Faulet700d9e82020-01-31 12:21:52 +01005765 done:
5766 if (!(s->flags & SF_ERR_MASK))
5767 s->flags |= SF_ERR_LOCAL;
5768 if (!(s->flags & SF_FINST_MASK))
5769 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02005770
Christopher Faulet4ad73102020-03-05 11:07:31 +01005771 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005772 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005773 return 0;
5774}
5775
Christopher Faulet700d9e82020-01-31 12:21:52 +01005776/*
5777 *
5778 *
5779 * Class REPLY
5780 *
5781 *
5782 */
5783
5784/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
5785 * free slots, the function fails and returns 0;
5786 */
5787static int hlua_txn_reply_new(lua_State *L)
5788{
5789 struct hlua_txn *htxn;
5790 const char *reason, *body = NULL;
5791 int ret, status;
5792
5793 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005794 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01005795 hlua_pusherror(L, "txn object is not an HTTP transaction.");
5796 WILL_LJMP(lua_error(L));
5797 }
5798
5799 /* Default value */
5800 status = 200;
5801 reason = http_get_reason(status);
5802
5803 if (lua_istable(L, 2)) {
5804 /* load status and reason from the table argument at index 2 */
5805 ret = lua_getfield(L, 2, "status");
5806 if (ret == LUA_TNIL)
5807 goto reason;
5808 else if (ret != LUA_TNUMBER) {
5809 /* invalid status: ignore the reason */
5810 goto body;
5811 }
5812 status = lua_tointeger(L, -1);
5813
5814 reason:
5815 lua_pop(L, 1); /* restore the stack: remove status */
5816 ret = lua_getfield(L, 2, "reason");
5817 if (ret == LUA_TSTRING)
5818 reason = lua_tostring(L, -1);
5819
5820 body:
5821 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
5822 ret = lua_getfield(L, 2, "body");
5823 if (ret == LUA_TSTRING)
5824 body = lua_tostring(L, -1);
5825 lua_pop(L, 1); /* restore the stack: remove body */
5826 }
5827
5828 /* Create the Reply table */
5829 lua_newtable(L);
5830
5831 /* Add status element */
5832 lua_pushstring(L, "status");
5833 lua_pushinteger(L, status);
5834 lua_settable(L, -3);
5835
5836 /* Add reason element */
5837 reason = http_get_reason(status);
5838 lua_pushstring(L, "reason");
5839 lua_pushstring(L, reason);
5840 lua_settable(L, -3);
5841
5842 /* Add body element, nil if undefined */
5843 lua_pushstring(L, "body");
5844 if (body)
5845 lua_pushstring(L, body);
5846 else
5847 lua_pushnil(L);
5848 lua_settable(L, -3);
5849
5850 /* Add headers element */
5851 lua_pushstring(L, "headers");
5852 lua_newtable(L);
5853
5854 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
5855 if (lua_istable(L, 2)) {
5856 /* load headers from the table argument at index 2. If it is a table, copy it. */
5857 ret = lua_getfield(L, 2, "headers");
5858 if (ret == LUA_TTABLE) {
5859 /* stack: [ ... <headers:table>, <table> ] */
5860 lua_pushnil(L);
5861 while (lua_next(L, -2) != 0) {
5862 /* stack: [ ... <headers:table>, <table>, k, v] */
5863 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
5864 /* invalid value type, skip it */
5865 lua_pop(L, 1);
5866 continue;
5867 }
5868
5869
5870 /* Duplicate the key and swap it with the value. */
5871 lua_pushvalue(L, -2);
5872 lua_insert(L, -2);
5873 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
5874
5875 lua_newtable(L);
5876 lua_insert(L, -2);
5877 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
5878
5879 if (lua_isstring(L, -1)) {
5880 /* push the value in the inner table */
5881 lua_rawseti(L, -2, 1);
5882 }
5883 else { /* table */
5884 lua_pushnil(L);
5885 while (lua_next(L, -2) != 0) {
5886 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
5887 if (!lua_isstring(L, -1)) {
5888 /* invalid value type, skip it*/
5889 lua_pop(L, 1);
5890 continue;
5891 }
5892 /* push the value in the inner table */
5893 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
5894 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
5895 }
5896 lua_pop(L, 1);
5897 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
5898 }
5899
5900 /* push (k,v) on the stack in the headers table:
5901 * stack: [ ... <headers:table>, <table>, k, k, v ]
5902 */
5903 lua_settable(L, -5);
5904 /* stack: [ ... <headers:table>, <table>, k ] */
5905 }
5906 }
5907 lua_pop(L, 1);
5908 }
5909 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
5910 lua_settable(L, -3);
5911 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
5912
5913 /* Pop a class sesison metatable and affect it to the userdata. */
5914 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
5915 lua_setmetatable(L, -2);
5916 return 1;
5917}
5918
5919/* Set the reply status code, and optionally the reason. If no reason is
5920 * provided, the default one corresponding to the status code is used.
5921 */
5922__LJMP static int hlua_txn_reply_set_status(lua_State *L)
5923{
5924 int status = MAY_LJMP(luaL_checkinteger(L, 2));
5925 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5926
5927 /* First argument (self) must be a table */
5928 luaL_checktype(L, 1, LUA_TTABLE);
5929
5930 if (status < 100 || status > 599) {
5931 lua_pushboolean(L, 0);
5932 return 1;
5933 }
5934 if (!reason)
5935 reason = http_get_reason(status);
5936
5937 lua_pushinteger(L, status);
5938 lua_setfield(L, 1, "status");
5939
5940 lua_pushstring(L, reason);
5941 lua_setfield(L, 1, "reason");
5942
5943 lua_pushboolean(L, 1);
5944 return 1;
5945}
5946
5947/* Add a header into the reply object. Each header name is associated to an
5948 * array of values in the "headers" table. If the header name is not found, a
5949 * new entry is created.
5950 */
5951__LJMP static int hlua_txn_reply_add_header(lua_State *L)
5952{
5953 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
5954 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
5955 int ret;
5956
5957 /* First argument (self) must be a table */
5958 luaL_checktype(L, 1, LUA_TTABLE);
5959
5960 /* Push in the stack the "headers" entry. */
5961 ret = lua_getfield(L, 1, "headers");
5962 if (ret != LUA_TTABLE) {
5963 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
5964 WILL_LJMP(lua_error(L));
5965 }
5966
5967 /* check if the header is already registered. If not, register it. */
5968 ret = lua_getfield(L, -1, name);
5969 if (ret == LUA_TNIL) {
5970 /* Entry not found. */
5971 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
5972
5973 /* Insert the new header name in the array in the top of the stack.
5974 * It left the new array in the top of the stack.
5975 */
5976 lua_newtable(L);
5977 lua_pushstring(L, name);
5978 lua_pushvalue(L, -2);
5979 lua_settable(L, -4);
5980 }
5981 else if (ret != LUA_TTABLE) {
5982 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
5983 WILL_LJMP(lua_error(L));
5984 }
5985
5986 /* Now the top od thestack is an array of values. We push
5987 * the header value as new entry.
5988 */
5989 lua_pushstring(L, value);
5990 ret = lua_rawlen(L, -2);
5991 lua_rawseti(L, -2, ret + 1);
5992
5993 lua_pushboolean(L, 1);
5994 return 1;
5995}
5996
5997/* Remove all occurrences of a given header name. */
5998__LJMP static int hlua_txn_reply_del_header(lua_State *L)
5999{
6000 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
6001 int ret;
6002
6003 /* First argument (self) must be a table */
6004 luaL_checktype(L, 1, LUA_TTABLE);
6005
6006 /* Push in the stack the "headers" entry. */
6007 ret = lua_getfield(L, 1, "headers");
6008 if (ret != LUA_TTABLE) {
6009 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
6010 WILL_LJMP(lua_error(L));
6011 }
6012
6013 lua_pushstring(L, name);
6014 lua_pushnil(L);
6015 lua_settable(L, -3);
6016
6017 lua_pushboolean(L, 1);
6018 return 1;
6019}
6020
6021/* Set the reply's body. Overwrite any existing entry. */
6022__LJMP static int hlua_txn_reply_set_body(lua_State *L)
6023{
6024 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
6025
6026 /* First argument (self) must be a table */
6027 luaL_checktype(L, 1, LUA_TTABLE);
6028
6029 lua_pushstring(L, payload);
6030 lua_setfield(L, 1, "body");
6031
6032 lua_pushboolean(L, 1);
6033 return 1;
6034}
6035
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006036__LJMP static int hlua_log(lua_State *L)
6037{
6038 int level;
6039 const char *msg;
6040
6041 MAY_LJMP(check_args(L, 2, "log"));
6042 level = MAY_LJMP(luaL_checkinteger(L, 1));
6043 msg = MAY_LJMP(luaL_checkstring(L, 2));
6044
6045 if (level < 0 || level >= NB_LOG_LEVELS)
6046 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
6047
6048 hlua_sendlog(NULL, level, msg);
6049 return 0;
6050}
6051
6052__LJMP static int hlua_log_debug(lua_State *L)
6053{
6054 const char *msg;
6055
6056 MAY_LJMP(check_args(L, 1, "debug"));
6057 msg = MAY_LJMP(luaL_checkstring(L, 1));
6058 hlua_sendlog(NULL, LOG_DEBUG, msg);
6059 return 0;
6060}
6061
6062__LJMP static int hlua_log_info(lua_State *L)
6063{
6064 const char *msg;
6065
6066 MAY_LJMP(check_args(L, 1, "info"));
6067 msg = MAY_LJMP(luaL_checkstring(L, 1));
6068 hlua_sendlog(NULL, LOG_INFO, msg);
6069 return 0;
6070}
6071
6072__LJMP static int hlua_log_warning(lua_State *L)
6073{
6074 const char *msg;
6075
6076 MAY_LJMP(check_args(L, 1, "warning"));
6077 msg = MAY_LJMP(luaL_checkstring(L, 1));
6078 hlua_sendlog(NULL, LOG_WARNING, msg);
6079 return 0;
6080}
6081
6082__LJMP static int hlua_log_alert(lua_State *L)
6083{
6084 const char *msg;
6085
6086 MAY_LJMP(check_args(L, 1, "alert"));
6087 msg = MAY_LJMP(luaL_checkstring(L, 1));
6088 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006089 return 0;
6090}
6091
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006092__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006093{
6094 int wakeup_ms = lua_tointeger(L, -1);
6095 if (now_ms < wakeup_ms)
Willy Tarreau9635e032018-10-16 17:52:55 +02006096 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006097 return 0;
6098}
6099
6100__LJMP static int hlua_sleep(lua_State *L)
6101{
6102 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006103 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006104
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006105 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006106
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006107 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006108 wakeup_ms = tick_add(now_ms, delay);
6109 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006110
Willy Tarreau9635e032018-10-16 17:52:55 +02006111 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006112 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006113}
6114
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006115__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006116{
6117 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006118 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006119
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006120 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006121
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006122 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006123 wakeup_ms = tick_add(now_ms, delay);
6124 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006125
Willy Tarreau9635e032018-10-16 17:52:55 +02006126 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006127 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006128}
6129
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006130/* This functionis an LUA binding. it permits to give back
6131 * the hand at the HAProxy scheduler. It is used when the
6132 * LUA processing consumes a lot of time.
6133 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006134__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006135{
6136 return 0;
6137}
6138
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006139__LJMP static int hlua_yield(lua_State *L)
6140{
Willy Tarreau9635e032018-10-16 17:52:55 +02006141 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006142 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006143}
6144
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006145/* This function change the nice of the currently executed
6146 * task. It is used set low or high priority at the current
6147 * task.
6148 */
Willy Tarreau59551662015-03-10 14:23:13 +01006149__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006150{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006151 struct hlua *hlua;
6152 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006153
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006154 MAY_LJMP(check_args(L, 1, "set_nice"));
6155 hlua = hlua_gethlua(L);
6156 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006157
6158 /* If he task is not set, I'm in a start mode. */
6159 if (!hlua || !hlua->task)
6160 return 0;
6161
6162 if (nice < -1024)
6163 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006164 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006165 nice = 1024;
6166
6167 hlua->task->nice = nice;
6168 return 0;
6169}
6170
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006171/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006172 * HAProxy task subsystem when the task is awaked. The LUA runtime can
6173 * return an E_AGAIN signal, the emmiter of this signal must set a
6174 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006175 *
6176 * Task wrapper are longjmp safe because the only one Lua code
6177 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006178 */
Willy Tarreau60409db2019-08-21 14:14:50 +02006179struct task *hlua_process_task(struct task *task, void *context, unsigned short state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006180{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006181 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006182 enum hlua_exec status;
6183
Christopher Faulet5bc99722018-04-25 10:34:45 +02006184 if (task->thread_mask == MAX_THREADS_MASK)
6185 task_set_affinity(task, tid_bit);
6186
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006187 /* If it is the first call to the task, we must initialize the
6188 * execution timeouts.
6189 */
6190 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006191 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006192
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006193 /* Execute the Lua code. */
6194 status = hlua_ctx_resume(hlua, 1);
6195
6196 switch (status) {
6197 /* finished or yield */
6198 case HLUA_E_OK:
6199 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006200 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02006201 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006202 break;
6203
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006204 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01006205 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02006206 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006207 break;
6208
6209 /* finished with error. */
6210 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006211 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006212 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006213 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006214 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006215 break;
6216
6217 case HLUA_E_ERR:
6218 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006219 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006220 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006221 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006222 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006223 break;
6224 }
Emeric Brun253e53e2017-10-17 18:58:40 +02006225 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006226}
6227
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006228/* This function is an LUA binding that register LUA function to be
6229 * executed after the HAProxy configuration parsing and before the
6230 * HAProxy scheduler starts. This function expect only one LUA
6231 * argument that is a function. This function returns nothing, but
6232 * throws if an error is encountered.
6233 */
6234__LJMP static int hlua_register_init(lua_State *L)
6235{
6236 struct hlua_init_function *init;
6237 int ref;
6238
6239 MAY_LJMP(check_args(L, 1, "register_init"));
6240
6241 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6242
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006243 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006244 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006245 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006246
6247 init->function_ref = ref;
6248 LIST_ADDQ(&hlua_init_functions, &init->l);
6249 return 0;
6250}
6251
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006252/* This functio is an LUA binding. It permits to register a task
6253 * executed in parallel of the main HAroxy activity. The task is
6254 * created and it is set in the HAProxy scheduler. It can be called
6255 * from the "init" section, "post init" or during the runtime.
6256 *
6257 * Lua prototype:
6258 *
6259 * <none> core.register_task(<function>)
6260 */
6261static int hlua_register_task(lua_State *L)
6262{
6263 struct hlua *hlua;
6264 struct task *task;
6265 int ref;
6266
6267 MAY_LJMP(check_args(L, 1, "register_task"));
6268
6269 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6270
Willy Tarreaubafbe012017-11-24 17:34:44 +01006271 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006272 if (!hlua)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006273 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006274
Emeric Brunc60def82017-09-27 14:59:38 +02006275 task = task_new(MAX_THREADS_MASK);
Willy Tarreaue09101e2018-10-16 17:37:12 +02006276 if (!task)
6277 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
6278
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006279 task->context = hlua;
6280 task->process = hlua_process_task;
6281
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006282 if (!hlua_ctx_init(hlua, task, 1))
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006283 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006284
6285 /* Restore the function in the stack. */
6286 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
6287 hlua->nargs = 0;
6288
6289 /* Schedule task. */
6290 task_schedule(task, now_ms);
6291
6292 return 0;
6293}
6294
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006295/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
6296 * doesn't allow "yield" functions because the HAProxy engine cannot
6297 * resume converters.
6298 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006299static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006300{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006301 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006302 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006303 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006304
Willy Tarreaube508f12016-03-10 11:47:01 +01006305 if (!stream)
6306 return 0;
6307
Willy Tarreau87b09662015-04-03 00:22:06 +02006308 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006309 * Lua context can be not initialized. This behavior
6310 * permits to save performances because a systematic
6311 * Lua initialization cause 5% performances loss.
6312 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006313 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006314 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006315 if (!stream->hlua) {
6316 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6317 return 0;
6318 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006319 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006320 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6321 return 0;
6322 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006323 }
6324
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006325 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006326 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006327
6328 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006329 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6330 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6331 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006332 else
6333 error = "critical error";
6334 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006335 return 0;
6336 }
6337
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006338 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006339 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006340 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006341 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006342 return 0;
6343 }
6344
6345 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006346 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006347
6348 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006349 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006350 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006351 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006352 return 0;
6353 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006354 hlua_smp2lua(stream->hlua->T, smp);
6355 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006356
6357 /* push keywords in the stack. */
6358 if (arg_p) {
6359 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006360 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006361 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006362 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006363 return 0;
6364 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006365 hlua_arg2lua(stream->hlua->T, arg_p);
6366 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006367 }
6368 }
6369
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006370 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006371 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006372
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006373 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006374 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006375 }
6376
6377 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006378 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006379 /* finished. */
6380 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006381 /* If the stack is empty, the function fails. */
6382 if (lua_gettop(stream->hlua->T) <= 0)
6383 return 0;
6384
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006385 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006386 hlua_lua2smp(stream->hlua->T, -1, smp);
6387 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006388 return 1;
6389
6390 /* yield. */
6391 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006392 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006393 return 0;
6394
6395 /* finished with error. */
6396 case HLUA_E_ERRMSG:
6397 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006398 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006399 fcn->name, lua_tostring(stream->hlua->T, -1));
6400 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006401 return 0;
6402
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006403 case HLUA_E_ETMOUT:
6404 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
6405 return 0;
6406
6407 case HLUA_E_NOMEM:
6408 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
6409 return 0;
6410
6411 case HLUA_E_YIELD:
6412 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
6413 return 0;
6414
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006415 case HLUA_E_ERR:
6416 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006417 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02006418 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006419
6420 default:
6421 return 0;
6422 }
6423}
6424
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006425/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
6426 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01006427 * resume sample-fetches. This function will be called by the sample
6428 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006429 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02006430static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
6431 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006432{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006433 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006434 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006435 const char *error;
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006436 unsigned int hflags = HLUA_TXN_NOTERM;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006437
Willy Tarreaube508f12016-03-10 11:47:01 +01006438 if (!stream)
6439 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01006440
Willy Tarreau87b09662015-04-03 00:22:06 +02006441 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006442 * Lua context can be not initialized. This behavior
6443 * permits to save performances because a systematic
6444 * Lua initialization cause 5% performances loss.
6445 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006446 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006447 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006448 if (!stream->hlua) {
6449 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6450 return 0;
6451 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006452 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006453 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6454 return 0;
6455 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006456 }
6457
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006458 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006459 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006460
6461 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006462 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6463 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6464 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006465 else
6466 error = "critical error";
6467 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006468 return 0;
6469 }
6470
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006471 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006472 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006473 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006474 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006475 return 0;
6476 }
6477
6478 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006479 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006480
6481 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006482 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006483 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006484 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006485 return 0;
6486 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006487 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006488
6489 /* push keywords in the stack. */
6490 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
6491 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006492 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006493 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006494 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006495 return 0;
6496 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006497 hlua_arg2lua(stream->hlua->T, arg_p);
6498 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006499 }
6500
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006501 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006502 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006503
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006504 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006505 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006506 }
6507
6508 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006509 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006510 /* finished. */
6511 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006512 /* If the stack is empty, the function fails. */
6513 if (lua_gettop(stream->hlua->T) <= 0)
6514 return 0;
6515
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006516 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006517 hlua_lua2smp(stream->hlua->T, -1, smp);
6518 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006519
6520 /* Set the end of execution flag. */
6521 smp->flags &= ~SMP_F_MAY_CHANGE;
6522 return 1;
6523
6524 /* yield. */
6525 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006526 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006527 return 0;
6528
6529 /* finished with error. */
6530 case HLUA_E_ERRMSG:
6531 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006532 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006533 fcn->name, lua_tostring(stream->hlua->T, -1));
6534 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006535 return 0;
6536
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006537 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006538 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
6539 return 0;
6540
6541 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006542 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
6543 return 0;
6544
6545 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006546 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
6547 return 0;
6548
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006549 case HLUA_E_ERR:
6550 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006551 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02006552 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006553
6554 default:
6555 return 0;
6556 }
6557}
6558
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006559/* This function is an LUA binding used for registering
6560 * "sample-conv" functions. It expects a converter name used
6561 * in the haproxy configuration file, and an LUA function.
6562 */
6563__LJMP static int hlua_register_converters(lua_State *L)
6564{
6565 struct sample_conv_kw_list *sck;
6566 const char *name;
6567 int ref;
6568 int len;
6569 struct hlua_function *fcn;
6570
6571 MAY_LJMP(check_args(L, 2, "register_converters"));
6572
6573 /* First argument : converter name. */
6574 name = MAY_LJMP(luaL_checkstring(L, 1));
6575
6576 /* Second argument : lua function. */
6577 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6578
6579 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006580 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006581 if (!sck)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006582 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006583 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006584 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006585 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006586
6587 /* Fill fcn. */
6588 fcn->name = strdup(name);
6589 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006590 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006591 fcn->function_ref = ref;
6592
6593 /* List head */
6594 sck->list.n = sck->list.p = NULL;
6595
6596 /* converter keyword. */
6597 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006598 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006599 if (!sck->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006600 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006601
6602 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
6603 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006604 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 +01006605 sck->kw[0].val_args = NULL;
6606 sck->kw[0].in_type = SMP_T_STR;
6607 sck->kw[0].out_type = SMP_T_STR;
6608 sck->kw[0].private = fcn;
6609
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006610 /* Register this new converter */
6611 sample_register_convs(sck);
6612
6613 return 0;
6614}
6615
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006616/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006617 * "sample-fetch" functions. It expects a converter name used
6618 * in the haproxy configuration file, and an LUA function.
6619 */
6620__LJMP static int hlua_register_fetches(lua_State *L)
6621{
6622 const char *name;
6623 int ref;
6624 int len;
6625 struct sample_fetch_kw_list *sfk;
6626 struct hlua_function *fcn;
6627
6628 MAY_LJMP(check_args(L, 2, "register_fetches"));
6629
6630 /* First argument : sample-fetch name. */
6631 name = MAY_LJMP(luaL_checkstring(L, 1));
6632
6633 /* Second argument : lua function. */
6634 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6635
6636 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006637 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006638 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006639 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006640 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006641 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006642 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006643
6644 /* Fill fcn. */
6645 fcn->name = strdup(name);
6646 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006647 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006648 fcn->function_ref = ref;
6649
6650 /* List head */
6651 sfk->list.n = sfk->list.p = NULL;
6652
6653 /* sample-fetch keyword. */
6654 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006655 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006656 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006657 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006658
6659 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
6660 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006661 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 +01006662 sfk->kw[0].val_args = NULL;
6663 sfk->kw[0].out_type = SMP_T_STR;
6664 sfk->kw[0].use = SMP_USE_HTTP_ANY;
6665 sfk->kw[0].val = 0;
6666 sfk->kw[0].private = fcn;
6667
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006668 /* Register this new fetch. */
6669 sample_register_fetches(sfk);
6670
6671 return 0;
6672}
6673
Christopher Faulet501465d2020-02-26 14:54:16 +01006674/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01006675 */
Christopher Faulet501465d2020-02-26 14:54:16 +01006676__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01006677{
6678 struct hlua *hlua = hlua_gethlua(L);
6679 unsigned int delay;
6680 unsigned int wakeup_ms;
6681
6682 MAY_LJMP(check_args(L, 1, "wake_time"));
6683
6684 delay = MAY_LJMP(luaL_checkinteger(L, 1));
6685 wakeup_ms = tick_add(now_ms, delay);
6686 hlua->wake_time = wakeup_ms;
6687 return 0;
6688}
6689
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006690/* This function is a wrapper to execute each LUA function declared as an action
6691 * wrapper during the initialisation period. This function may return any
6692 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
6693 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
6694 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006695 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006696static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006697 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006698{
6699 char **arg;
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006700 unsigned int hflags = 0;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006701 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006702 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006703
6704 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006705 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
6706 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
6707 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
6708 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006709 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006710 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006711 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006712 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006713
Willy Tarreau87b09662015-04-03 00:22:06 +02006714 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006715 * Lua context can be not initialized. This behavior
6716 * permits to save performances because a systematic
6717 * Lua initialization cause 5% performances loss.
6718 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006719 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006720 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006721 if (!s->hlua) {
6722 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6723 rule->arg.hlua_rule->fcn.name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006724 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006725 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006726 if (!hlua_ctx_init(s->hlua, s->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006727 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6728 rule->arg.hlua_rule->fcn.name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006729 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006730 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006731 }
6732
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006733 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006734 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006735
6736 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006737 if (!SET_SAFE_LJMP(s->hlua->T)) {
6738 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6739 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006740 else
6741 error = "critical error";
6742 SEND_ERR(px, "Lua function '%s': %s.\n",
6743 rule->arg.hlua_rule->fcn.name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006744 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006745 }
6746
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006747 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006748 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006749 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006750 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006751 RESET_SAFE_LJMP(s->hlua->T);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006752 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006753 }
6754
6755 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006756 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006757
Willy Tarreau87b09662015-04-03 00:22:06 +02006758 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006759 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006760 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006761 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006762 RESET_SAFE_LJMP(s->hlua->T);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006763 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006764 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006765 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006766
6767 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006768 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006769 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006770 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006771 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006772 RESET_SAFE_LJMP(s->hlua->T);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006773 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006774 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006775 lua_pushstring(s->hlua->T, *arg);
6776 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006777 }
6778
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006779 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006780 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006781
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006782 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006783 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006784 }
6785
6786 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01006787 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006788 /* finished. */
6789 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006790 /* Catch the return value */
6791 if (lua_gettop(s->hlua->T) > 0)
6792 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006793
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01006794 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02006795 if (act_ret == ACT_RET_YIELD) {
6796 if (flags & ACT_OPT_FINAL)
6797 goto err_yield;
6798
Christopher Faulet8f587ea2020-07-28 12:01:55 +02006799 if (dir == SMP_OPT_DIR_REQ)
6800 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
6801 s->hlua->wake_time);
6802 else
6803 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
6804 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01006805 }
6806 goto end;
6807
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006808 /* yield. */
6809 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006810 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02006811 if (dir == SMP_OPT_DIR_REQ)
6812 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
6813 s->hlua->wake_time);
6814 else
6815 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
6816 s->hlua->wake_time);
6817
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006818 /* Some actions can be wake up when a "write" event
6819 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006820 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006821 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02006822 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006823 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006824 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006825 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006826 act_ret = ACT_RET_YIELD;
6827 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006828
6829 /* finished with error. */
6830 case HLUA_E_ERRMSG:
6831 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006832 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006833 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6834 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006835 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006836
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006837 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006838 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn.name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006839 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006840
6841 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006842 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn.name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006843 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006844
6845 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02006846 err_yield:
6847 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006848 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
6849 rule->arg.hlua_rule->fcn.name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006850 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006851
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006852 case HLUA_E_ERR:
6853 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006854 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006855 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006856
6857 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006858 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006859 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006860
6861 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02006862 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02006863 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006864 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006865}
6866
Olivier Houchard9f6af332018-05-25 14:04:04 +02006867struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned short state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006868{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006869 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006870
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006871 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006872 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006873 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006874}
6875
6876static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6877{
6878 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006879 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006880 struct task *task;
6881 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006882 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006883
Willy Tarreaubafbe012017-11-24 17:34:44 +01006884 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006885 if (!hlua) {
6886 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6887 ctx->rule->arg.hlua_rule->fcn.name);
6888 return 0;
6889 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006890 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006891 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006892 ctx->ctx.hlua_apptcp.flags = 0;
6893
6894 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006895 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006896 if (!task) {
6897 SEND_ERR(px, "Lua applet tcp '%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_apptcp.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 FOURNIERf0a64b62015-09-19 12:36:17 +02006912 SEND_ERR(px, "Lua applet tcp '%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 FOURNIERf0a64b62015-09-19 12:36:17 +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 tcp '%s': %s.\n",
6927 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006928 return 0;
6929 }
6930
6931 /* Check stack available size. */
6932 if (!lua_checkstack(hlua->T, 1)) {
6933 SEND_ERR(px, "Lua applet tcp '%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_tcp_new(hlua->T, ctx)) {
6944 SEND_ERR(px, "Lua applet tcp '%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
6951 /* 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 tcp '%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 ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01006966 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01006967 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006968
6969 return 1;
6970}
6971
Willy Tarreau60409db2019-08-21 14:14:50 +02006972void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006973{
6974 struct stream_interface *si = ctx->owner;
6975 struct stream *strm = si_strm(si);
6976 struct channel *res = si_ic(si);
6977 struct act_rule *rule = ctx->rule;
6978 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006979 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006980
6981 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02006982 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
6983 /* eat the whole request */
6984 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006985 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02006986 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006987
6988 /* If the stream is disconnect or closed, ldo nothing. */
6989 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6990 return;
6991
6992 /* Execute the function. */
6993 switch (hlua_ctx_resume(hlua, 1)) {
6994 /* finished. */
6995 case HLUA_E_OK:
6996 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6997
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006998 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02006999 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007000 res->flags |= CF_READ_NULL;
7001 si_shutr(si);
7002 return;
7003
7004 /* yield. */
7005 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01007006 if (hlua->wake_time != TICK_ETERNITY)
7007 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007008 return;
7009
7010 /* finished with error. */
7011 case HLUA_E_ERRMSG:
7012 /* Display log. */
7013 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
7014 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7015 lua_pop(hlua->T, 1);
7016 goto error;
7017
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007018 case HLUA_E_ETMOUT:
7019 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
7020 rule->arg.hlua_rule->fcn.name);
7021 goto error;
7022
7023 case HLUA_E_NOMEM:
7024 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
7025 rule->arg.hlua_rule->fcn.name);
7026 goto error;
7027
7028 case HLUA_E_YIELD: /* unexpected */
7029 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
7030 rule->arg.hlua_rule->fcn.name);
7031 goto error;
7032
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007033 case HLUA_E_ERR:
7034 /* Display log. */
7035 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
7036 rule->arg.hlua_rule->fcn.name);
7037 goto error;
7038
7039 default:
7040 goto error;
7041 }
7042
7043error:
7044
7045 /* For all other cases, just close the stream. */
7046 si_shutw(si);
7047 si_shutr(si);
7048 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7049}
7050
7051static void hlua_applet_tcp_release(struct appctx *ctx)
7052{
Olivier Houchard3f795f72019-04-17 22:51:06 +02007053 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007054 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007055 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007056 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007057}
7058
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007059/* The function returns 1 if the initialisation is complete, 0 if
7060 * an errors occurs and -1 if more data are required for initializing
7061 * the applet.
7062 */
7063static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
7064{
7065 struct stream_interface *si = ctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007066 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007067 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007068 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007069 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007070 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007071
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007072 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01007073 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007074 if (!hlua) {
7075 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
7076 ctx->rule->arg.hlua_rule->fcn.name);
7077 return 0;
7078 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007079 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007080 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007081 ctx->ctx.hlua_apphttp.left_bytes = -1;
7082 ctx->ctx.hlua_apphttp.flags = 0;
7083
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01007084 if (txn->req.flags & HTTP_MSGF_VER_11)
7085 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
7086
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007087 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007088 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007089 if (!task) {
7090 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
7091 ctx->rule->arg.hlua_rule->fcn.name);
7092 return 0;
7093 }
7094 task->nice = 0;
7095 task->context = ctx;
7096 task->process = hlua_applet_wakeup;
7097 ctx->ctx.hlua_apphttp.task = task;
7098
7099 /* In the execution wrappers linked with a stream, the
7100 * Lua context can be not initialized. This behavior
7101 * permits to save performances because a systematic
7102 * Lua initialization cause 5% performances loss.
7103 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007104 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007105 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
7106 ctx->rule->arg.hlua_rule->fcn.name);
7107 return 0;
7108 }
7109
7110 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007111 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007112
7113 /* The following Lua calls can fail. */
7114 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007115 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7116 error = lua_tostring(hlua->T, -1);
7117 else
7118 error = "critical error";
7119 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7120 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007121 return 0;
7122 }
7123
7124 /* Check stack available size. */
7125 if (!lua_checkstack(hlua->T, 1)) {
7126 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7127 ctx->rule->arg.hlua_rule->fcn.name);
7128 RESET_SAFE_LJMP(hlua->T);
7129 return 0;
7130 }
7131
7132 /* Restore the function in the stack. */
7133 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
7134
7135 /* Create and and push object stream in the stack. */
7136 if (!hlua_applet_http_new(hlua->T, ctx)) {
7137 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7138 ctx->rule->arg.hlua_rule->fcn.name);
7139 RESET_SAFE_LJMP(hlua->T);
7140 return 0;
7141 }
7142 hlua->nargs = 1;
7143
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007144 /* push keywords in the stack. */
7145 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7146 if (!lua_checkstack(hlua->T, 1)) {
7147 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7148 ctx->rule->arg.hlua_rule->fcn.name);
7149 RESET_SAFE_LJMP(hlua->T);
7150 return 0;
7151 }
7152 lua_pushstring(hlua->T, *arg);
7153 hlua->nargs++;
7154 }
7155
7156 RESET_SAFE_LJMP(hlua->T);
7157
7158 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007159 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007160
7161 return 1;
7162}
7163
Willy Tarreau60409db2019-08-21 14:14:50 +02007164void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007165{
7166 struct stream_interface *si = ctx->owner;
7167 struct stream *strm = si_strm(si);
7168 struct channel *req = si_oc(si);
7169 struct channel *res = si_ic(si);
7170 struct act_rule *rule = ctx->rule;
7171 struct proxy *px = strm->be;
7172 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
7173 struct htx *req_htx, *res_htx;
7174
7175 res_htx = htx_from_buf(&res->buf);
7176
7177 /* If the stream is disconnect or closed, ldo nothing. */
7178 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7179 goto out;
7180
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007181 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007182 if (!b_size(&res->buf)) {
7183 si_rx_room_blk(si);
7184 goto out;
7185 }
7186 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007187 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007188 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7189
7190 /* Set the currently running flag. */
7191 if (!HLUA_IS_RUNNING(hlua) &&
7192 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7193 struct htx_blk *blk;
7194 size_t count = co_data(req);
7195
7196 if (!count) {
7197 si_cant_get(si);
7198 goto out;
7199 }
7200
7201 /* We need to flush the request header. This left the body for
7202 * the Lua.
7203 */
7204 req_htx = htx_from_buf(&req->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02007205 blk = htx_get_first_blk(req_htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007206 while (count && blk) {
7207 enum htx_blk_type type = htx_get_blk_type(blk);
7208 uint32_t sz = htx_get_blksz(blk);
7209
7210 if (sz > count) {
7211 si_cant_get(si);
Christopher Faulet0ae79d02019-02-27 21:36:59 +01007212 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007213 goto out;
7214 }
7215
7216 count -= sz;
7217 co_set_data(req, co_data(req) - sz);
7218 blk = htx_remove_blk(req_htx, blk);
7219
7220 if (type == HTX_BLK_EOH)
7221 break;
7222 }
Christopher Faulet0ae79d02019-02-27 21:36:59 +01007223 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007224 }
7225
7226 /* Executes The applet if it is not done. */
7227 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7228
7229 /* Execute the function. */
7230 switch (hlua_ctx_resume(hlua, 1)) {
7231 /* finished. */
7232 case HLUA_E_OK:
7233 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7234 break;
7235
7236 /* yield. */
7237 case HLUA_E_AGAIN:
7238 if (hlua->wake_time != TICK_ETERNITY)
7239 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007240 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007241
7242 /* finished with error. */
7243 case HLUA_E_ERRMSG:
7244 /* Display log. */
7245 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7246 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7247 lua_pop(hlua->T, 1);
7248 goto error;
7249
7250 case HLUA_E_ETMOUT:
7251 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
7252 rule->arg.hlua_rule->fcn.name);
7253 goto error;
7254
7255 case HLUA_E_NOMEM:
7256 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
7257 rule->arg.hlua_rule->fcn.name);
7258 goto error;
7259
7260 case HLUA_E_YIELD: /* unexpected */
7261 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
7262 rule->arg.hlua_rule->fcn.name);
7263 goto error;
7264
7265 case HLUA_E_ERR:
7266 /* Display log. */
7267 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
7268 rule->arg.hlua_rule->fcn.name);
7269 goto error;
7270
7271 default:
7272 goto error;
7273 }
7274 }
7275
7276 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007277 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
7278 goto done;
7279
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007280 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7281 goto error;
7282
Christopher Faulet54b5e212019-06-04 10:08:28 +02007283 /* Don't add TLR because mux-h1 will take care of it */
Willy Tarreauf1ea47d2020-07-23 06:53:27 +02007284 res_htx->flags |= HTX_FL_EOI; /* no more data are expected. Only EOM remains to add now */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007285 if (!htx_add_endof(res_htx, HTX_BLK_EOM)) {
7286 si_rx_room_blk(si);
7287 goto out;
7288 }
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007289 channel_add_input(res, 1);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007290 strm->txn->status = ctx->ctx.hlua_apphttp.status;
7291 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007292 }
7293
7294 done:
7295 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007296 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007297 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007298 si_shutr(si);
7299 }
7300
7301 /* eat the whole request */
7302 if (co_data(req)) {
7303 req_htx = htx_from_buf(&req->buf);
7304 co_htx_skip(req, req_htx, co_data(req));
7305 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007306 }
7307 }
7308
7309 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007310 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007311 return;
7312
7313 error:
7314
7315 /* If we are in HTTP mode, and we are not send any
7316 * data, return a 500 server error in best effort:
7317 * if there is no room available in the buffer,
7318 * just close the connection.
7319 */
7320 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02007321 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007322
7323 channel_erase(res);
7324 res->buf.data = b_data(err);
7325 memcpy(res->buf.area, b_head(err), b_data(err));
7326 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007327 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007328 }
7329 if (!(strm->flags & SF_ERR_MASK))
7330 strm->flags |= SF_ERR_RESOURCE;
7331 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7332 goto done;
7333}
7334
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007335static void hlua_applet_http_release(struct appctx *ctx)
7336{
Olivier Houchard3f795f72019-04-17 22:51:06 +02007337 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007338 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007339 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007340 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007341}
7342
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007343/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007344 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007345 *
7346 * This function can fail with an abort() due to an Lua critical error.
7347 * We are in the configuration parsing process of HAProxy, this abort() is
7348 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007349 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007350static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
7351 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007352{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007353 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007354 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007355
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007356 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007357 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007358 if (!rule->arg.hlua_rule) {
7359 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007360 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007361 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007362
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007363 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02007364 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
7365 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007366 if (!rule->arg.hlua_rule->args) {
7367 memprintf(err, "out of memory error");
7368 return ACT_RET_PRS_ERR;
7369 }
7370
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007371 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007372 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007373
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007374 /* Expect some arguments */
7375 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007376 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007377 memprintf(err, "expect %d arguments", fcn->nargs);
7378 return ACT_RET_PRS_ERR;
7379 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007380 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007381 if (!rule->arg.hlua_rule->args[i]) {
7382 memprintf(err, "out of memory error");
7383 return ACT_RET_PRS_ERR;
7384 }
7385 (*cur_arg)++;
7386 }
7387 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007388
Thierry FOURNIER42148732015-09-02 17:17:33 +02007389 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007390 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007391 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007392}
7393
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007394static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
7395 struct act_rule *rule, char **err)
7396{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007397 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007398
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007399 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007400 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007401 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007402 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007403 * the call of this analyzer.
7404 */
7405 if (rule->from != ACT_F_HTTP_REQ) {
7406 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
7407 return ACT_RET_PRS_ERR;
7408 }
7409
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007410 /* Memory for the rule. */
7411 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7412 if (!rule->arg.hlua_rule) {
7413 memprintf(err, "out of memory error");
7414 return ACT_RET_PRS_ERR;
7415 }
7416
7417 /* Reference the Lua function and store the reference. */
7418 rule->arg.hlua_rule->fcn = *fcn;
7419
7420 /* TODO: later accept arguments. */
7421 rule->arg.hlua_rule->args = NULL;
7422
7423 /* Add applet pointer in the rule. */
7424 rule->applet.obj_type = OBJ_TYPE_APPLET;
7425 rule->applet.name = fcn->name;
7426 rule->applet.init = hlua_applet_http_init;
7427 rule->applet.fct = hlua_applet_http_fct;
7428 rule->applet.release = hlua_applet_http_release;
7429 rule->applet.timeout = hlua_timeout_applet;
7430
7431 return ACT_RET_PRS_OK;
7432}
7433
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007434/* This function is an LUA binding used for registering
7435 * "sample-conv" functions. It expects a converter name used
7436 * in the haproxy configuration file, and an LUA function.
7437 */
7438__LJMP static int hlua_register_action(lua_State *L)
7439{
7440 struct action_kw_list *akl;
7441 const char *name;
7442 int ref;
7443 int len;
7444 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007445 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007446
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007447 /* Initialise the number of expected arguments at 0. */
7448 nargs = 0;
7449
7450 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7451 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007452
7453 /* First argument : converter name. */
7454 name = MAY_LJMP(luaL_checkstring(L, 1));
7455
7456 /* Second argument : environment. */
7457 if (lua_type(L, 2) != LUA_TTABLE)
7458 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7459
7460 /* Third argument : lua function. */
7461 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7462
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007463 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007464 if (lua_gettop(L) >= 4)
7465 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
7466
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007467 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007468 lua_pushnil(L);
7469 while (lua_next(L, 2) != 0) {
7470 if (lua_type(L, -1) != LUA_TSTRING)
7471 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7472
7473 /* Check required environment. Only accepted "http" or "tcp". */
7474 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007475 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007476 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007477 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007478 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007479 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007480 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007481
7482 /* Fill fcn. */
7483 fcn->name = strdup(name);
7484 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007485 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007486 fcn->function_ref = ref;
7487
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007488 /* Set the expected number od arguments. */
7489 fcn->nargs = nargs;
7490
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007491 /* List head */
7492 akl->list.n = akl->list.p = NULL;
7493
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007494 /* action keyword. */
7495 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007496 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007497 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007498 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007499
7500 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7501
7502 akl->kw[0].match_pfx = 0;
7503 akl->kw[0].private = fcn;
7504 akl->kw[0].parse = action_register_lua;
7505
7506 /* select the action registering point. */
7507 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
7508 tcp_req_cont_keywords_register(akl);
7509 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
7510 tcp_res_cont_keywords_register(akl);
7511 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
7512 http_req_keywords_register(akl);
7513 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
7514 http_res_keywords_register(akl);
7515 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007516 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007517 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
7518 "are expected.", lua_tostring(L, -1)));
7519
7520 /* pop the environment string. */
7521 lua_pop(L, 1);
7522 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007523 return ACT_RET_PRS_OK;
7524}
7525
7526static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
7527 struct act_rule *rule, char **err)
7528{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007529 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007530
Christopher Faulet280f85b2019-07-15 15:02:04 +02007531 if (px->mode == PR_MODE_HTTP) {
7532 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01007533 return ACT_RET_PRS_ERR;
7534 }
7535
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007536 /* Memory for the rule. */
7537 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7538 if (!rule->arg.hlua_rule) {
7539 memprintf(err, "out of memory error");
7540 return ACT_RET_PRS_ERR;
7541 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007542
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007543 /* Reference the Lua function and store the reference. */
7544 rule->arg.hlua_rule->fcn = *fcn;
7545
7546 /* TODO: later accept arguments. */
7547 rule->arg.hlua_rule->args = NULL;
7548
7549 /* Add applet pointer in the rule. */
7550 rule->applet.obj_type = OBJ_TYPE_APPLET;
7551 rule->applet.name = fcn->name;
7552 rule->applet.init = hlua_applet_tcp_init;
7553 rule->applet.fct = hlua_applet_tcp_fct;
7554 rule->applet.release = hlua_applet_tcp_release;
7555 rule->applet.timeout = hlua_timeout_applet;
7556
7557 return 0;
7558}
7559
7560/* This function is an LUA binding used for registering
7561 * "sample-conv" functions. It expects a converter name used
7562 * in the haproxy configuration file, and an LUA function.
7563 */
7564__LJMP static int hlua_register_service(lua_State *L)
7565{
7566 struct action_kw_list *akl;
7567 const char *name;
7568 const char *env;
7569 int ref;
7570 int len;
7571 struct hlua_function *fcn;
7572
7573 MAY_LJMP(check_args(L, 3, "register_service"));
7574
7575 /* First argument : converter name. */
7576 name = MAY_LJMP(luaL_checkstring(L, 1));
7577
7578 /* Second argument : environment. */
7579 env = MAY_LJMP(luaL_checkstring(L, 2));
7580
7581 /* Third argument : lua function. */
7582 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7583
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007584 /* Allocate and fill the sample fetch keyword struct. */
7585 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
7586 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007587 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007588 fcn = calloc(1, sizeof(*fcn));
7589 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007590 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007591
7592 /* Fill fcn. */
7593 len = strlen("<lua.>") + strlen(name) + 1;
7594 fcn->name = calloc(1, len);
7595 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007596 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007597 snprintf((char *)fcn->name, len, "<lua.%s>", name);
7598 fcn->function_ref = ref;
7599
7600 /* List head */
7601 akl->list.n = akl->list.p = NULL;
7602
7603 /* converter keyword. */
7604 len = strlen("lua.") + strlen(name) + 1;
7605 akl->kw[0].kw = calloc(1, len);
7606 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007607 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007608
7609 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7610
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01007611 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007612 if (strcmp(env, "tcp") == 0)
7613 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007614 else if (strcmp(env, "http") == 0)
7615 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007616 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007617 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01007618 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007619
7620 akl->kw[0].match_pfx = 0;
7621 akl->kw[0].private = fcn;
7622
7623 /* End of array. */
7624 memset(&akl->kw[1], 0, sizeof(*akl->kw));
7625
7626 /* Register this new converter */
7627 service_keywords_register(akl);
7628
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007629 return 0;
7630}
7631
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007632/* This function initialises Lua cli handler. It copies the
7633 * arguments in the Lua stack and create channel IO objects.
7634 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007635static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007636{
7637 struct hlua *hlua;
7638 struct hlua_function *fcn;
7639 int i;
7640 const char *error;
7641
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007642 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007643 appctx->ctx.hlua_cli.fcn = private;
7644
Willy Tarreaubafbe012017-11-24 17:34:44 +01007645 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007646 if (!hlua) {
7647 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007648 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007649 }
7650 HLUA_INIT(hlua);
7651 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007652
7653 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +05007654 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007655 * applet_http. It is absolutely compatible.
7656 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007657 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007658 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01007659 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007660 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007661 }
7662 appctx->ctx.hlua_cli.task->nice = 0;
7663 appctx->ctx.hlua_cli.task->context = appctx;
7664 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
7665
7666 /* Initialises the Lua context */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007667 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007668 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007669 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007670 }
7671
7672 /* The following Lua calls can fail. */
7673 if (!SET_SAFE_LJMP(hlua->T)) {
7674 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7675 error = lua_tostring(hlua->T, -1);
7676 else
7677 error = "critical error";
7678 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
7679 goto error;
7680 }
7681
7682 /* Check stack available size. */
7683 if (!lua_checkstack(hlua->T, 2)) {
7684 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7685 goto error;
7686 }
7687
7688 /* Restore the function in the stack. */
7689 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
7690
7691 /* Once the arguments parsed, the CLI is like an AppletTCP,
7692 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007693 */
7694 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
7695 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7696 goto error;
7697 }
7698 hlua->nargs = 1;
7699
7700 /* push keywords in the stack. */
7701 for (i = 0; *args[i]; i++) {
7702 /* Check stack available size. */
7703 if (!lua_checkstack(hlua->T, 1)) {
7704 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7705 goto error;
7706 }
7707 lua_pushstring(hlua->T, args[i]);
7708 hlua->nargs++;
7709 }
7710
7711 /* We must initialize the execution timeouts. */
7712 hlua->max_time = hlua_timeout_session;
7713
7714 /* At this point the execution is safe. */
7715 RESET_SAFE_LJMP(hlua->T);
7716
7717 /* It's ok */
7718 return 0;
7719
7720 /* It's not ok. */
7721error:
7722 RESET_SAFE_LJMP(hlua->T);
7723 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007724 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007725 return 1;
7726}
7727
7728static int hlua_cli_io_handler_fct(struct appctx *appctx)
7729{
7730 struct hlua *hlua;
7731 struct stream_interface *si;
7732 struct hlua_function *fcn;
7733
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007734 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007735 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01007736 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007737
7738 /* If the stream is disconnect or closed, ldo nothing. */
7739 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7740 return 1;
7741
7742 /* Execute the function. */
7743 switch (hlua_ctx_resume(hlua, 1)) {
7744
7745 /* finished. */
7746 case HLUA_E_OK:
7747 return 1;
7748
7749 /* yield. */
7750 case HLUA_E_AGAIN:
7751 /* We want write. */
7752 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01007753 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007754 /* Set the timeout. */
7755 if (hlua->wake_time != TICK_ETERNITY)
7756 task_schedule(hlua->task, hlua->wake_time);
7757 return 0;
7758
7759 /* finished with error. */
7760 case HLUA_E_ERRMSG:
7761 /* Display log. */
7762 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
7763 fcn->name, lua_tostring(hlua->T, -1));
7764 lua_pop(hlua->T, 1);
7765 return 1;
7766
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007767 case HLUA_E_ETMOUT:
7768 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
7769 fcn->name);
7770 return 1;
7771
7772 case HLUA_E_NOMEM:
7773 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
7774 fcn->name);
7775 return 1;
7776
7777 case HLUA_E_YIELD: /* unexpected */
7778 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
7779 fcn->name);
7780 return 1;
7781
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007782 case HLUA_E_ERR:
7783 /* Display log. */
7784 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
7785 fcn->name);
7786 return 1;
7787
7788 default:
7789 return 1;
7790 }
7791
7792 return 1;
7793}
7794
7795static void hlua_cli_io_release_fct(struct appctx *appctx)
7796{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007797 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007798 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007799}
7800
7801/* This function is an LUA binding used for registering
7802 * new keywords in the cli. It expects a list of keywords
7803 * which are the "path". It is limited to 5 keywords. A
7804 * description of the command, a function to be executed
7805 * for the parsing and a function for io handlers.
7806 */
7807__LJMP static int hlua_register_cli(lua_State *L)
7808{
7809 struct cli_kw_list *cli_kws;
7810 const char *message;
7811 int ref_io;
7812 int len;
7813 struct hlua_function *fcn;
7814 int index;
7815 int i;
7816
7817 MAY_LJMP(check_args(L, 3, "register_cli"));
7818
7819 /* First argument : an array of maximum 5 keywords. */
7820 if (!lua_istable(L, 1))
7821 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
7822
7823 /* Second argument : string with contextual message. */
7824 message = MAY_LJMP(luaL_checkstring(L, 2));
7825
7826 /* Third and fourth argument : lua function. */
7827 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
7828
7829 /* Allocate and fill the sample fetch keyword struct. */
7830 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
7831 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007832 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007833 fcn = calloc(1, sizeof(*fcn));
7834 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007835 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007836
7837 /* Fill path. */
7838 index = 0;
7839 lua_pushnil(L);
7840 while(lua_next(L, 1) != 0) {
7841 if (index >= 5)
7842 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
7843 if (lua_type(L, -1) != LUA_TSTRING)
7844 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
7845 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
7846 if (!cli_kws->kw[0].str_kw[index])
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007847 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007848 index++;
7849 lua_pop(L, 1);
7850 }
7851
7852 /* Copy help message. */
7853 cli_kws->kw[0].usage = strdup(message);
7854 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007855 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007856
7857 /* Fill fcn io handler. */
7858 len = strlen("<lua.cli>") + 1;
7859 for (i = 0; i < index; i++)
7860 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
7861 fcn->name = calloc(1, len);
7862 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007863 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007864 strncat((char *)fcn->name, "<lua.cli", len);
7865 for (i = 0; i < index; i++) {
7866 strncat((char *)fcn->name, ".", len);
7867 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
7868 }
7869 strncat((char *)fcn->name, ">", len);
7870 fcn->function_ref = ref_io;
7871
7872 /* Fill last entries. */
7873 cli_kws->kw[0].private = fcn;
7874 cli_kws->kw[0].parse = hlua_cli_parse_fct;
7875 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
7876 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
7877
7878 /* Register this new converter */
7879 cli_register_kw(cli_kws);
7880
7881 return 0;
7882}
7883
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007884static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
7885 struct proxy *defpx, const char *file, int line,
7886 char **err, unsigned int *timeout)
7887{
7888 const char *error;
7889
7890 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +02007891 if (error == PARSE_TIME_OVER) {
7892 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
7893 args[1], args[0]);
7894 return -1;
7895 }
7896 else if (error == PARSE_TIME_UNDER) {
7897 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
7898 args[1], args[0]);
7899 return -1;
7900 }
7901 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007902 memprintf(err, "%s: invalid timeout", args[0]);
7903 return -1;
7904 }
7905 return 0;
7906}
7907
7908static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
7909 struct proxy *defpx, const char *file, int line,
7910 char **err)
7911{
7912 return hlua_read_timeout(args, section_type, curpx, defpx,
7913 file, line, err, &hlua_timeout_session);
7914}
7915
7916static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
7917 struct proxy *defpx, const char *file, int line,
7918 char **err)
7919{
7920 return hlua_read_timeout(args, section_type, curpx, defpx,
7921 file, line, err, &hlua_timeout_task);
7922}
7923
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007924static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
7925 struct proxy *defpx, const char *file, int line,
7926 char **err)
7927{
7928 return hlua_read_timeout(args, section_type, curpx, defpx,
7929 file, line, err, &hlua_timeout_applet);
7930}
7931
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007932static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
7933 struct proxy *defpx, const char *file, int line,
7934 char **err)
7935{
7936 char *error;
7937
7938 hlua_nb_instruction = strtoll(args[1], &error, 10);
7939 if (*error != '\0') {
7940 memprintf(err, "%s: invalid number", args[0]);
7941 return -1;
7942 }
7943 return 0;
7944}
7945
Willy Tarreau32f61e22015-03-18 17:54:59 +01007946static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
7947 struct proxy *defpx, const char *file, int line,
7948 char **err)
7949{
7950 char *error;
7951
7952 if (*(args[1]) == 0) {
7953 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
7954 return -1;
7955 }
7956 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
7957 if (*error != '\0') {
7958 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
7959 return -1;
7960 }
7961 return 0;
7962}
7963
7964
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007965/* This function is called by the main configuration key "lua-load". It loads and
7966 * execute an lua file during the parsing of the HAProxy configuration file. It is
7967 * the main lua entry point.
7968 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007969 * This function runs with the HAProxy keywords API. It returns -1 if an error
7970 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007971 *
7972 * In some error case, LUA set an error message in top of the stack. This function
7973 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007974 *
7975 * This function can fail with an abort() due to an Lua critical error.
7976 * We are in the configuration parsing process of HAProxy, this abort() is
7977 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007978 */
7979static int hlua_load(char **args, int section_type, struct proxy *curpx,
7980 struct proxy *defpx, const char *file, int line,
7981 char **err)
7982{
7983 int error;
7984
7985 /* Just load and compile the file. */
7986 error = luaL_loadfile(gL.T, args[1]);
7987 if (error) {
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007988 memprintf(err, "error in Lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007989 lua_pop(gL.T, 1);
7990 return -1;
7991 }
7992
7993 /* If no syntax error where detected, execute the code. */
7994 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
7995 switch (error) {
7996 case LUA_OK:
7997 break;
7998 case LUA_ERRRUN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007999 memprintf(err, "Lua runtime error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008000 lua_pop(gL.T, 1);
8001 return -1;
8002 case LUA_ERRMEM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008003 memprintf(err, "Lua out of memory error.n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008004 return -1;
8005 case LUA_ERRERR:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008006 memprintf(err, "Lua message handler error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008007 lua_pop(gL.T, 1);
8008 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +02008009#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008010 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008011 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008012 lua_pop(gL.T, 1);
8013 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +02008014#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008015 default:
Ilya Shipitsind4259502020-04-08 01:07:56 +05008016 memprintf(err, "Lua unknown error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008017 lua_pop(gL.T, 1);
8018 return -1;
8019 }
8020
8021 return 0;
8022}
8023
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +01008024/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
8025 * in the given <ctx>.
8026 */
8027static int hlua_prepend_path(struct hlua ctx, char *type, char *path)
8028{
8029 lua_getglobal(ctx.T, "package"); /* push package variable */
8030 lua_pushstring(ctx.T, path); /* push given path */
8031 lua_pushstring(ctx.T, ";"); /* push semicolon */
8032 lua_getfield(ctx.T, -3, type); /* push old path */
8033 lua_concat(ctx.T, 3); /* concatenate to new path */
8034 lua_setfield(ctx.T, -2, type); /* store new path */
8035 lua_pop(ctx.T, 1); /* pop package variable */
8036
8037 return 0;
8038}
8039
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008040static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
8041 struct proxy *defpx, const char *file, int line,
8042 char **err)
8043{
8044 char *path;
8045 char *type = "path";
8046 if (too_many_args(2, args, err, NULL)) {
8047 return -1;
8048 }
8049
8050 if (!(*args[1])) {
8051 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
8052 return -1;
8053 }
8054 path = args[1];
8055
8056 if (*args[2]) {
8057 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
8058 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
8059 return -1;
8060 }
8061 type = args[2];
8062 }
8063
8064 return hlua_prepend_path(gL, type, path);
8065}
8066
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008067/* configuration keywords declaration */
8068static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008069 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008070 { CFG_GLOBAL, "lua-load", hlua_load },
8071 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
8072 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02008073 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008074 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01008075 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008076 { 0, NULL, NULL },
8077}};
8078
Willy Tarreau0108d902018-11-25 19:14:37 +01008079INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
8080
Christopher Fauletafd8f102018-11-08 11:34:21 +01008081
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008082/* This function can fail with an abort() due to an Lua critical error.
8083 * We are in the initialisation process of HAProxy, this abort() is
8084 * tolerated.
8085 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008086int hlua_post_init()
8087{
8088 struct hlua_init_function *init;
8089 const char *msg;
8090 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008091 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008092
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05008093 /* Call post initialisation function in safe environment. */
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008094 if (!SET_SAFE_LJMP(gL.T)) {
8095 if (lua_type(gL.T, -1) == LUA_TSTRING)
8096 error = lua_tostring(gL.T, -1);
8097 else
8098 error = "critical error";
8099 fprintf(stderr, "Lua post-init: %s.\n", error);
8100 exit(1);
8101 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +02008102
8103#if USE_OPENSSL
8104 /* Initialize SSL server. */
8105 if (socket_ssl.xprt->prepare_srv) {
8106 int saved_used_backed = global.ssl_used_backend;
8107 // don't affect maxconn automatic computation
8108 socket_ssl.xprt->prepare_srv(&socket_ssl);
8109 global.ssl_used_backend = saved_used_backed;
8110 }
8111#endif
8112
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008113 hlua_fcn_post_init(gL.T);
8114 RESET_SAFE_LJMP(gL.T);
8115
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008116 list_for_each_entry(init, &hlua_init_functions, l) {
8117 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
8118 ret = hlua_ctx_resume(&gL, 0);
8119 switch (ret) {
8120 case HLUA_E_OK:
8121 lua_pop(gL.T, -1);
8122 return 1;
8123 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008124 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008125 return 0;
8126 case HLUA_E_ERRMSG:
8127 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01008128 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008129 return 0;
8130 case HLUA_E_ERR:
8131 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008132 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008133 return 0;
8134 }
8135 }
8136 return 1;
8137}
8138
Willy Tarreau32f61e22015-03-18 17:54:59 +01008139/* The memory allocator used by the Lua stack. <ud> is a pointer to the
8140 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
8141 * is the previously allocated size or the kind of object in case of a new
8142 * allocation. <nsize> is the requested new size.
8143 */
8144static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
8145{
8146 struct hlua_mem_allocator *zone = ud;
8147
8148 if (nsize == 0) {
8149 /* it's a free */
8150 if (ptr)
8151 zone->allocated -= osize;
8152 free(ptr);
8153 return NULL;
8154 }
8155
8156 if (!ptr) {
8157 /* it's a new allocation */
8158 if (zone->limit && zone->allocated + nsize > zone->limit)
8159 return NULL;
8160
8161 ptr = malloc(nsize);
8162 if (ptr)
8163 zone->allocated += nsize;
8164 return ptr;
8165 }
8166
8167 /* it's a realloc */
8168 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
8169 return NULL;
8170
8171 ptr = realloc(ptr, nsize);
8172 if (ptr)
8173 zone->allocated += nsize - osize;
8174 return ptr;
8175}
8176
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008177/* Ithis function can fail with an abort() due to an Lua critical error.
8178 * We are in the initialisation process of HAProxy, this abort() is
8179 * tolerated.
8180 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008181void hlua_init(void)
8182{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008183 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008184 int idx;
8185 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008186 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008187 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008188 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008189#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008190 struct srv_kw *kw;
8191 int tmp_error;
8192 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008193 char *args[] = { /* SSL client configuration. */
8194 "ssl",
8195 "verify",
8196 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008197 NULL
8198 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008199#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008200
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008201 /* Init main lua stack. */
8202 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01008203 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01008204 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02008205 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008206 hlua_sethlua(&gL);
8207 gL.Tref = LUA_REFNIL;
8208 gL.task = NULL;
8209
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008210 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008211 * the Lua function can fail with an abort. We are in the initialisation
8212 * process of HAProxy, this abort() is tolerated.
8213 */
8214
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008215 /* Initialise lua. */
8216 luaL_openlibs(gL.T);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +01008217#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
8218#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
8219#ifdef HLUA_PREPEND_PATH
8220 hlua_prepend_path(gL, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
8221#endif
8222#ifdef HLUA_PREPEND_CPATH
8223 hlua_prepend_path(gL, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
8224#endif
8225#undef HLUA_PREPEND_PATH_TOSTRING
8226#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008227
Thierry Fournier75933d42016-01-21 09:30:18 +01008228 /* Set safe environment for the initialisation. */
8229 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008230 if (lua_type(gL.T, -1) == LUA_TSTRING)
8231 error_msg = lua_tostring(gL.T, -1);
8232 else
8233 error_msg = "critical error";
8234 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01008235 exit(1);
8236 }
8237
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008238 /*
8239 *
8240 * Create "core" object.
8241 *
8242 */
8243
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01008244 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008245 lua_newtable(gL.T);
8246
8247 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008248 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008249 hlua_class_const_int(gL.T, log_levels[i], i);
8250
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008251 /* Register special functions. */
8252 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008253 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008254 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008255 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008256 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008257 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008258 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008259 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01008260 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008261 hlua_class_function(gL.T, "sleep", hlua_sleep);
8262 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01008263 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
8264 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
8265 hlua_class_function(gL.T, "set_map", hlua_set_map);
8266 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008267 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008268 hlua_class_function(gL.T, "log", hlua_log);
8269 hlua_class_function(gL.T, "Debug", hlua_log_debug);
8270 hlua_class_function(gL.T, "Info", hlua_log_info);
8271 hlua_class_function(gL.T, "Warning", hlua_log_warning);
8272 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02008273 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01008274 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008275
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008276 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008277
8278 /*
8279 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +01008280 * Create "act" object.
8281 *
8282 */
8283
8284 /* This table entry is the object "act" base. */
8285 lua_newtable(gL.T);
8286
8287 /* push action return constants */
8288 hlua_class_const_int(gL.T, "CONTINUE", ACT_RET_CONT);
8289 hlua_class_const_int(gL.T, "STOP", ACT_RET_STOP);
8290 hlua_class_const_int(gL.T, "YIELD", ACT_RET_YIELD);
8291 hlua_class_const_int(gL.T, "ERROR", ACT_RET_ERR);
8292 hlua_class_const_int(gL.T, "DONE", ACT_RET_DONE);
8293 hlua_class_const_int(gL.T, "DENY", ACT_RET_DENY);
8294 hlua_class_const_int(gL.T, "ABORT", ACT_RET_ABRT);
8295 hlua_class_const_int(gL.T, "INVALID", ACT_RET_INV);
8296
Christopher Faulet501465d2020-02-26 14:54:16 +01008297 hlua_class_function(gL.T, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008298
Christopher Faulet0f3c8902020-01-31 18:57:12 +01008299 lua_setglobal(gL.T, "act");
8300
8301 /*
8302 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008303 * Register class Map
8304 *
8305 */
8306
8307 /* This table entry is the object "Map" base. */
8308 lua_newtable(gL.T);
8309
8310 /* register pattern types. */
8311 for (i=0; i<PAT_MATCH_NUM; i++)
8312 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008313 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008314 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
8315 hlua_class_const_int(gL.T, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008316 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008317
8318 /* register constructor. */
8319 hlua_class_function(gL.T, "new", hlua_map_new);
8320
8321 /* Create and fill the metatable. */
8322 lua_newtable(gL.T);
8323
Ilya Shipitsind4259502020-04-08 01:07:56 +05008324 /* Create and fill the __index entry. */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008325 lua_pushstring(gL.T, "__index");
8326 lua_newtable(gL.T);
8327
8328 /* Register . */
8329 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
8330 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
8331
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008332 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008333
Thierry Fournier45e78d72016-02-19 18:34:46 +01008334 /* Register previous table in the registry with reference and named entry.
8335 * The function hlua_register_metatable() pops the stack, so we
8336 * previously create a copy of the table.
8337 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008338 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008339 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008340
8341 /* Assign the metatable to the mai Map object. */
8342 lua_setmetatable(gL.T, -2);
8343
8344 /* Set a name to the table. */
8345 lua_setglobal(gL.T, "Map");
8346
8347 /*
8348 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008349 * Register class Channel
8350 *
8351 */
8352
8353 /* Create and fill the metatable. */
8354 lua_newtable(gL.T);
8355
Ilya Shipitsind4259502020-04-08 01:07:56 +05008356 /* Create and fill the __index entry. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008357 lua_pushstring(gL.T, "__index");
8358 lua_newtable(gL.T);
8359
8360 /* Register . */
8361 hlua_class_function(gL.T, "get", hlua_channel_get);
8362 hlua_class_function(gL.T, "dup", hlua_channel_dup);
8363 hlua_class_function(gL.T, "getline", hlua_channel_getline);
8364 hlua_class_function(gL.T, "set", hlua_channel_set);
8365 hlua_class_function(gL.T, "append", hlua_channel_append);
8366 hlua_class_function(gL.T, "send", hlua_channel_send);
8367 hlua_class_function(gL.T, "forward", hlua_channel_forward);
8368 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
8369 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01008370 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01008371 hlua_class_function(gL.T, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008372
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008373 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008374
8375 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008376 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008377
8378 /*
8379 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008380 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008381 *
8382 */
8383
8384 /* Create and fill the metatable. */
8385 lua_newtable(gL.T);
8386
Ilya Shipitsind4259502020-04-08 01:07:56 +05008387 /* Create and fill the __index entry. */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008388 lua_pushstring(gL.T, "__index");
8389 lua_newtable(gL.T);
8390
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008391 /* Browse existing fetches and create the associated
8392 * object method.
8393 */
8394 sf = NULL;
8395 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008396 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8397 * by an underscore.
8398 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008399 strncpy(trash.area, sf->kw, trash.size);
8400 trash.area[trash.size - 1] = '\0';
8401 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008402 if (*p == '.' || *p == '-' || *p == '+')
8403 *p = '_';
8404
8405 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008406 lua_pushstring(gL.T, trash.area);
Willy Tarreau2ec22742015-03-10 14:27:20 +01008407 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008408 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008409 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008410 }
8411
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008412 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008413
8414 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008415 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008416
8417 /*
8418 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008419 * Register class Converters
8420 *
8421 */
8422
8423 /* Create and fill the metatable. */
8424 lua_newtable(gL.T);
8425
8426 /* Create and fill the __index entry. */
8427 lua_pushstring(gL.T, "__index");
8428 lua_newtable(gL.T);
8429
8430 /* Browse existing converters and create the associated
8431 * object method.
8432 */
8433 sc = NULL;
8434 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008435 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8436 * by an underscore.
8437 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008438 strncpy(trash.area, sc->kw, trash.size);
8439 trash.area[trash.size - 1] = '\0';
8440 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008441 if (*p == '.' || *p == '-' || *p == '+')
8442 *p = '_';
8443
8444 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008445 lua_pushstring(gL.T, trash.area);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008446 lua_pushlightuserdata(gL.T, sc);
8447 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008448 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008449 }
8450
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008451 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008452
8453 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008454 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008455
8456 /*
8457 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008458 * Register class HTTP
8459 *
8460 */
8461
8462 /* Create and fill the metatable. */
8463 lua_newtable(gL.T);
8464
Ilya Shipitsind4259502020-04-08 01:07:56 +05008465 /* Create and fill the __index entry. */
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008466 lua_pushstring(gL.T, "__index");
8467 lua_newtable(gL.T);
8468
8469 /* Register Lua functions. */
8470 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
8471 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
8472 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
8473 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
8474 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
8475 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
8476 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
8477 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
8478 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
8479 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
8480
8481 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
8482 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
8483 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
8484 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
8485 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
8486 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02008487 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008488
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008489 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008490
8491 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008492 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008493
8494 /*
8495 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008496 * Register class AppletTCP
8497 *
8498 */
8499
8500 /* Create and fill the metatable. */
8501 lua_newtable(gL.T);
8502
Ilya Shipitsind4259502020-04-08 01:07:56 +05008503 /* Create and fill the __index entry. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008504 lua_pushstring(gL.T, "__index");
8505 lua_newtable(gL.T);
8506
8507 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01008508 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
8509 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
8510 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
8511 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
8512 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008513 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
8514 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
8515 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008516
8517 lua_settable(gL.T, -3);
8518
8519 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008520 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008521
8522 /*
8523 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008524 * Register class AppletHTTP
8525 *
8526 */
8527
8528 /* Create and fill the metatable. */
8529 lua_newtable(gL.T);
8530
Ilya Shipitsind4259502020-04-08 01:07:56 +05008531 /* Create and fill the __index entry. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008532 lua_pushstring(gL.T, "__index");
8533 lua_newtable(gL.T);
8534
8535 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01008536 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
8537 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008538 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
8539 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
8540 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008541 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
8542 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
8543 hlua_class_function(gL.T, "send", hlua_applet_http_send);
8544 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
8545 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
8546 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
8547
8548 lua_settable(gL.T, -3);
8549
8550 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008551 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008552
8553 /*
8554 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008555 * Register class TXN
8556 *
8557 */
8558
8559 /* Create and fill the metatable. */
8560 lua_newtable(gL.T);
8561
Ilya Shipitsind4259502020-04-08 01:07:56 +05008562 /* Create and fill the __index entry. */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008563 lua_pushstring(gL.T, "__index");
8564 lua_newtable(gL.T);
8565
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008566 /* Register Lua functions. */
Patrick Hemmer268a7072018-05-11 12:52:31 -04008567 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
8568 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
8569 hlua_class_function(gL.T, "set_var", hlua_set_var);
8570 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
8571 hlua_class_function(gL.T, "get_var", hlua_get_var);
8572 hlua_class_function(gL.T, "done", hlua_txn_done);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008573 hlua_class_function(gL.T, "reply", hlua_txn_reply_new);
Patrick Hemmer268a7072018-05-11 12:52:31 -04008574 hlua_class_function(gL.T, "set_loglevel", hlua_txn_set_loglevel);
8575 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
8576 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
8577 hlua_class_function(gL.T, "set_priority_class", hlua_txn_set_priority_class);
8578 hlua_class_function(gL.T, "set_priority_offset", hlua_txn_set_priority_offset);
8579 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
8580 hlua_class_function(gL.T, "log", hlua_txn_log);
8581 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
8582 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
8583 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
8584 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008585
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008586 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008587
8588 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008589 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008590
8591 /*
8592 *
Christopher Faulet700d9e82020-01-31 12:21:52 +01008593 * Register class reply
8594 *
8595 */
8596 lua_newtable(gL.T);
8597 lua_pushstring(gL.T, "__index");
8598 lua_newtable(gL.T);
8599 hlua_class_function(gL.T, "set_status", hlua_txn_reply_set_status);
8600 hlua_class_function(gL.T, "add_header", hlua_txn_reply_add_header);
8601 hlua_class_function(gL.T, "del_header", hlua_txn_reply_del_header);
8602 hlua_class_function(gL.T, "set_body", hlua_txn_reply_set_body);
8603 lua_settable(gL.T, -3); /* Sets the __index entry. */
8604 class_txn_reply_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
8605
8606
8607 /*
8608 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008609 * Register class Socket
8610 *
8611 */
8612
8613 /* Create and fill the metatable. */
8614 lua_newtable(gL.T);
8615
Ilya Shipitsind4259502020-04-08 01:07:56 +05008616 /* Create and fill the __index entry. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008617 lua_pushstring(gL.T, "__index");
8618 lua_newtable(gL.T);
8619
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008620#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008621 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008622#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008623 hlua_class_function(gL.T, "connect", hlua_socket_connect);
8624 hlua_class_function(gL.T, "send", hlua_socket_send);
8625 hlua_class_function(gL.T, "receive", hlua_socket_receive);
8626 hlua_class_function(gL.T, "close", hlua_socket_close);
8627 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
8628 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
8629 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
8630 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
8631
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008632 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008633
8634 /* Register the garbage collector entry. */
8635 lua_pushstring(gL.T, "__gc");
8636 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008637 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008638
8639 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008640 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008641
8642 /* Proxy and server configuration initialisation. */
8643 memset(&socket_proxy, 0, sizeof(socket_proxy));
8644 init_new_proxy(&socket_proxy);
8645 socket_proxy.parent = NULL;
8646 socket_proxy.last_change = now.tv_sec;
8647 socket_proxy.id = "LUA-SOCKET";
8648 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
8649 socket_proxy.maxconn = 0;
8650 socket_proxy.accept = NULL;
8651 socket_proxy.options2 |= PR_O2_INDEPSTR;
8652 socket_proxy.srv = NULL;
8653 socket_proxy.conn_retries = 0;
8654 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
8655
8656 /* Init TCP server: unchanged parameters */
8657 memset(&socket_tcp, 0, sizeof(socket_tcp));
8658 socket_tcp.next = NULL;
8659 socket_tcp.proxy = &socket_proxy;
8660 socket_tcp.obj_type = OBJ_TYPE_SERVER;
8661 LIST_INIT(&socket_tcp.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008662 socket_tcp.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008663 socket_tcp.idle_conns = NULL;
8664 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008665 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008666 socket_tcp.last_change = 0;
8667 socket_tcp.id = "LUA-TCP-CONN";
8668 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8669 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8670 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
8671
8672 /* XXX: Copy default parameter from default server,
8673 * but the default server is not initialized.
8674 */
8675 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
8676 socket_tcp.minconn = socket_proxy.defsrv.minconn;
8677 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
8678 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
8679 socket_tcp.onerror = socket_proxy.defsrv.onerror;
8680 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8681 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
8682 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8683 socket_tcp.uweight = socket_proxy.defsrv.iweight;
8684 socket_tcp.iweight = socket_proxy.defsrv.iweight;
8685
8686 socket_tcp.check.status = HCHK_STATUS_INI;
8687 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
8688 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
8689 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
8690 socket_tcp.check.server = &socket_tcp;
8691
8692 socket_tcp.agent.status = HCHK_STATUS_INI;
8693 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
8694 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
8695 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
8696 socket_tcp.agent.server = &socket_tcp;
8697
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008698 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008699
8700#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008701 /* Init TCP server: unchanged parameters */
8702 memset(&socket_ssl, 0, sizeof(socket_ssl));
8703 socket_ssl.next = NULL;
8704 socket_ssl.proxy = &socket_proxy;
8705 socket_ssl.obj_type = OBJ_TYPE_SERVER;
8706 LIST_INIT(&socket_ssl.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008707 socket_ssl.pendconns = EB_ROOT;
Willy Tarreaub784b352019-02-07 14:48:24 +01008708 socket_ssl.idle_conns = NULL;
8709 socket_ssl.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008710 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008711 socket_ssl.last_change = 0;
8712 socket_ssl.id = "LUA-SSL-CONN";
8713 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8714 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8715 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
8716
8717 /* XXX: Copy default parameter from default server,
8718 * but the default server is not initialized.
8719 */
8720 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
8721 socket_ssl.minconn = socket_proxy.defsrv.minconn;
8722 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
8723 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
8724 socket_ssl.onerror = socket_proxy.defsrv.onerror;
8725 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8726 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
8727 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8728 socket_ssl.uweight = socket_proxy.defsrv.iweight;
8729 socket_ssl.iweight = socket_proxy.defsrv.iweight;
8730
8731 socket_ssl.check.status = HCHK_STATUS_INI;
8732 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
8733 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
8734 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
8735 socket_ssl.check.server = &socket_ssl;
8736
8737 socket_ssl.agent.status = HCHK_STATUS_INI;
8738 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
8739 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
8740 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
8741 socket_ssl.agent.server = &socket_ssl;
8742
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008743 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008744 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008745
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008746 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008747 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
8748 /*
8749 *
8750 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008751 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008752 * features like client certificates and ssl_verify.
8753 *
8754 */
8755 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
8756 if (tmp_error != 0) {
8757 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
8758 abort(); /* This must be never arrives because the command line
8759 not editable by the user. */
8760 }
8761 idx += kw->skip;
8762 }
8763 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008764#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01008765
8766 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008767}
Willy Tarreaubb57d942016-12-21 19:04:56 +01008768
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +02008769static void hlua_deinit()
8770{
8771 lua_close(gL.T);
8772}
8773
8774REGISTER_POST_DEINIT(hlua_deinit);
8775
Willy Tarreau80713382018-11-26 10:19:54 +01008776static void hlua_register_build_options(void)
8777{
Willy Tarreaubb57d942016-12-21 19:04:56 +01008778 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +01008779
Willy Tarreaubb57d942016-12-21 19:04:56 +01008780 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
8781 hap_register_build_opts(ptr, 1);
8782}
Willy Tarreau80713382018-11-26 10:19:54 +01008783
8784INITCALL0(STG_REGISTER, hlua_register_build_options);