blob: 633841c6d7aecce3e5cf893e01b5eed1cfe64e0f [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
Thierry FOURNIER380d0932015-01-23 14:27:52 +010024#include <ebpttree.h>
25
26#include <common/cfgparse.h>
Thierry FOURNIER2da788e2017-09-11 18:37:23 +020027#include <common/xref.h>
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +020028#include <common/hathreads.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010029
William Lallemand9ed62032016-11-21 17:49:11 +010030#include <types/cli.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010031#include <types/hlua.h>
32#include <types/proxy.h>
William Lallemand9ed62032016-11-21 17:49:11 +010033#include <types/stats.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010034
Thierry FOURNIER55da1652015-01-23 11:36:30 +010035#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020036#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010037#include <proto/channel.h>
William Lallemand9ed62032016-11-21 17:49:11 +010038#include <proto/cli.h>
Willy Tarreaua71f6422016-11-16 17:00:14 +010039#include <proto/connection.h>
William Lallemand9ed62032016-11-21 17:49:11 +010040#include <proto/stats.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010041#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010042#include <proto/hlua.h>
Thierry Fournierfb0b5462016-01-21 09:28:58 +010043#include <proto/hlua_fcn.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020044#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010045#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010046#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010047#include <proto/payload.h>
48#include <proto/proto_http.h>
49#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010050#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020051#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020052#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010053#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010054#include <proto/task.h>
Willy Tarreau39713102016-11-25 15:49:32 +010055#include <proto/tcp_rules.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020056#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010057
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010058/* Lua uses longjmp to perform yield or throwing errors. This
59 * macro is used only for identifying the function that can
60 * not return because a longjmp is executed.
61 * __LJMP marks a prototype of hlua file that can use longjmp.
62 * WILL_LJMP() marks an lua function that will use longjmp.
63 * MAY_LJMP() marks an lua function that may use longjmp.
64 */
65#define __LJMP
66#define WILL_LJMP(func) func
67#define MAY_LJMP(func) func
68
Thierry FOURNIERbabae282015-09-17 11:36:37 +020069/* This couple of function executes securely some Lua calls outside of
70 * the lua runtime environment. Each Lua call can return a longjmp
71 * if it encounter a memory error.
72 *
73 * Lua documentation extract:
74 *
75 * If an error happens outside any protected environment, Lua calls
76 * a panic function (see lua_atpanic) and then calls abort, thus
77 * exiting the host application. Your panic function can avoid this
78 * exit by never returning (e.g., doing a long jump to your own
79 * recovery point outside Lua).
80 *
81 * The panic function runs as if it were a message handler (see
82 * §2.3); in particular, the error message is at the top of the
83 * stack. However, there is no guarantee about stack space. To push
84 * anything on the stack, the panic function must first check the
85 * available space (see §4.2).
86 *
87 * We must check all the Lua entry point. This includes:
88 * - The include/proto/hlua.h exported functions
89 * - the task wrapper function
90 * - The action wrapper function
91 * - The converters wrapper function
92 * - The sample-fetch wrapper functions
93 *
94 * It is tolerated that the initilisation function returns an abort.
95 * Before each Lua abort, an error message is writed on stderr.
96 *
97 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
98 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
99 * because they must be exists in the program stack when the longjmp
100 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200101 *
102 * Note that the Lua processing is not really thread safe. It provides
103 * heavy system which consists to add our own lock function in the Lua
104 * code and recompile the library. This system will probably not accepted
105 * by maintainers of various distribs.
106 *
107 * Our main excution point of the Lua is the function lua_resume(). A
108 * quick looking on the Lua sources displays a lua_lock() a the start
109 * of function and a lua_unlock() at the end of the function. So I
110 * conclude that the Lua thread safe mode just perform a mutex around
111 * all execution. So I prefer to do this in the HAProxy code, it will be
112 * easier for distro maintainers.
113 *
114 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
115 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
116 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200117 */
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100118__decl_hathreads(HA_SPINLOCK_T hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200119THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200120static int hlua_panic_safe(lua_State *L) { return 0; }
121static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
122
123#define SET_SAFE_LJMP(__L) \
124 ({ \
125 int ret; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100126 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200127 if (setjmp(safe_ljmp_env) != 0) { \
128 lua_atpanic(__L, hlua_panic_safe); \
129 ret = 0; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100130 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200131 } else { \
132 lua_atpanic(__L, hlua_panic_ljmp); \
133 ret = 1; \
134 } \
135 ret; \
136 })
137
138/* If we are the last function catching Lua errors, we
139 * must reset the panic function.
140 */
141#define RESET_SAFE_LJMP(__L) \
142 do { \
143 lua_atpanic(__L, hlua_panic_safe); \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100144 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200145 } while(0)
146
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200147/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200148#define APPLET_DONE 0x01 /* applet processing is done. */
149#define APPLET_100C 0x02 /* 100 continue expected. */
150#define APPLET_HDR_SENT 0x04 /* Response header sent. */
151#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
152#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100153#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200154
155#define HTTP_100C "HTTP/1.1 100 Continue\r\n\r\n"
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200156
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100157/* The main Lua execution context. */
158struct hlua gL;
159
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100160/* This is the memory pool containing struct lua for applets
161 * (including cli).
162 */
Willy Tarreaubafbe012017-11-24 17:34:44 +0100163struct pool_head *pool_head_hlua;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100164
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100165/* Used for Socket connection. */
166static struct proxy socket_proxy;
167static struct server socket_tcp;
168#ifdef USE_OPENSSL
169static struct server socket_ssl;
170#endif
171
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100172/* List head of the function called at the initialisation time. */
173struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
174
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100175/* The following variables contains the reference of the different
176 * Lua classes. These references are useful for identify metadata
177 * associated with an object.
178 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100179static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100180static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100181static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100182static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100183static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100184static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200185static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200186static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200187static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100188
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100189/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200190 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100191 * short timeout. Lua linked with tasks doesn't have a timeout
192 * because a task may remain alive during all the haproxy execution.
193 */
194static unsigned int hlua_timeout_session = 4000; /* session timeout. */
195static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200196static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100197
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100198/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
199 * it is used for preventing infinite loops.
200 *
201 * I test the scheer with an infinite loop containing one incrementation
202 * and one test. I run this loop between 10 seconds, I raise a ceil of
203 * 710M loops from one interrupt each 9000 instructions, so I fix the value
204 * to one interrupt each 10 000 instructions.
205 *
206 * configured | Number of
207 * instructions | loops executed
208 * between two | in milions
209 * forced yields |
210 * ---------------+---------------
211 * 10 | 160
212 * 500 | 670
213 * 1000 | 680
214 * 5000 | 700
215 * 7000 | 700
216 * 8000 | 700
217 * 9000 | 710 <- ceil
218 * 10000 | 710
219 * 100000 | 710
220 * 1000000 | 710
221 *
222 */
223static unsigned int hlua_nb_instruction = 10000;
224
Willy Tarreau32f61e22015-03-18 17:54:59 +0100225/* Descriptor for the memory allocation state. If limit is not null, it will
226 * be enforced on any memory allocation.
227 */
228struct hlua_mem_allocator {
229 size_t allocated;
230 size_t limit;
231};
232
233static struct hlua_mem_allocator hlua_global_allocator;
234
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200235static const char error_500[] =
Jarno Huuskonen16ad94a2017-01-09 14:17:10 +0200236 "HTTP/1.0 500 Internal Server Error\r\n"
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200237 "Cache-Control: no-cache\r\n"
238 "Connection: close\r\n"
239 "Content-Type: text/html\r\n"
240 "\r\n"
Jarno Huuskonen16ad94a2017-01-09 14:17:10 +0200241 "<html><body><h1>500 Internal Server Error</h1>\nAn internal server error occured.\n</body></html>\n";
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200242
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100243/* These functions converts types between HAProxy internal args or
244 * sample and LUA types. Another function permits to check if the
245 * LUA stack contains arguments according with an required ARG_T
246 * format.
247 */
248static int hlua_arg2lua(lua_State *L, const struct arg *arg);
249static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100250__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100251 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100252static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100253static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100254static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
255
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200256__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
257
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200258#define SEND_ERR(__be, __fmt, __args...) \
259 do { \
260 send_log(__be, LOG_ERR, __fmt, ## __args); \
261 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100262 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200263 } while (0)
264
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100265/* Used to check an Lua function type in the stack. It creates and
266 * returns a reference of the function. This function throws an
267 * error if the rgument is not a "function".
268 */
269__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
270{
271 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100272 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100273 WILL_LJMP(luaL_argerror(L, argno, msg));
274 }
275 lua_pushvalue(L, argno);
276 return luaL_ref(L, LUA_REGISTRYINDEX);
277}
278
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200279/* Return the string that is of the top of the stack. */
280const char *hlua_get_top_error_string(lua_State *L)
281{
282 if (lua_gettop(L) < 1)
283 return "unknown error";
284 if (lua_type(L, -1) != LUA_TSTRING)
285 return "unknown error";
286 return lua_tostring(L, -1);
287}
288
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100289/* This function check the number of arguments available in the
290 * stack. If the number of arguments available is not the same
291 * then <nb> an error is throwed.
292 */
293__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
294{
295 if (lua_gettop(L) == nb)
296 return;
297 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
298}
299
Mark Lakes22154b42018-01-29 14:38:40 -0800300/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100301 * and the line number where the error is encountered.
302 */
303static int hlua_pusherror(lua_State *L, const char *fmt, ...)
304{
305 va_list argp;
306 va_start(argp, fmt);
307 luaL_where(L, 1);
308 lua_pushvfstring(L, fmt, argp);
309 va_end(argp);
310 lua_concat(L, 2);
311 return 1;
312}
313
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100314/* This functions is used with sample fetch and converters. It
315 * converts the HAProxy configuration argument in a lua stack
316 * values.
317 *
318 * It takes an array of "arg", and each entry of the array is
319 * converted and pushed in the LUA stack.
320 */
321static int hlua_arg2lua(lua_State *L, const struct arg *arg)
322{
323 switch (arg->type) {
324 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100325 case ARGT_TIME:
326 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100327 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100328 break;
329
330 case ARGT_STR:
331 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
332 break;
333
334 case ARGT_IPV4:
335 case ARGT_IPV6:
336 case ARGT_MSK4:
337 case ARGT_MSK6:
338 case ARGT_FE:
339 case ARGT_BE:
340 case ARGT_TAB:
341 case ARGT_SRV:
342 case ARGT_USR:
343 case ARGT_MAP:
344 default:
345 lua_pushnil(L);
346 break;
347 }
348 return 1;
349}
350
351/* This function take one entrie in an LUA stack at the index "ud",
352 * and try to convert it in an HAProxy argument entry. This is useful
353 * with sample fetch wrappers. The input arguments are gived to the
354 * lua wrapper and converted as arg list by thi function.
355 */
356static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
357{
358 switch (lua_type(L, ud)) {
359
360 case LUA_TNUMBER:
361 case LUA_TBOOLEAN:
362 arg->type = ARGT_SINT;
363 arg->data.sint = lua_tointeger(L, ud);
364 break;
365
366 case LUA_TSTRING:
367 arg->type = ARGT_STR;
368 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
369 break;
370
371 case LUA_TUSERDATA:
372 case LUA_TNIL:
373 case LUA_TTABLE:
374 case LUA_TFUNCTION:
375 case LUA_TTHREAD:
376 case LUA_TLIGHTUSERDATA:
377 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200378 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100379 break;
380 }
381 return 1;
382}
383
384/* the following functions are used to convert a struct sample
385 * in Lua type. This useful to convert the return of the
386 * fetchs or converters.
387 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100388static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100389{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200390 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100391 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100392 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200393 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100394 break;
395
396 case SMP_T_BIN:
397 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200398 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100399 break;
400
401 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200402 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100403 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
404 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
405 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
406 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
407 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
408 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
409 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
410 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
411 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200412 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100413 break;
414 default:
415 lua_pushnil(L);
416 break;
417 }
418 break;
419
420 case SMP_T_IPV4:
421 case SMP_T_IPV6:
422 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200423 if (sample_casts[smp->data.type][SMP_T_STR] &&
424 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200425 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100426 else
427 lua_pushnil(L);
428 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100429 default:
430 lua_pushnil(L);
431 break;
432 }
433 return 1;
434}
435
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100436/* the following functions are used to convert a struct sample
437 * in Lua strings. This is useful to convert the return of the
438 * fetchs or converters.
439 */
440static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
441{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200442 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100443
444 case SMP_T_BIN:
445 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200446 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100447 break;
448
449 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200450 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100451 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
452 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
453 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
454 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
455 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
456 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
457 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
458 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
459 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200460 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100461 break;
462 default:
463 lua_pushstring(L, "");
464 break;
465 }
466 break;
467
468 case SMP_T_SINT:
469 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100470 case SMP_T_IPV4:
471 case SMP_T_IPV6:
472 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200473 if (sample_casts[smp->data.type][SMP_T_STR] &&
474 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200475 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100476 else
477 lua_pushstring(L, "");
478 break;
479 default:
480 lua_pushstring(L, "");
481 break;
482 }
483 return 1;
484}
485
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100486/* the following functions are used to convert an Lua type in a
487 * struct sample. This is useful to provide data from a converter
488 * to the LUA code.
489 */
490static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
491{
492 switch (lua_type(L, ud)) {
493
494 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200495 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200496 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100497 break;
498
499
500 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200501 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200502 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100503 break;
504
505 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200506 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100507 smp->flags |= SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200508 smp->data.u.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100509 break;
510
511 case LUA_TUSERDATA:
512 case LUA_TNIL:
513 case LUA_TTABLE:
514 case LUA_TFUNCTION:
515 case LUA_TTHREAD:
516 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200517 case LUA_TNONE:
518 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200519 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200520 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100521 break;
522 }
523 return 1;
524}
525
526/* This function check the "argp" builded by another conversion function
527 * is in accord with the expected argp defined by the "mask". The fucntion
528 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100529 *
530 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
531 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100532 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100533__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100534 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100535{
536 int min_arg;
537 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100538 struct proxy *px;
539 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100540
541 idx = 0;
542 min_arg = ARGM(mask);
543 mask >>= ARGM_BITS;
544
545 while (1) {
546
547 /* Check oversize. */
548 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100549 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100550 }
551
552 /* Check for mandatory arguments. */
553 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100554 if (idx < min_arg) {
555
556 /* If miss other argument than the first one, we return an error. */
557 if (idx > 0)
558 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
559
560 /* If first argument have a certain type, some default values
561 * may be used. See the function smp_resolve_args().
562 */
563 switch (mask & ARGT_MASK) {
564
565 case ARGT_FE:
566 if (!(p->cap & PR_CAP_FE))
567 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
568 argp[idx].data.prx = p;
569 argp[idx].type = ARGT_FE;
570 argp[idx+1].type = ARGT_STOP;
571 break;
572
573 case ARGT_BE:
574 if (!(p->cap & PR_CAP_BE))
575 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
576 argp[idx].data.prx = p;
577 argp[idx].type = ARGT_BE;
578 argp[idx+1].type = ARGT_STOP;
579 break;
580
581 case ARGT_TAB:
582 argp[idx].data.prx = p;
583 argp[idx].type = ARGT_TAB;
584 argp[idx+1].type = ARGT_STOP;
585 break;
586
587 default:
588 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
589 break;
590 }
591 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100592 return 0;
593 }
594
595 /* Check for exceed the number of requiered argument. */
596 if ((mask & ARGT_MASK) == ARGT_STOP &&
597 argp[idx].type != ARGT_STOP) {
598 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
599 }
600
601 if ((mask & ARGT_MASK) == ARGT_STOP &&
602 argp[idx].type == ARGT_STOP) {
603 return 0;
604 }
605
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100606 /* Convert some argument types. */
607 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100608 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100609 if (argp[idx].type != ARGT_SINT)
610 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
611 argp[idx].type = ARGT_SINT;
612 break;
613
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100614 case ARGT_TIME:
615 if (argp[idx].type != ARGT_SINT)
616 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200617 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100618 break;
619
620 case ARGT_SIZE:
621 if (argp[idx].type != ARGT_SINT)
622 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200623 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100624 break;
625
626 case ARGT_FE:
627 if (argp[idx].type != ARGT_STR)
628 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
629 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
630 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200631 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100632 if (!argp[idx].data.prx)
633 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
634 argp[idx].type = ARGT_FE;
635 break;
636
637 case ARGT_BE:
638 if (argp[idx].type != ARGT_STR)
639 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
640 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
641 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200642 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100643 if (!argp[idx].data.prx)
644 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
645 argp[idx].type = ARGT_BE;
646 break;
647
648 case ARGT_TAB:
649 if (argp[idx].type != ARGT_STR)
650 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
651 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
652 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200653 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100654 if (!argp[idx].data.prx)
655 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
656 argp[idx].type = ARGT_TAB;
657 break;
658
659 case ARGT_SRV:
660 if (argp[idx].type != ARGT_STR)
661 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
662 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
663 trash.str[argp[idx].data.str.len] = 0;
664 sname = strrchr(trash.str, '/');
665 if (sname) {
666 *sname++ = '\0';
667 pname = trash.str;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200668 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100669 if (!px)
670 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
671 }
672 else {
673 sname = trash.str;
674 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100675 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100676 argp[idx].data.srv = findserver(px, sname);
677 if (!argp[idx].data.srv)
678 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
679 argp[idx].type = ARGT_SRV;
680 break;
681
682 case ARGT_IPV4:
683 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
684 trash.str[argp[idx].data.str.len] = 0;
685 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
686 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
687 argp[idx].type = ARGT_IPV4;
688 break;
689
690 case ARGT_MSK4:
691 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
692 trash.str[argp[idx].data.str.len] = 0;
693 if (!str2mask(trash.str, &argp[idx].data.ipv4))
694 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
695 argp[idx].type = ARGT_MSK4;
696 break;
697
698 case ARGT_IPV6:
699 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
700 trash.str[argp[idx].data.str.len] = 0;
701 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
702 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
703 argp[idx].type = ARGT_IPV6;
704 break;
705
706 case ARGT_MSK6:
Tim Duesterhusb814da62018-01-25 16:24:50 +0100707 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
708 trash.str[argp[idx].data.str.len] = 0;
709 if (!str2mask6(trash.str, &argp[idx].data.ipv6))
710 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 mask"));
711 argp[idx].type = ARGT_MSK6;
712 break;
713
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100714 case ARGT_MAP:
715 case ARGT_REG:
716 case ARGT_USR:
717 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100718 break;
719 }
720
721 /* Check for type of argument. */
722 if ((mask & ARGT_MASK) != argp[idx].type) {
723 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
724 arg_type_names[(mask & ARGT_MASK)],
725 arg_type_names[argp[idx].type & ARGT_MASK]);
726 WILL_LJMP(luaL_argerror(L, first + idx, msg));
727 }
728
729 /* Next argument. */
730 mask >>= ARGT_BITS;
731 idx++;
732 }
733}
734
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100735/*
736 * The following functions are used to make correspondance between the the
737 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100738 *
739 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100740 * - hlua_sethlua : create the association between hlua context and lua_state.
741 */
742static inline struct hlua *hlua_gethlua(lua_State *L)
743{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100744 struct hlua **hlua = lua_getextraspace(L);
745 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100746}
747static inline void hlua_sethlua(struct hlua *hlua)
748{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100749 struct hlua **hlua_store = lua_getextraspace(hlua->T);
750 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100751}
752
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100753/* This function is used to send logs. It try to send on screen (stderr)
754 * and on the default syslog server.
755 */
756static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
757{
758 struct tm tm;
759 char *p;
760
761 /* Cleanup the log message. */
762 p = trash.str;
763 for (; *msg != '\0'; msg++, p++) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200764 if (p >= trash.str + trash.size - 1) {
765 /* Break the message if exceed the buffer size. */
766 *(p-4) = ' ';
767 *(p-3) = '.';
768 *(p-2) = '.';
769 *(p-1) = '.';
770 break;
771 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100772 if (isprint(*msg))
773 *p = *msg;
774 else
775 *p = '.';
776 }
777 *p = '\0';
778
Thierry FOURNIER5554e292015-09-09 11:21:37 +0200779 send_log(px, level, "%s\n", trash.str);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100780 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200781 get_localtime(date.tv_sec, &tm);
782 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100783 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
784 (int)getpid(), trash.str);
785 fflush(stderr);
786 }
787}
788
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100789/* This function just ensure that the yield will be always
790 * returned with a timeout and permit to set some flags
791 */
792__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100793 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100794{
795 struct hlua *hlua = hlua_gethlua(L);
796
797 /* Set the wake timeout. If timeout is required, we set
798 * the expiration time.
799 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200800 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100801
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100802 hlua->flags |= flags;
803
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100804 /* Process the yield. */
805 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
806}
807
Willy Tarreau87b09662015-04-03 00:22:06 +0200808/* This function initialises the Lua environment stored in the stream.
809 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100810 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200811 *
812 * This function is particular. it initialises a new Lua thread. If the
813 * initialisation fails (example: out of memory error), the lua function
814 * throws an error (longjmp).
815 *
816 * This function manipulates two Lua stack: the main and the thread. Only
817 * the main stack can fail. The thread is not manipulated. This function
818 * MUST NOT manipulate the created thread stack state, because is not
819 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100820 */
821int hlua_ctx_init(struct hlua *lua, struct task *task)
822{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200823 if (!SET_SAFE_LJMP(gL.T)) {
824 lua->Tref = LUA_REFNIL;
825 return 0;
826 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100827 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100828 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100829 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100830 lua->T = lua_newthread(gL.T);
831 if (!lua->T) {
832 lua->Tref = LUA_REFNIL;
Thierry FOURNIER0a976202017-07-12 11:18:00 +0200833 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100834 return 0;
835 }
836 hlua_sethlua(lua);
837 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
838 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200839 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100840 return 1;
841}
842
Willy Tarreau87b09662015-04-03 00:22:06 +0200843/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100844 * is destroyed. The destroy also the memory context. The struct "lua"
845 * is not freed.
846 */
847void hlua_ctx_destroy(struct hlua *lua)
848{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100849 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100850 return;
851
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100852 if (!lua->T)
853 goto end;
854
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100855 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +0200856 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100857
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200858 if (!SET_SAFE_LJMP(lua->T))
859 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100860 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200861 RESET_SAFE_LJMP(lua->T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200862
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200863 if (!SET_SAFE_LJMP(gL.T))
864 return;
865 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
866 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200867 /* Forces a garbage collecting process. If the Lua program is finished
868 * without error, we run the GC on the thread pointer. Its freed all
869 * the unused memory.
870 * If the thread is finnish with an error or is currently yielded,
871 * it seems that the GC applied on the thread doesn't clean anything,
872 * so e run the GC on the main thread.
873 * NOTE: maybe this action locks all the Lua threads untiml the en of
874 * the garbage collection.
875 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200876 if (lua->flags & HLUA_MUST_GC) {
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200877 if (!SET_SAFE_LJMP(gL.T))
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200878 return;
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200879 lua_gc(gL.T, LUA_GCCOLLECT, 0);
880 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200881 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200882
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200883 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100884
885end:
Willy Tarreaubafbe012017-11-24 17:34:44 +0100886 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100887}
888
889/* This function is used to restore the Lua context when a coroutine
890 * fails. This function copy the common memory between old coroutine
891 * and the new coroutine. The old coroutine is destroyed, and its
892 * replaced by the new coroutine.
893 * If the flag "keep_msg" is set, the last entry of the old is assumed
894 * as string error message and it is copied in the new stack.
895 */
896static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
897{
898 lua_State *T;
899 int new_ref;
900
901 /* Renew the main LUA stack doesn't have sense. */
902 if (lua == &gL)
903 return 0;
904
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100905 /* New Lua coroutine. */
906 T = lua_newthread(gL.T);
907 if (!T)
908 return 0;
909
910 /* Copy last error message. */
911 if (keep_msg)
912 lua_xmove(lua->T, T, 1);
913
914 /* Copy data between the coroutines. */
915 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
916 lua_xmove(lua->T, T, 1);
917 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
918
919 /* Destroy old data. */
920 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
921
922 /* The thread is garbage collected by Lua. */
923 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
924
925 /* Fill the struct with the new coroutine values. */
926 lua->Mref = new_ref;
927 lua->T = T;
928 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
929
930 /* Set context. */
931 hlua_sethlua(lua);
932
933 return 1;
934}
935
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100936void hlua_hook(lua_State *L, lua_Debug *ar)
937{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100938 struct hlua *hlua = hlua_gethlua(L);
939
940 /* Lua cannot yield when its returning from a function,
941 * so, we can fix the interrupt hook to 1 instruction,
942 * expecting that the function is finnished.
943 */
944 if (lua_gethookmask(L) & LUA_MASKRET) {
945 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
946 return;
947 }
948
949 /* restore the interrupt condition. */
950 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
951
952 /* If we interrupt the Lua processing in yieldable state, we yield.
953 * If the state is not yieldable, trying yield causes an error.
954 */
955 if (lua_isyieldable(L))
956 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
957
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +0100958 /* If we cannot yield, update the clock and check the timeout. */
959 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200960 hlua->run_time += now_ms - hlua->start_time;
961 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100962 lua_pushfstring(L, "execution timeout");
963 WILL_LJMP(lua_error(L));
964 }
965
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200966 /* Update the start time. */
967 hlua->start_time = now_ms;
968
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100969 /* Try to interrupt the process at the end of the current
970 * unyieldable function.
971 */
972 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100973}
974
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100975/* This function start or resumes the Lua stack execution. If the flag
976 * "yield_allowed" if no set and the LUA stack execution returns a yield
977 * The function return an error.
978 *
979 * The function can returns 4 values:
980 * - HLUA_E_OK : The execution is terminated without any errors.
981 * - HLUA_E_AGAIN : The execution must continue at the next associated
982 * task wakeup.
983 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
984 * the top of the stack.
985 * - HLUA_E_ERR : An error has occured without error message.
986 *
987 * If an error occured, the stack is renewed and it is ready to run new
988 * LUA code.
989 */
990static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
991{
992 int ret;
993 const char *msg;
994
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200995 /* Initialise run time counter. */
996 if (!HLUA_IS_RUNNING(lua))
997 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100998
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200999 /* Lock the whole Lua execution. This lock must be before the
1000 * label "resume_execution".
1001 */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001002 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001003
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001004resume_execution:
1005
1006 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1007 * instructions. it is used for preventing infinite loops.
1008 */
1009 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1010
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001011 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001012 HLUA_SET_RUN(lua);
1013 HLUA_CLR_CTRLYIELD(lua);
1014 HLUA_CLR_WAKERESWR(lua);
1015 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001016
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001017 /* Update the start time. */
1018 lua->start_time = now_ms;
1019
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001020 /* Call the function. */
1021 ret = lua_resume(lua->T, gL.T, lua->nargs);
1022 switch (ret) {
1023
1024 case LUA_OK:
1025 ret = HLUA_E_OK;
1026 break;
1027
1028 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001029 /* Check if the execution timeout is expired. It it is the case, we
1030 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001031 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001032 tv_update_date(0, 1);
1033 lua->run_time += now_ms - lua->start_time;
1034 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001035 lua_settop(lua->T, 0); /* Empty the stack. */
1036 if (!lua_checkstack(lua->T, 1)) {
1037 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001038 break;
1039 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001040 lua_pushfstring(lua->T, "execution timeout");
1041 ret = HLUA_E_ERRMSG;
1042 break;
1043 }
1044 /* Process the forced yield. if the general yield is not allowed or
1045 * if no task were associated this the current Lua execution
1046 * coroutine, we resume the execution. Else we want to return in the
1047 * scheduler and we want to be waked up again, to continue the
1048 * current Lua execution. So we schedule our own task.
1049 */
1050 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001051 if (!yield_allowed || !lua->task)
1052 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001053 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001054 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001055 if (!yield_allowed) {
1056 lua_settop(lua->T, 0); /* Empty the stack. */
1057 if (!lua_checkstack(lua->T, 1)) {
1058 ret = HLUA_E_ERR;
1059 break;
1060 }
1061 lua_pushfstring(lua->T, "yield not allowed");
1062 ret = HLUA_E_ERRMSG;
1063 break;
1064 }
1065 ret = HLUA_E_AGAIN;
1066 break;
1067
1068 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001069
1070 /* Special exit case. The traditionnal exit is returned as an error
1071 * because the errors ares the only one mean to return immediately
1072 * from and lua execution.
1073 */
1074 if (lua->flags & HLUA_EXIT) {
1075 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001076 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001077 break;
1078 }
1079
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001080 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001081 if (!lua_checkstack(lua->T, 1)) {
1082 ret = HLUA_E_ERR;
1083 break;
1084 }
1085 msg = lua_tostring(lua->T, -1);
1086 lua_settop(lua->T, 0); /* Empty the stack. */
1087 lua_pop(lua->T, 1);
1088 if (msg)
1089 lua_pushfstring(lua->T, "runtime error: %s", msg);
1090 else
1091 lua_pushfstring(lua->T, "unknown runtime error");
1092 ret = HLUA_E_ERRMSG;
1093 break;
1094
1095 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001096 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001097 lua_settop(lua->T, 0); /* Empty the stack. */
1098 if (!lua_checkstack(lua->T, 1)) {
1099 ret = HLUA_E_ERR;
1100 break;
1101 }
1102 lua_pushfstring(lua->T, "out of memory error");
1103 ret = HLUA_E_ERRMSG;
1104 break;
1105
1106 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001107 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001108 if (!lua_checkstack(lua->T, 1)) {
1109 ret = HLUA_E_ERR;
1110 break;
1111 }
1112 msg = lua_tostring(lua->T, -1);
1113 lua_settop(lua->T, 0); /* Empty the stack. */
1114 lua_pop(lua->T, 1);
1115 if (msg)
1116 lua_pushfstring(lua->T, "message handler error: %s", msg);
1117 else
1118 lua_pushfstring(lua->T, "message handler error");
1119 ret = HLUA_E_ERRMSG;
1120 break;
1121
1122 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001123 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001124 lua_settop(lua->T, 0); /* Empty the stack. */
1125 if (!lua_checkstack(lua->T, 1)) {
1126 ret = HLUA_E_ERR;
1127 break;
1128 }
1129 lua_pushfstring(lua->T, "unknonwn error");
1130 ret = HLUA_E_ERRMSG;
1131 break;
1132 }
1133
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001134 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001135 if (lua->flags & HLUA_MUST_GC &&
1136 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001137 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1138
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001139 switch (ret) {
1140 case HLUA_E_AGAIN:
1141 break;
1142
1143 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001144 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001145 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001146 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001147 break;
1148
1149 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001150 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001151 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001152 hlua_ctx_renew(lua, 0);
1153 break;
1154
1155 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001156 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001157 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001158 break;
1159 }
1160
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001161 /* This is the main exit point, remove the Lua lock. */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001162 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001163
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001164 return ret;
1165}
1166
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001167/* This function exit the current code. */
1168__LJMP static int hlua_done(lua_State *L)
1169{
1170 struct hlua *hlua = hlua_gethlua(L);
1171
1172 hlua->flags |= HLUA_EXIT;
1173 WILL_LJMP(lua_error(L));
1174
1175 return 0;
1176}
1177
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001178/* This function is an LUA binding. It provides a function
1179 * for deleting ACL from a referenced ACL file.
1180 */
1181__LJMP static int hlua_del_acl(lua_State *L)
1182{
1183 const char *name;
1184 const char *key;
1185 struct pat_ref *ref;
1186
1187 MAY_LJMP(check_args(L, 2, "del_acl"));
1188
1189 name = MAY_LJMP(luaL_checkstring(L, 1));
1190 key = MAY_LJMP(luaL_checkstring(L, 2));
1191
1192 ref = pat_ref_lookup(name);
1193 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001194 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001195
1196 pat_ref_delete(ref, key);
1197 return 0;
1198}
1199
1200/* This function is an LUA binding. It provides a function
1201 * for deleting map entry from a referenced map file.
1202 */
1203static int hlua_del_map(lua_State *L)
1204{
1205 const char *name;
1206 const char *key;
1207 struct pat_ref *ref;
1208
1209 MAY_LJMP(check_args(L, 2, "del_map"));
1210
1211 name = MAY_LJMP(luaL_checkstring(L, 1));
1212 key = MAY_LJMP(luaL_checkstring(L, 2));
1213
1214 ref = pat_ref_lookup(name);
1215 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001216 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001217
1218 pat_ref_delete(ref, key);
1219 return 0;
1220}
1221
1222/* This function is an LUA binding. It provides a function
1223 * for adding ACL pattern from a referenced ACL file.
1224 */
1225static int hlua_add_acl(lua_State *L)
1226{
1227 const char *name;
1228 const char *key;
1229 struct pat_ref *ref;
1230
1231 MAY_LJMP(check_args(L, 2, "add_acl"));
1232
1233 name = MAY_LJMP(luaL_checkstring(L, 1));
1234 key = MAY_LJMP(luaL_checkstring(L, 2));
1235
1236 ref = pat_ref_lookup(name);
1237 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001238 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001239
1240 if (pat_ref_find_elt(ref, key) == NULL)
1241 pat_ref_add(ref, key, NULL, NULL);
1242 return 0;
1243}
1244
1245/* This function is an LUA binding. It provides a function
1246 * for setting map pattern and sample from a referenced map
1247 * file.
1248 */
1249static int hlua_set_map(lua_State *L)
1250{
1251 const char *name;
1252 const char *key;
1253 const char *value;
1254 struct pat_ref *ref;
1255
1256 MAY_LJMP(check_args(L, 3, "set_map"));
1257
1258 name = MAY_LJMP(luaL_checkstring(L, 1));
1259 key = MAY_LJMP(luaL_checkstring(L, 2));
1260 value = MAY_LJMP(luaL_checkstring(L, 3));
1261
1262 ref = pat_ref_lookup(name);
1263 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001264 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001265
1266 if (pat_ref_find_elt(ref, key) != NULL)
1267 pat_ref_set(ref, key, value, NULL);
1268 else
1269 pat_ref_add(ref, key, value, NULL);
1270 return 0;
1271}
1272
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001273/* A class is a lot of memory that contain data. This data can be a table,
1274 * an integer or user data. This data is associated with a metatable. This
1275 * metatable have an original version registred in the global context with
1276 * the name of the object (_G[<name>] = <metable> ).
1277 *
1278 * A metable is a table that modify the standard behavior of a standard
1279 * access to the associated data. The entries of this new metatable are
1280 * defined as is:
1281 *
1282 * http://lua-users.org/wiki/MetatableEvents
1283 *
1284 * __index
1285 *
1286 * we access an absent field in a table, the result is nil. This is
1287 * true, but it is not the whole truth. Actually, such access triggers
1288 * the interpreter to look for an __index metamethod: If there is no
1289 * such method, as usually happens, then the access results in nil;
1290 * otherwise, the metamethod will provide the result.
1291 *
1292 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1293 * the key does not appear in the table, but the metatable has an __index
1294 * property:
1295 *
1296 * - if the value is a function, the function is called, passing in the
1297 * table and the key; the return value of that function is returned as
1298 * the result.
1299 *
1300 * - if the value is another table, the value of the key in that table is
1301 * asked for and returned (and if it doesn't exist in that table, but that
1302 * table's metatable has an __index property, then it continues on up)
1303 *
1304 * - Use "rawget(myTable,key)" to skip this metamethod.
1305 *
1306 * http://www.lua.org/pil/13.4.1.html
1307 *
1308 * __newindex
1309 *
1310 * Like __index, but control property assignment.
1311 *
1312 * __mode - Control weak references. A string value with one or both
1313 * of the characters 'k' and 'v' which specifies that the the
1314 * keys and/or values in the table are weak references.
1315 *
1316 * __call - Treat a table like a function. When a table is followed by
1317 * parenthesis such as "myTable( 'foo' )" and the metatable has
1318 * a __call key pointing to a function, that function is invoked
1319 * (passing any specified arguments) and the return value is
1320 * returned.
1321 *
1322 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1323 * called, if the metatable for myTable has a __metatable
1324 * key, the value of that key is returned instead of the
1325 * actual metatable.
1326 *
1327 * __tostring - Control string representation. When the builtin
1328 * "tostring( myTable )" function is called, if the metatable
1329 * for myTable has a __tostring property set to a function,
1330 * that function is invoked (passing myTable to it) and the
1331 * return value is used as the string representation.
1332 *
1333 * __len - Control table length. When the table length is requested using
1334 * the length operator ( '#' ), if the metatable for myTable has
1335 * a __len key pointing to a function, that function is invoked
1336 * (passing myTable to it) and the return value used as the value
1337 * of "#myTable".
1338 *
1339 * __gc - Userdata finalizer code. When userdata is set to be garbage
1340 * collected, if the metatable has a __gc field pointing to a
1341 * function, that function is first invoked, passing the userdata
1342 * to it. The __gc metamethod is not called for tables.
1343 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1344 *
1345 * Special metamethods for redefining standard operators:
1346 * http://www.lua.org/pil/13.1.html
1347 *
1348 * __add "+"
1349 * __sub "-"
1350 * __mul "*"
1351 * __div "/"
1352 * __unm "!"
1353 * __pow "^"
1354 * __concat ".."
1355 *
1356 * Special methods for redfining standar relations
1357 * http://www.lua.org/pil/13.2.html
1358 *
1359 * __eq "=="
1360 * __lt "<"
1361 * __le "<="
1362 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001363
1364/*
1365 *
1366 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001367 * Class Map
1368 *
1369 *
1370 */
1371
1372/* Returns a struct hlua_map if the stack entry "ud" is
1373 * a class session, otherwise it throws an error.
1374 */
1375__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1376{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001377 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001378}
1379
1380/* This function is the map constructor. It don't need
1381 * the class Map object. It creates and return a new Map
1382 * object. It must be called only during "body" or "init"
1383 * context because it process some filesystem accesses.
1384 */
1385__LJMP static int hlua_map_new(struct lua_State *L)
1386{
1387 const char *fn;
1388 int match = PAT_MATCH_STR;
1389 struct sample_conv conv;
1390 const char *file = "";
1391 int line = 0;
1392 lua_Debug ar;
1393 char *err = NULL;
1394 struct arg args[2];
1395
1396 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1397 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1398
1399 fn = MAY_LJMP(luaL_checkstring(L, 1));
1400
1401 if (lua_gettop(L) >= 2) {
1402 match = MAY_LJMP(luaL_checkinteger(L, 2));
1403 if (match < 0 || match >= PAT_MATCH_NUM)
1404 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1405 }
1406
1407 /* Get Lua filename and line number. */
1408 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1409 lua_getinfo(L, "Sl", &ar); /* get info about it */
1410 if (ar.currentline > 0) { /* is there info? */
1411 file = ar.short_src;
1412 line = ar.currentline;
1413 }
1414 }
1415
1416 /* fill fake sample_conv struct. */
1417 conv.kw = ""; /* unused. */
1418 conv.process = NULL; /* unused. */
1419 conv.arg_mask = 0; /* unused. */
1420 conv.val_args = NULL; /* unused. */
1421 conv.out_type = SMP_T_STR;
1422 conv.private = (void *)(long)match;
1423 switch (match) {
1424 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1425 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1426 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1427 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1428 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1429 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1430 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001431 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001432 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1433 default:
1434 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1435 }
1436
1437 /* fill fake args. */
1438 args[0].type = ARGT_STR;
1439 args[0].data.str.str = (char *)fn;
1440 args[1].type = ARGT_STOP;
1441
1442 /* load the map. */
1443 if (!sample_load_map(args, &conv, file, line, &err)) {
1444 /* error case: we cant use luaL_error because we must
1445 * free the err variable.
1446 */
1447 luaL_where(L, 1);
1448 lua_pushfstring(L, "'new': %s.", err);
1449 lua_concat(L, 2);
1450 free(err);
1451 WILL_LJMP(lua_error(L));
1452 }
1453
1454 /* create the lua object. */
1455 lua_newtable(L);
1456 lua_pushlightuserdata(L, args[0].data.map);
1457 lua_rawseti(L, -2, 0);
1458
1459 /* Pop a class Map metatable and affect it to the userdata. */
1460 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1461 lua_setmetatable(L, -2);
1462
1463
1464 return 1;
1465}
1466
1467__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1468{
1469 struct map_descriptor *desc;
1470 struct pattern *pat;
1471 struct sample smp;
1472
1473 MAY_LJMP(check_args(L, 2, "lookup"));
1474 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001475 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001476 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001477 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001478 }
1479 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001480 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001481 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001482 smp.data.u.str.str = (char *)MAY_LJMP(luaL_checklstring(L, 2, (size_t *)&smp.data.u.str.len));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001483 }
1484
1485 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001486 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001487 if (str)
1488 lua_pushstring(L, "");
1489 else
1490 lua_pushnil(L);
1491 return 1;
1492 }
1493
1494 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001495 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001496 return 1;
1497}
1498
1499__LJMP static int hlua_map_lookup(struct lua_State *L)
1500{
1501 return _hlua_map_lookup(L, 0);
1502}
1503
1504__LJMP static int hlua_map_slookup(struct lua_State *L)
1505{
1506 return _hlua_map_lookup(L, 1);
1507}
1508
1509/*
1510 *
1511 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001512 * Class Socket
1513 *
1514 *
1515 */
1516
1517__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1518{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001519 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001520}
1521
1522/* This function is the handler called for each I/O on the established
1523 * connection. It is used for notify space avalaible to send or data
1524 * received.
1525 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001526static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001527{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001528 struct stream_interface *si = appctx->owner;
Olivier Houchard9aaf7782017-09-13 18:30:23 +02001529 struct connection *c = cs_conn(objt_cs(si_opposite(si)->end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001530
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001531 if (appctx->ctx.hlua_cosocket.die) {
1532 si_shutw(si);
1533 si_shutr(si);
1534 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001535 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1536 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001537 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1538 }
1539
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001540 /* If the connection object is not avalaible, close all the
1541 * streams and wakeup everithing waiting for.
1542 */
1543 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001544 si_shutw(si);
1545 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001546 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001547 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1548 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001549 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001550 }
1551
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001552 /* If we cant write, wakeup the pending write signals. */
1553 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001554 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001555
1556 /* If we cant read, wakeup the pending read signals. */
1557 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001558 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001559
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001560 /* if the connection is not estabkished, inform the stream that we want
1561 * to be notified whenever the connection completes.
1562 */
1563 if (!(c->flags & CO_FL_CONNECTED)) {
1564 si_applet_cant_get(si);
1565 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001566 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001567 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001568
1569 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001570 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001571
1572 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001573 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001574 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001575
1576 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001577 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001578 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001579}
1580
Willy Tarreau87b09662015-04-03 00:22:06 +02001581/* This function is called when the "struct stream" is destroyed.
1582 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001583 * Wake all the pending signals.
1584 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001585static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001586{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001587 struct xref *peer;
1588
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001589 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001590 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1591 if (peer)
1592 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001593
1594 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001595 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1596 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001597}
1598
1599/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001600 * uses this object. If the stream does not exists, just quit.
1601 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001602 * pending signal can rest in the read and write lists. destroy
1603 * it.
1604 */
1605__LJMP static int hlua_socket_gc(lua_State *L)
1606{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001607 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001608 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001609 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001610
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001611 MAY_LJMP(check_args(L, 1, "__gc"));
1612
1613 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001614 peer = xref_get_peer_and_lock(&socket->xref);
1615 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001616 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001617 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001618
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001619 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001620 appctx->ctx.hlua_cosocket.die = 1;
1621 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001622
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001623 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001624 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001625 return 0;
1626}
1627
1628/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001629 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001630 */
1631__LJMP static int hlua_socket_close(lua_State *L)
1632{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001633 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001634 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001635 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001636
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001637 MAY_LJMP(check_args(L, 1, "close"));
1638
1639 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001640
1641 /* Check if we run on the same thread than the xreator thread.
1642 * We cannot access to the socket if the thread is different.
1643 */
1644 if (socket->tid != tid)
1645 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1646
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001647 peer = xref_get_peer_and_lock(&socket->xref);
1648 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001649 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001650 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001651
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001652 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001653 appctx->ctx.hlua_cosocket.die = 1;
1654 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001655
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001656 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001657 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001658 return 0;
1659}
1660
1661/* This Lua function assumes that the stack contain three parameters.
1662 * 1 - USERDATA containing a struct socket
1663 * 2 - INTEGER with values of the macro defined below
1664 * If the integer is -1, we must read at most one line.
1665 * If the integer is -2, we ust read all the data until the
1666 * end of the stream.
1667 * If the integer is positive value, we must read a number of
1668 * bytes corresponding to this value.
1669 */
1670#define HLSR_READ_LINE (-1)
1671#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001672__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001673{
1674 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1675 int wanted = lua_tointeger(L, 2);
1676 struct hlua *hlua = hlua_gethlua(L);
1677 struct appctx *appctx;
1678 int len;
1679 int nblk;
1680 char *blk1;
1681 int len1;
1682 char *blk2;
1683 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001684 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001685 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001686 struct stream_interface *si;
1687 struct stream *s;
1688 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001689
1690 /* Check if this lua stack is schedulable. */
1691 if (!hlua || !hlua->task)
1692 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1693 "'frontend', 'backend' or 'task'"));
1694
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001695 /* Check if we run on the same thread than the xreator thread.
1696 * We cannot access to the socket if the thread is different.
1697 */
1698 if (socket->tid != tid)
1699 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1700
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001701 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001702 peer = xref_get_peer_and_lock(&socket->xref);
1703 if (!peer)
1704 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001705 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1706 si = appctx->owner;
1707 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001708
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001709 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001710 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001711 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001712 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001713 if (nblk < 0) /* Connection close. */
1714 goto connection_closed;
1715 if (nblk == 0) /* No data avalaible. */
1716 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001717
1718 /* remove final \r\n. */
1719 if (nblk == 1) {
1720 if (blk1[len1-1] == '\n') {
1721 len1--;
1722 skip_at_end++;
1723 if (blk1[len1-1] == '\r') {
1724 len1--;
1725 skip_at_end++;
1726 }
1727 }
1728 }
1729 else {
1730 if (blk2[len2-1] == '\n') {
1731 len2--;
1732 skip_at_end++;
1733 if (blk2[len2-1] == '\r') {
1734 len2--;
1735 skip_at_end++;
1736 }
1737 }
1738 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001739 }
1740
1741 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001742 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001743 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001744 if (nblk < 0) /* Connection close. */
1745 goto connection_closed;
1746 if (nblk == 0) /* No data avalaible. */
1747 goto connection_empty;
1748 }
1749
1750 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001751 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001752 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001753 if (nblk < 0) /* Connection close. */
1754 goto connection_closed;
1755 if (nblk == 0) /* No data avalaible. */
1756 goto connection_empty;
1757
1758 if (len1 > wanted) {
1759 nblk = 1;
1760 len1 = wanted;
1761 } if (nblk == 2 && len1 + len2 > wanted)
1762 len2 = wanted - len1;
1763 }
1764
1765 len = len1;
1766
1767 luaL_addlstring(&socket->b, blk1, len1);
1768 if (nblk == 2) {
1769 len += len2;
1770 luaL_addlstring(&socket->b, blk2, len2);
1771 }
1772
1773 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001774 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001775
1776 /* Don't wait anything. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001777 stream_int_notify(&s->si[0]);
1778 stream_int_update_applet(&s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001779
1780 /* If the pattern reclaim to read all the data
1781 * in the connection, got out.
1782 */
1783 if (wanted == HLSR_READ_ALL)
1784 goto connection_empty;
1785 else if (wanted >= 0 && len < wanted)
1786 goto connection_empty;
1787
1788 /* Return result. */
1789 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001790 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001791 return 1;
1792
1793connection_closed:
1794
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001795 xref_unlock(&socket->xref, peer);
1796
1797no_peer:
1798
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001799 /* If the buffer containds data. */
1800 if (socket->b.n > 0) {
1801 luaL_pushresult(&socket->b);
1802 return 1;
1803 }
1804 lua_pushnil(L);
1805 lua_pushstring(L, "connection closed.");
1806 return 2;
1807
1808connection_empty:
1809
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001810 appctx = objt_appctx(s->si[0].end);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001811 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
1812 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001813 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001814 }
1815 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001816 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001817 return 0;
1818}
1819
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001820/* This Lua function gets two parameters. The first one can be string
1821 * or a number. If the string is "*l", the user requires one line. If
1822 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001823 * If the value is a number, the user require a number of bytes equal
1824 * to the value. The default value is "*l" (a line).
1825 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001826 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001827 * integer takes this values:
1828 * -1 : read a line
1829 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001830 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001831 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001832 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001833 * concatenated with the read data.
1834 */
1835__LJMP static int hlua_socket_receive(struct lua_State *L)
1836{
1837 int wanted = HLSR_READ_LINE;
1838 const char *pattern;
1839 int type;
1840 char *error;
1841 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001842 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001843
1844 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1845 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1846
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001847 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001848
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001849 /* Check if we run on the same thread than the xreator thread.
1850 * We cannot access to the socket if the thread is different.
1851 */
1852 if (socket->tid != tid)
1853 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1854
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001855 /* check for pattern. */
1856 if (lua_gettop(L) >= 2) {
1857 type = lua_type(L, 2);
1858 if (type == LUA_TSTRING) {
1859 pattern = lua_tostring(L, 2);
1860 if (strcmp(pattern, "*a") == 0)
1861 wanted = HLSR_READ_ALL;
1862 else if (strcmp(pattern, "*l") == 0)
1863 wanted = HLSR_READ_LINE;
1864 else {
1865 wanted = strtoll(pattern, &error, 10);
1866 if (*error != '\0')
1867 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1868 }
1869 }
1870 else if (type == LUA_TNUMBER) {
1871 wanted = lua_tointeger(L, 2);
1872 if (wanted < 0)
1873 WILL_LJMP(luaL_error(L, "Unsupported size."));
1874 }
1875 }
1876
1877 /* Set pattern. */
1878 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01001879
1880 /* Check if we would replace the top by itself. */
1881 if (lua_gettop(L) != 2)
1882 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001883
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001884 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001885 luaL_buffinit(L, &socket->b);
1886
1887 /* Check prefix. */
1888 if (lua_gettop(L) >= 3) {
1889 if (lua_type(L, 3) != LUA_TSTRING)
1890 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1891 pattern = lua_tolstring(L, 3, &len);
1892 luaL_addlstring(&socket->b, pattern, len);
1893 }
1894
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001895 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001896}
1897
1898/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08001899 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001900 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001901static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001902{
1903 struct hlua_socket *socket;
1904 struct hlua *hlua = hlua_gethlua(L);
1905 struct appctx *appctx;
1906 size_t buf_len;
1907 const char *buf;
1908 int len;
1909 int send_len;
1910 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001911 struct xref *peer;
1912 struct stream_interface *si;
1913 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001914
1915 /* Check if this lua stack is schedulable. */
1916 if (!hlua || !hlua->task)
1917 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1918 "'frontend', 'backend' or 'task'"));
1919
1920 /* Get object */
1921 socket = MAY_LJMP(hlua_checksocket(L, 1));
1922 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001923 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001924
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001925 /* Check if we run on the same thread than the xreator thread.
1926 * We cannot access to the socket if the thread is different.
1927 */
1928 if (socket->tid != tid)
1929 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1930
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001931 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001932 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001933 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001934 lua_pushinteger(L, -1);
1935 return 1;
1936 }
1937 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1938 si = appctx->owner;
1939 s = si_strm(si);
1940
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001941 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001942 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001943 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001944 lua_pushinteger(L, -1);
1945 return 1;
1946 }
1947
1948 /* Update the input buffer data. */
1949 buf += sent;
1950 send_len = buf_len - sent;
1951
1952 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001953 if (sent >= buf_len) {
1954 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001955 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001956 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001957
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001958 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1959 * the request buffer if its not required.
1960 */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001961 if (s->req.buf->size == 0) {
Christopher Faulet33834b12016-12-19 09:29:06 +01001962 appctx = hlua->task->context;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001963 if (!channel_alloc_buffer(&s->req, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01001964 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001965 }
1966
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001967 /* Check for avalaible space. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001968 len = buffer_total_space(s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01001969 if (len <= 0) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001970 appctx = objt_appctx(s->si[0].end);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001971 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
1972 xref_unlock(&socket->xref, peer);
Christopher Faulet33834b12016-12-19 09:29:06 +01001973 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001974 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001975 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01001976 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001977
1978 /* send data */
1979 if (len < send_len)
1980 send_len = len;
Willy Tarreau06d80a92017-10-19 14:32:15 +02001981 len = ci_putblk(&s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001982
1983 /* "Not enough space" (-1), "Buffer too little to contain
1984 * the data" (-2) are not expected because the available length
1985 * is tested.
1986 * Other unknown error are also not expected.
1987 */
1988 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001989 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001990 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001991
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001992 MAY_LJMP(hlua_socket_close(L));
1993 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001994 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001995 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001996 return 1;
1997 }
1998
1999 /* update buffers. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002000 stream_int_notify(&s->si[0]);
2001 stream_int_update_applet(&s->si[0]);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002002
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002003 s->req.rex = TICK_ETERNITY;
2004 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002005
2006 /* Update length sent. */
2007 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002008 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002009
2010 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002011 if (sent + len >= buf_len) {
2012 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002013 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002014 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002015
2016hlua_socket_write_yield_return:
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002017 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002018 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002019 return 0;
2020}
2021
2022/* This function initiate the send of data. It just check the input
2023 * parameters and push an integer in the Lua stack that contain the
2024 * amount of data writed in the buffer. This is used by the function
2025 * "hlua_socket_write_yield" that can yield.
2026 *
2027 * The Lua function gets between 3 and 4 parameters. The first one is
2028 * the associated object. The second is a string buffer. The third is
2029 * a facultative integer that represents where is the buffer position
2030 * of the start of the data that can send. The first byte is the
2031 * position "1". The default value is "1". The fourth argument is a
2032 * facultative integer that represents where is the buffer position
2033 * of the end of the data that can send. The default is the last byte.
2034 */
2035static int hlua_socket_send(struct lua_State *L)
2036{
2037 int i;
2038 int j;
2039 const char *buf;
2040 size_t buf_len;
2041
2042 /* Check number of arguments. */
2043 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2044 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2045
2046 /* Get the string. */
2047 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2048
2049 /* Get and check j. */
2050 if (lua_gettop(L) == 4) {
2051 j = MAY_LJMP(luaL_checkinteger(L, 4));
2052 if (j < 0)
2053 j = buf_len + j + 1;
2054 if (j > buf_len)
2055 j = buf_len + 1;
2056 lua_pop(L, 1);
2057 }
2058 else
2059 j = buf_len;
2060
2061 /* Get and check i. */
2062 if (lua_gettop(L) == 3) {
2063 i = MAY_LJMP(luaL_checkinteger(L, 3));
2064 if (i < 0)
2065 i = buf_len + i + 1;
2066 if (i > buf_len)
2067 i = buf_len + 1;
2068 lua_pop(L, 1);
2069 } else
2070 i = 1;
2071
2072 /* Check bth i and j. */
2073 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002074 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002075 return 1;
2076 }
2077 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002078 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002079 return 1;
2080 }
2081 if (i == 0)
2082 i = 1;
2083 if (j == 0)
2084 j = 1;
2085
2086 /* Pop the string. */
2087 lua_pop(L, 1);
2088
2089 /* Update the buffer length. */
2090 buf += i - 1;
2091 buf_len = j - i + 1;
2092 lua_pushlstring(L, buf, buf_len);
2093
2094 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002095 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002096
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002097 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002098}
2099
Willy Tarreau22b0a682015-06-17 19:43:49 +02002100#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002101__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2102{
2103 static char buffer[SOCKET_INFO_MAX_LEN];
2104 int ret;
2105 int len;
2106 char *p;
2107
2108 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2109 if (ret <= 0) {
2110 lua_pushnil(L);
2111 return 1;
2112 }
2113
2114 if (ret == AF_UNIX) {
2115 lua_pushstring(L, buffer+1);
2116 return 1;
2117 }
2118 else if (ret == AF_INET6) {
2119 buffer[0] = '[';
2120 len = strlen(buffer);
2121 buffer[len] = ']';
2122 len++;
2123 buffer[len] = ':';
2124 len++;
2125 p = buffer;
2126 }
2127 else if (ret == AF_INET) {
2128 p = buffer + 1;
2129 len = strlen(p);
2130 p[len] = ':';
2131 len++;
2132 }
2133 else {
2134 lua_pushnil(L);
2135 return 1;
2136 }
2137
2138 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2139 lua_pushnil(L);
2140 return 1;
2141 }
2142
2143 lua_pushstring(L, p);
2144 return 1;
2145}
2146
2147/* Returns information about the peer of the connection. */
2148__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2149{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002150 struct hlua_socket *socket;
2151 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002152 struct xref *peer;
2153 struct appctx *appctx;
2154 struct stream_interface *si;
2155 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002156 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002157
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002158 MAY_LJMP(check_args(L, 1, "getpeername"));
2159
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002160 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002161
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002162 /* Check if we run on the same thread than the xreator thread.
2163 * We cannot access to the socket if the thread is different.
2164 */
2165 if (socket->tid != tid)
2166 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2167
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002168 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002169 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002170 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002171 lua_pushnil(L);
2172 return 1;
2173 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002174 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2175 si = appctx->owner;
2176 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002177
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002178 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002179 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002180 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002181 lua_pushnil(L);
2182 return 1;
2183 }
2184
Willy Tarreaua71f6422016-11-16 17:00:14 +01002185 conn_get_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002186 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002187 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002188 lua_pushnil(L);
2189 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002190 }
2191
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002192 ret = MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2193 xref_unlock(&socket->xref, peer);
2194 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002195}
2196
2197/* Returns information about my connection side. */
2198static int hlua_socket_getsockname(struct lua_State *L)
2199{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002200 struct hlua_socket *socket;
2201 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002202 struct appctx *appctx;
2203 struct xref *peer;
2204 struct stream_interface *si;
2205 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002206 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002207
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002208 MAY_LJMP(check_args(L, 1, "getsockname"));
2209
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002210 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002211
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002212 /* Check if we run on the same thread than the xreator thread.
2213 * We cannot access to the socket if the thread is different.
2214 */
2215 if (socket->tid != tid)
2216 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2217
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002218 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002219 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002220 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002221 lua_pushnil(L);
2222 return 1;
2223 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002224 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2225 si = appctx->owner;
2226 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002227
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002228 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002229 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002230 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002231 lua_pushnil(L);
2232 return 1;
2233 }
2234
Willy Tarreaua71f6422016-11-16 17:00:14 +01002235 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002236 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002237 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002238 lua_pushnil(L);
2239 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002240 }
2241
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002242 ret = hlua_socket_info(L, &conn->addr.from);
2243 xref_unlock(&socket->xref, peer);
2244 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002245}
2246
2247/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002248static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002249 .obj_type = OBJ_TYPE_APPLET,
2250 .name = "<LUA_TCP>",
2251 .fct = hlua_socket_handler,
2252 .release = hlua_socket_release,
2253};
2254
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002255__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002256{
2257 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2258 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002259 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002260 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002261 struct stream_interface *si;
2262 struct stream *s;
2263
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002264 /* Check if we run on the same thread than the xreator thread.
2265 * We cannot access to the socket if the thread is different.
2266 */
2267 if (socket->tid != tid)
2268 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2269
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002270 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002271 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002272 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002273 lua_pushnil(L);
2274 lua_pushstring(L, "Can't connect");
2275 return 2;
2276 }
2277 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2278 si = appctx->owner;
2279 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002280
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002281 /* Check if we run on the same thread than the xreator thread.
2282 * We cannot access to the socket if the thread is different.
2283 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002284 if (socket->tid != tid) {
2285 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002286 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002287 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002288
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002289 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002290 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002291 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002292 lua_pushnil(L);
2293 lua_pushstring(L, "Can't connect");
2294 return 2;
2295 }
2296
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002297 appctx = objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002298
2299 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002300 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002301 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002302 lua_pushinteger(L, 1);
2303 return 1;
2304 }
2305
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002306 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2307 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002308 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002309 }
2310 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002311 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002312 return 0;
2313}
2314
2315/* This function fail or initite the connection. */
2316__LJMP static int hlua_socket_connect(struct lua_State *L)
2317{
2318 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002319 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002320 const char *ip;
2321 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002322 struct hlua *hlua;
2323 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002324 int low, high;
2325 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002326 struct xref *peer;
2327 struct stream_interface *si;
2328 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002329
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002330 if (lua_gettop(L) < 2)
2331 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002332
2333 /* Get args. */
2334 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002335
2336 /* Check if we run on the same thread than the xreator thread.
2337 * We cannot access to the socket if the thread is different.
2338 */
2339 if (socket->tid != tid)
2340 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2341
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002342 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002343 if (lua_gettop(L) >= 3) {
2344 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002345 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002346
Tim Duesterhus6edab862018-01-06 19:04:45 +01002347 /* Force the ip to end with a colon, to support IPv6 addresses
2348 * that are not enclosed within square brackets.
2349 */
2350 if (port > 0) {
2351 luaL_buffinit(L, &b);
2352 luaL_addstring(&b, ip);
2353 luaL_addchar(&b, ':');
2354 luaL_pushresult(&b);
2355 ip = lua_tolstring(L, lua_gettop(L), NULL);
2356 }
2357 }
2358
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002359 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002360 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002361 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002362 lua_pushnil(L);
2363 return 1;
2364 }
2365 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2366 si = appctx->owner;
2367 s = si_strm(si);
2368
2369 /* Initialise connection. */
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002370 conn = cs_conn(si_alloc_cs(&s->si[1], NULL));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002371 if (!conn) {
2372 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002373 WILL_LJMP(luaL_error(L, "connect: internal error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002374 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002375
Willy Tarreau3adac082015-09-26 17:51:09 +02002376 /* needed for the connection not to be closed */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002377 conn->target = s->target;
Willy Tarreau3adac082015-09-26 17:51:09 +02002378
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002379 /* Parse ip address. */
Willy Tarreau48ef4c92017-01-06 18:32:38 +01002380 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, 0);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002381 if (!addr) {
2382 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002383 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002384 }
2385 if (low != high) {
2386 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002387 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002388 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002389 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002390
2391 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002392 if (low == 0) {
2393 if (conn->addr.to.ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002394 if (port == -1) {
2395 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002396 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002397 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002398 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2399 } else if (conn->addr.to.ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002400 if (port == -1) {
2401 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002402 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002403 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002404 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2405 }
2406 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002407
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002408 hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002409 appctx = objt_appctx(s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002410
2411 /* inform the stream that we want to be notified whenever the
2412 * connection completes.
2413 */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002414 si_applet_cant_get(&s->si[0]);
2415 si_applet_cant_put(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002416 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002417
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002418 hlua->flags |= HLUA_MUST_GC;
2419
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002420 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2421 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002422 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002423 }
2424 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002425 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002426
2427 return 0;
2428}
2429
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002430#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002431__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2432{
2433 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002434 struct xref *peer;
2435 struct appctx *appctx;
2436 struct stream_interface *si;
2437 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002438
2439 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2440 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002441
2442 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002443 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002444 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002445 lua_pushnil(L);
2446 return 1;
2447 }
2448 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2449 si = appctx->owner;
2450 s = si_strm(si);
2451
2452 s->target = &socket_ssl.obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002453 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002454 return MAY_LJMP(hlua_socket_connect(L));
2455}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002456#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002457
2458__LJMP static int hlua_socket_setoption(struct lua_State *L)
2459{
2460 return 0;
2461}
2462
2463__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2464{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002465 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002466 int tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002467 struct xref *peer;
2468 struct appctx *appctx;
2469 struct stream_interface *si;
2470 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002471
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002472 MAY_LJMP(check_args(L, 2, "settimeout"));
2473
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002474 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002475 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002476
Thierry Fournier17a921b2018-03-08 09:59:02 +01002477 /* Check for negative values */
2478 if (tmout < 0)
2479 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2480
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002481 /* Check if we run on the same thread than the xreator thread.
2482 * We cannot access to the socket if the thread is different.
2483 */
2484 if (socket->tid != tid)
2485 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2486
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002487 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002488 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002489 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002490 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2491 WILL_LJMP(lua_error(L));
2492 return 0;
2493 }
2494 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2495 si = appctx->owner;
2496 s = si_strm(si);
2497
2498 s->req.rto = tmout;
2499 s->req.wto = tmout;
2500 s->res.rto = tmout;
2501 s->res.wto = tmout;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002502 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002503
Thierry Fourniere9636f12018-03-08 09:54:32 +01002504 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002505 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002506}
2507
2508__LJMP static int hlua_socket_new(lua_State *L)
2509{
2510 struct hlua_socket *socket;
2511 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002512 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002513 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002514
2515 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002516 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002517 hlua_pusherror(L, "socket: full stack");
2518 goto out_fail_conf;
2519 }
2520
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002521 /* Create the object: obj[0] = userdata. */
2522 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002523 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002524 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002525 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002526 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002527
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002528 /* Check if the various memory pools are intialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002529 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002530 hlua_pusherror(L, "socket: uninitialized pools.");
2531 goto out_fail_conf;
2532 }
2533
Willy Tarreau87b09662015-04-03 00:22:06 +02002534 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002535 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2536 lua_setmetatable(L, -2);
2537
Willy Tarreaud420a972015-04-06 00:39:18 +02002538 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002539 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002540 if (!appctx) {
2541 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002542 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002543 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002544
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002545 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002546 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002547 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2548 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002549
Willy Tarreaud420a972015-04-06 00:39:18 +02002550 /* Now create a session, task and stream for this applet */
2551 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2552 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002553 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002554 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002555 }
2556
Willy Tarreau87787ac2017-08-28 16:22:54 +02002557 strm = stream_new(sess, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002558 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002559 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002560 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002561 }
2562
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002563 /* Initialise cross reference between stream and Lua socket object. */
2564 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002565
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002566 /* Configure "right" stream interface. this "si" is used to connect
2567 * and retrieve data from the server. The connection is initialized
2568 * with the "struct server".
2569 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002570 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002571
2572 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002573 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2574 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002575
Willy Tarreau87787ac2017-08-28 16:22:54 +02002576 task_wakeup(strm->task, TASK_WOKEN_INIT);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002577 /* Return yield waiting for connection. */
2578 return 1;
2579
Willy Tarreaud420a972015-04-06 00:39:18 +02002580 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002581 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002582 out_fail_sess:
2583 appctx_free(appctx);
2584 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002585 WILL_LJMP(lua_error(L));
2586 return 0;
2587}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002588
2589/*
2590 *
2591 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002592 * Class Channel
2593 *
2594 *
2595 */
2596
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002597/* The state between the channel data and the HTTP parser state can be
2598 * unconsistent, so reset the parser and call it again. Warning, this
2599 * action not revalidate the request and not send a 400 if the modified
2600 * resuest is not valid.
2601 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002602 * This function never fails. The direction is set using dir, which equals
2603 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002604 */
2605static void hlua_resynchonize_proto(struct stream *stream, int dir)
2606{
2607 /* Protocol HTTP. */
2608 if (stream->be->mode == PR_MODE_HTTP) {
2609
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002610 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002611 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002612 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002613 http_txn_reset_res(stream->txn);
2614
2615 if (stream->txn->hdr_idx.v)
2616 hdr_idx_init(&stream->txn->hdr_idx);
2617
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002618 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002619 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002620 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002621 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2622 }
2623}
2624
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002625/* This function is called before the Lua execution. It stores
2626 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002627 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002628static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002629{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002630 c->mode = stream->be->mode;
2631 switch (c->mode) {
2632 case PR_MODE_HTTP:
2633 c->data.http.dir = opt & SMP_OPT_DIR;
2634 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2635 c->data.http.state = stream->txn->req.msg_state;
2636 else
2637 c->data.http.state = stream->txn->rsp.msg_state;
2638 break;
2639 default:
2640 break;
2641 }
2642}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002643
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002644/* This function is called after the Lua execution. it
2645 * returns true if the parser state is consistent, otherwise,
2646 * it return false.
2647 *
2648 * In HTTP mode, the parser state must be in the same state
2649 * or greater when we exit the function. Even if we do a
2650 * control yield. This prevent to break the HTTP message
2651 * from the Lua code.
2652 */
2653static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2654{
2655 if (c->mode != stream->be->mode)
2656 return 0;
2657
2658 switch (c->mode) {
2659 case PR_MODE_HTTP:
2660 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002661 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002662 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2663 return stream->txn->req.msg_state >= c->data.http.state;
2664 else
2665 return stream->txn->rsp.msg_state >= c->data.http.state;
2666 default:
2667 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002668 }
2669 return 1;
2670}
2671
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002672/* Returns the struct hlua_channel join to the class channel in the
2673 * stack entry "ud" or throws an argument error.
2674 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002675__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002676{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002677 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002678}
2679
Willy Tarreau47860ed2015-03-10 14:07:50 +01002680/* Pushes the channel onto the top of the stack. If the stask does not have a
2681 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002682 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002683static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002684{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002685 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002686 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002687 return 0;
2688
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002689 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002690 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002691 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002692
2693 /* Pop a class sesison metatable and affect it to the userdata. */
2694 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2695 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002696 return 1;
2697}
2698
2699/* Duplicate all the data present in the input channel and put it
2700 * in a string LUA variables. Returns -1 and push a nil value in
2701 * the stack if the channel is closed and all the data are consumed,
2702 * returns 0 if no data are available, otherwise it returns the length
2703 * of the builded string.
2704 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002705static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002706{
2707 char *blk1;
2708 char *blk2;
2709 int len1;
2710 int len2;
2711 int ret;
2712 luaL_Buffer b;
2713
Willy Tarreau06d80a92017-10-19 14:32:15 +02002714 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002715 if (unlikely(ret == 0))
2716 return 0;
2717
2718 if (unlikely(ret < 0)) {
2719 lua_pushnil(L);
2720 return -1;
2721 }
2722
2723 luaL_buffinit(L, &b);
2724 luaL_addlstring(&b, blk1, len1);
2725 if (unlikely(ret == 2))
2726 luaL_addlstring(&b, blk2, len2);
2727 luaL_pushresult(&b);
2728
2729 if (unlikely(ret == 2))
2730 return len1 + len2;
2731 return len1;
2732}
2733
2734/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2735 * a yield. This function keep the data in the buffer.
2736 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002737__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002738{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002739 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002740
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002741 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2742
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002743 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002744 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002745 return 1;
2746}
2747
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002748/* Check arguments for the function "hlua_channel_dup_yield". */
2749__LJMP static int hlua_channel_dup(lua_State *L)
2750{
2751 MAY_LJMP(check_args(L, 1, "dup"));
2752 MAY_LJMP(hlua_checkchannel(L, 1));
2753 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2754}
2755
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002756/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2757 * a yield. This function consumes the data in the buffer. It returns
2758 * a string containing the data or a nil pointer if no data are available
2759 * and the channel is closed.
2760 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002761__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002762{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002763 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002764 int ret;
2765
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002766 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002767
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002768 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002769 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002770 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002771
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002772 if (unlikely(ret == -1))
2773 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002774
Willy Tarreau47860ed2015-03-10 14:07:50 +01002775 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002776 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002777 return 1;
2778}
2779
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002780/* Check arguments for the fucntion "hlua_channel_get_yield". */
2781__LJMP static int hlua_channel_get(lua_State *L)
2782{
2783 MAY_LJMP(check_args(L, 1, "get"));
2784 MAY_LJMP(hlua_checkchannel(L, 1));
2785 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2786}
2787
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002788/* This functions consumes and returns one line. If the channel is closed,
2789 * and the last data does not contains a final '\n', the data are returned
2790 * without the final '\n'. When no more data are avalaible, it returns nil
2791 * value.
2792 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002793__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002794{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002795 char *blk1;
2796 char *blk2;
2797 int len1;
2798 int len2;
2799 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002800 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002801 int ret;
2802 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002803
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002804 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2805
Willy Tarreau06d80a92017-10-19 14:32:15 +02002806 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002807 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002808 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002809
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002810 if (ret == -1) {
2811 lua_pushnil(L);
2812 return 1;
2813 }
2814
2815 luaL_buffinit(L, &b);
2816 luaL_addlstring(&b, blk1, len1);
2817 len = len1;
2818 if (unlikely(ret == 2)) {
2819 luaL_addlstring(&b, blk2, len2);
2820 len += len2;
2821 }
2822 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002823 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002824 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002825 return 1;
2826}
2827
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002828/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2829__LJMP static int hlua_channel_getline(lua_State *L)
2830{
2831 MAY_LJMP(check_args(L, 1, "getline"));
2832 MAY_LJMP(hlua_checkchannel(L, 1));
2833 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2834}
2835
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002836/* This function takes a string as input, and append it at the
2837 * input side of channel. If the data is too big, but a space
2838 * is probably available after sending some data, the function
2839 * yield. If the data is bigger than the buffer, or if the
2840 * channel is closed, it returns -1. otherwise, it returns the
2841 * amount of data writed.
2842 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002843__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002844{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002845 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002846 size_t len;
2847 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2848 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2849 int ret;
2850 int max;
2851
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002852 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2853 * the request buffer if its not required.
2854 */
2855 if (chn->buf->size == 0) {
2856 si_applet_cant_put(chn_prod(chn));
2857 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
2858 }
2859
Willy Tarreau47860ed2015-03-10 14:07:50 +01002860 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002861 if (max > len - l)
2862 max = len - l;
2863
Willy Tarreau06d80a92017-10-19 14:32:15 +02002864 ret = ci_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002865 if (ret == -2 || ret == -3) {
2866 lua_pushinteger(L, -1);
2867 return 1;
2868 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002869 if (ret == -1) {
2870 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002871 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002872 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002873 l += ret;
2874 lua_pop(L, 1);
2875 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002876 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002877
Willy Tarreau47860ed2015-03-10 14:07:50 +01002878 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2879 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002880 /* There are no space avalaible, and the output buffer is empty.
2881 * in this case, we cannot add more data, so we cannot yield,
2882 * we return the amount of copyied data.
2883 */
2884 return 1;
2885 }
2886 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002887 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002888 return 1;
2889}
2890
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002891/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002892 * of the writed string, or -1 if the channel is closed or if the
2893 * buffer size is too little for the data.
2894 */
2895__LJMP static int hlua_channel_append(lua_State *L)
2896{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002897 size_t len;
2898
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002899 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002900 MAY_LJMP(hlua_checkchannel(L, 1));
2901 MAY_LJMP(luaL_checklstring(L, 2, &len));
2902 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002903 lua_pushinteger(L, 0);
2904
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002905 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002906}
2907
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002908/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002909 * his process by cleaning the buffer. The result is a replacement
2910 * of the current data. It returns the length of the writed string,
2911 * or -1 if the channel is closed or if the buffer size is too
2912 * little for the data.
2913 */
2914__LJMP static int hlua_channel_set(lua_State *L)
2915{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002916 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002917
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002918 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002919 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002920 lua_pushinteger(L, 0);
2921
Willy Tarreau47860ed2015-03-10 14:07:50 +01002922 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002923
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002924 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002925}
2926
2927/* Append data in the output side of the buffer. This data is immediatly
2928 * sent. The fcuntion returns the ammount of data writed. If the buffer
2929 * cannot contains the data, the function yield. The function returns -1
2930 * if the channel is closed.
2931 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002932__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002933{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002934 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002935 size_t len;
2936 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2937 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2938 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002939 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002940
Willy Tarreau47860ed2015-03-10 14:07:50 +01002941 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002942 lua_pushinteger(L, -1);
2943 return 1;
2944 }
2945
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002946 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2947 * the request buffer if its not required.
2948 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002949 if (chn->buf->size == 0) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002950 si_applet_cant_put(chn_prod(chn));
2951 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002952 }
2953
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002954 /* the writed data will be immediatly sent, so we can check
2955 * the avalaible space without taking in account the reserve.
2956 * The reserve is guaranted for the processing of incoming
2957 * data, because the buffer will be flushed.
2958 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002959 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002960
2961 /* If there are no space avalaible, and the output buffer is empty.
2962 * in this case, we cannot add more data, so we cannot yield,
2963 * we return the amount of copyied data.
2964 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002965 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002966 return 1;
2967
2968 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002969 if (max > len - l)
2970 max = len - l;
2971
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002972 /* The buffer avalaible size may be not contiguous. This test
2973 * detects a non contiguous buffer and realign it.
2974 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002975 if (bi_space_for_replace(chn->buf) < max)
2976 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002977
2978 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002979 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002980
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002981 /* buffer replace considers that the input part is filled.
2982 * so, I must forward these new data in the output part.
2983 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002984 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002985
2986 l += max;
2987 lua_pop(L, 1);
2988 lua_pushinteger(L, l);
2989
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002990 /* If there are no space avalaible, and the output buffer is empty.
2991 * in this case, we cannot add more data, so we cannot yield,
2992 * we return the amount of copyied data.
2993 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002994 max = chn->buf->size - buffer_len(chn->buf);
2995 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002996 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002997
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002998 if (l < len) {
2999 /* If we are waiting for space in the response buffer, we
3000 * must set the flag WAKERESWR. This flag required the task
3001 * wake up if any activity is detected on the response buffer.
3002 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003003 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003004 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003005 else
3006 HLUA_SET_WAKEREQWR(hlua);
3007 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003008 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003009
3010 return 1;
3011}
3012
3013/* Just a wraper of "_hlua_channel_send". This wrapper permits
3014 * yield the LUA process, and resume it without checking the
3015 * input arguments.
3016 */
3017__LJMP static int hlua_channel_send(lua_State *L)
3018{
3019 MAY_LJMP(check_args(L, 2, "send"));
3020 lua_pushinteger(L, 0);
3021
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003022 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003023}
3024
3025/* This function forward and amount of butes. The data pass from
3026 * the input side of the buffer to the output side, and can be
3027 * forwarded. This function never fails.
3028 *
3029 * The Lua function takes an amount of bytes to be forwarded in
3030 * imput. It returns the number of bytes forwarded.
3031 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003032__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003033{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003034 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003035 int len;
3036 int l;
3037 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003038 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003039
3040 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3041 len = MAY_LJMP(luaL_checkinteger(L, 2));
3042 l = MAY_LJMP(luaL_checkinteger(L, -1));
3043
3044 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01003045 if (max > chn->buf->i)
3046 max = chn->buf->i;
3047 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003048 l += max;
3049
3050 lua_pop(L, 1);
3051 lua_pushinteger(L, l);
3052
3053 /* Check if it miss bytes to forward. */
3054 if (l < len) {
3055 /* The the input channel or the output channel are closed, we
3056 * must return the amount of data forwarded.
3057 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003058 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003059 return 1;
3060
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003061 /* If we are waiting for space data in the response buffer, we
3062 * must set the flag WAKERESWR. This flag required the task
3063 * wake up if any activity is detected on the response buffer.
3064 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003065 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003066 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003067 else
3068 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003069
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003070 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01003071 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003072 }
3073
3074 return 1;
3075}
3076
3077/* Just check the input and prepare the stack for the previous
3078 * function "hlua_channel_forward_yield"
3079 */
3080__LJMP static int hlua_channel_forward(lua_State *L)
3081{
3082 MAY_LJMP(check_args(L, 2, "forward"));
3083 MAY_LJMP(hlua_checkchannel(L, 1));
3084 MAY_LJMP(luaL_checkinteger(L, 2));
3085
3086 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003087 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003088}
3089
3090/* Just returns the number of bytes available in the input
3091 * side of the buffer. This function never fails.
3092 */
3093__LJMP static int hlua_channel_get_in_len(lua_State *L)
3094{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003095 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003096
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003097 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003098 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01003099 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003100 return 1;
3101}
3102
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003103/* Returns true if the channel is full. */
3104__LJMP static int hlua_channel_is_full(lua_State *L)
3105{
3106 struct channel *chn;
3107 int rem;
3108
3109 MAY_LJMP(check_args(L, 1, "is_full"));
3110 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3111
3112 rem = chn->buf->size;
3113 rem -= chn->buf->o; /* Output size */
3114 rem -= chn->buf->i; /* Input size */
3115 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
3116
3117 lua_pushboolean(L, rem <= 0);
3118 return 1;
3119}
3120
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003121/* Just returns the number of bytes available in the output
3122 * side of the buffer. This function never fails.
3123 */
3124__LJMP static int hlua_channel_get_out_len(lua_State *L)
3125{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003126 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003127
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003128 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003129 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01003130 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003131 return 1;
3132}
3133
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003134/*
3135 *
3136 *
3137 * Class Fetches
3138 *
3139 *
3140 */
3141
3142/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003143 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003144 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003145__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003146{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003147 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003148}
3149
3150/* This function creates and push in the stack a fetch object according
3151 * with a current TXN.
3152 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003153static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003154{
Willy Tarreau7073c472015-04-06 11:15:40 +02003155 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003156
3157 /* Check stack size. */
3158 if (!lua_checkstack(L, 3))
3159 return 0;
3160
3161 /* Create the object: obj[0] = userdata.
3162 * Note that the base of the Fetches object is the
3163 * transaction object.
3164 */
3165 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003166 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003167 lua_rawseti(L, -2, 0);
3168
Willy Tarreau7073c472015-04-06 11:15:40 +02003169 hsmp->s = txn->s;
3170 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003171 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003172 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003173
3174 /* Pop a class sesison metatable and affect it to the userdata. */
3175 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3176 lua_setmetatable(L, -2);
3177
3178 return 1;
3179}
3180
3181/* This function is an LUA binding. It is called with each sample-fetch.
3182 * It uses closure argument to store the associated sample-fetch. It
3183 * returns only one argument or throws an error. An error is thrown
3184 * only if an error is encountered during the argument parsing. If
3185 * the "sample-fetch" function fails, nil is returned.
3186 */
3187__LJMP static int hlua_run_sample_fetch(lua_State *L)
3188{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003189 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003190 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003191 struct arg args[ARGM_NBARGS + 1];
3192 int i;
3193 struct sample smp;
3194
3195 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003196 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003197
3198 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003199 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003200
Thierry FOURNIERca988662015-12-20 18:43:03 +01003201 /* Check execution authorization. */
3202 if (f->use & SMP_USE_HTTP_ANY &&
3203 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3204 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3205 "is not available in Lua services", f->kw);
3206 WILL_LJMP(lua_error(L));
3207 }
3208
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003209 /* Get extra arguments. */
3210 for (i = 0; i < lua_gettop(L) - 1; i++) {
3211 if (i >= ARGM_NBARGS)
3212 break;
3213 hlua_lua2arg(L, i + 2, &args[i]);
3214 }
3215 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003216 args[i].data.str.str = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003217
3218 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003219 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003220
3221 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003222 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003223 lua_pushfstring(L, "error in arguments");
3224 WILL_LJMP(lua_error(L));
3225 }
3226
3227 /* Initialise the sample. */
3228 memset(&smp, 0, sizeof(smp));
3229
3230 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003231 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003232 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003233 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003234 lua_pushstring(L, "");
3235 else
3236 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003237 return 1;
3238 }
3239
3240 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003241 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003242 hlua_smp2lua_str(L, &smp);
3243 else
3244 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003245 return 1;
3246}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003247
3248/*
3249 *
3250 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003251 * Class Converters
3252 *
3253 *
3254 */
3255
3256/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003257 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003258 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003259__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003260{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003261 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003262}
3263
3264/* This function creates and push in the stack a Converters object
3265 * according with a current TXN.
3266 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003267static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003268{
Willy Tarreau7073c472015-04-06 11:15:40 +02003269 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003270
3271 /* Check stack size. */
3272 if (!lua_checkstack(L, 3))
3273 return 0;
3274
3275 /* Create the object: obj[0] = userdata.
3276 * Note that the base of the Converters object is the
3277 * same than the TXN object.
3278 */
3279 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003280 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003281 lua_rawseti(L, -2, 0);
3282
Willy Tarreau7073c472015-04-06 11:15:40 +02003283 hsmp->s = txn->s;
3284 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003285 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003286 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003287
Willy Tarreau87b09662015-04-03 00:22:06 +02003288 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003289 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3290 lua_setmetatable(L, -2);
3291
3292 return 1;
3293}
3294
3295/* This function is an LUA binding. It is called with each converter.
3296 * It uses closure argument to store the associated converter. It
3297 * returns only one argument or throws an error. An error is thrown
3298 * only if an error is encountered during the argument parsing. If
3299 * the converter function function fails, nil is returned.
3300 */
3301__LJMP static int hlua_run_sample_conv(lua_State *L)
3302{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003303 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003304 struct sample_conv *conv;
3305 struct arg args[ARGM_NBARGS + 1];
3306 int i;
3307 struct sample smp;
3308
3309 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003310 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003311
3312 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003313 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003314
3315 /* Get extra arguments. */
3316 for (i = 0; i < lua_gettop(L) - 2; i++) {
3317 if (i >= ARGM_NBARGS)
3318 break;
3319 hlua_lua2arg(L, i + 3, &args[i]);
3320 }
3321 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003322 args[i].data.str.str = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003323
3324 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003325 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003326
3327 /* Run the special args checker. */
3328 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3329 hlua_pusherror(L, "error in arguments");
3330 WILL_LJMP(lua_error(L));
3331 }
3332
3333 /* Initialise the sample. */
3334 if (!hlua_lua2smp(L, 2, &smp)) {
3335 hlua_pusherror(L, "error in the input argument");
3336 WILL_LJMP(lua_error(L));
3337 }
3338
Willy Tarreau1777ea62016-03-10 16:15:46 +01003339 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3340
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003341 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003342 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003343 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003344 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003345 WILL_LJMP(lua_error(L));
3346 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003347 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3348 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003349 hlua_pusherror(L, "error during the input argument casting");
3350 WILL_LJMP(lua_error(L));
3351 }
3352
3353 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003354 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003355 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003356 lua_pushstring(L, "");
3357 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003358 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003359 return 1;
3360 }
3361
3362 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003363 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003364 hlua_smp2lua_str(L, &smp);
3365 else
3366 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003367 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003368}
3369
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003370/*
3371 *
3372 *
3373 * Class AppletTCP
3374 *
3375 *
3376 */
3377
3378/* Returns a struct hlua_txn if the stack entry "ud" is
3379 * a class stream, otherwise it throws an error.
3380 */
3381__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3382{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003383 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003384}
3385
3386/* This function creates and push in the stack an Applet object
3387 * according with a current TXN.
3388 */
3389static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3390{
3391 struct hlua_appctx *appctx;
3392 struct stream_interface *si = ctx->owner;
3393 struct stream *s = si_strm(si);
3394 struct proxy *p = s->be;
3395
3396 /* Check stack size. */
3397 if (!lua_checkstack(L, 3))
3398 return 0;
3399
3400 /* Create the object: obj[0] = userdata.
3401 * Note that the base of the Converters object is the
3402 * same than the TXN object.
3403 */
3404 lua_newtable(L);
3405 appctx = lua_newuserdata(L, sizeof(*appctx));
3406 lua_rawseti(L, -2, 0);
3407 appctx->appctx = ctx;
3408 appctx->htxn.s = s;
3409 appctx->htxn.p = p;
3410
3411 /* Create the "f" field that contains a list of fetches. */
3412 lua_pushstring(L, "f");
3413 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3414 return 0;
3415 lua_settable(L, -3);
3416
3417 /* Create the "sf" field that contains a list of stringsafe fetches. */
3418 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003419 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003420 return 0;
3421 lua_settable(L, -3);
3422
3423 /* Create the "c" field that contains a list of converters. */
3424 lua_pushstring(L, "c");
3425 if (!hlua_converters_new(L, &appctx->htxn, 0))
3426 return 0;
3427 lua_settable(L, -3);
3428
3429 /* Create the "sc" field that contains a list of stringsafe converters. */
3430 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003431 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003432 return 0;
3433 lua_settable(L, -3);
3434
3435 /* Pop a class stream metatable and affect it to the table. */
3436 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3437 lua_setmetatable(L, -2);
3438
3439 return 1;
3440}
3441
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003442__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3443{
3444 struct hlua_appctx *appctx;
3445 struct stream *s;
3446 const char *name;
3447 size_t len;
3448 struct sample smp;
3449
3450 MAY_LJMP(check_args(L, 3, "set_var"));
3451
3452 /* It is useles to retrieve the stream, but this function
3453 * runs only in a stream context.
3454 */
3455 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3456 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3457 s = appctx->htxn.s;
3458
3459 /* Converts the third argument in a sample. */
3460 hlua_lua2smp(L, 3, &smp);
3461
3462 /* Store the sample in a variable. */
3463 smp_set_owner(&smp, s->be, s->sess, s, 0);
3464 vars_set_by_name(name, len, &smp);
3465 return 0;
3466}
3467
3468__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3469{
3470 struct hlua_appctx *appctx;
3471 struct stream *s;
3472 const char *name;
3473 size_t len;
3474 struct sample smp;
3475
3476 MAY_LJMP(check_args(L, 2, "unset_var"));
3477
3478 /* It is useles to retrieve the stream, but this function
3479 * runs only in a stream context.
3480 */
3481 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3482 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3483 s = appctx->htxn.s;
3484
3485 /* Unset the variable. */
3486 smp_set_owner(&smp, s->be, s->sess, s, 0);
3487 vars_unset_by_name(name, len, &smp);
3488 return 0;
3489}
3490
3491__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3492{
3493 struct hlua_appctx *appctx;
3494 struct stream *s;
3495 const char *name;
3496 size_t len;
3497 struct sample smp;
3498
3499 MAY_LJMP(check_args(L, 2, "get_var"));
3500
3501 /* It is useles to retrieve the stream, but this function
3502 * runs only in a stream context.
3503 */
3504 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3505 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3506 s = appctx->htxn.s;
3507
3508 smp_set_owner(&smp, s->be, s->sess, s, 0);
3509 if (!vars_get_by_name(name, len, &smp)) {
3510 lua_pushnil(L);
3511 return 1;
3512 }
3513
3514 return hlua_smp2lua(L, &smp);
3515}
3516
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003517__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3518{
3519 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3520 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003521 struct hlua *hlua;
3522
3523 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003524 if (!s->hlua)
3525 return 0;
3526 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003527
3528 MAY_LJMP(check_args(L, 2, "set_priv"));
3529
3530 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003531 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003532
3533 /* Get and store new value. */
3534 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3535 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3536
3537 return 0;
3538}
3539
3540__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3541{
3542 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3543 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003544 struct hlua *hlua;
3545
3546 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003547 if (!s->hlua) {
3548 lua_pushnil(L);
3549 return 1;
3550 }
3551 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003552
3553 /* Push configuration index in the stack. */
3554 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3555
3556 return 1;
3557}
3558
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003559/* If expected data not yet available, it returns a yield. This function
3560 * consumes the data in the buffer. It returns a string containing the
3561 * data. This string can be empty.
3562 */
3563__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3564{
3565 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3566 struct stream_interface *si = appctx->appctx->owner;
3567 int ret;
3568 char *blk1;
3569 int len1;
3570 char *blk2;
3571 int len2;
3572
3573 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003574 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003575
3576 /* Data not yet avalaible. return yield. */
3577 if (ret == 0) {
3578 si_applet_cant_get(si);
3579 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3580 }
3581
3582 /* End of data: commit the total strings and return. */
3583 if (ret < 0) {
3584 luaL_pushresult(&appctx->b);
3585 return 1;
3586 }
3587
3588 /* Ensure that the block 2 length is usable. */
3589 if (ret == 1)
3590 len2 = 0;
3591
3592 /* dont check the max length read and dont check. */
3593 luaL_addlstring(&appctx->b, blk1, len1);
3594 luaL_addlstring(&appctx->b, blk2, len2);
3595
3596 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003597 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003598 luaL_pushresult(&appctx->b);
3599 return 1;
3600}
3601
3602/* Check arguments for the fucntion "hlua_channel_get_yield". */
3603__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3604{
3605 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3606
3607 /* Initialise the string catenation. */
3608 luaL_buffinit(L, &appctx->b);
3609
3610 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3611}
3612
3613/* If expected data not yet available, it returns a yield. This function
3614 * consumes the data in the buffer. It returns a string containing the
3615 * data. This string can be empty.
3616 */
3617__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3618{
3619 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3620 struct stream_interface *si = appctx->appctx->owner;
3621 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3622 int ret;
3623 char *blk1;
3624 int len1;
3625 char *blk2;
3626 int len2;
3627
3628 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003629 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003630
3631 /* Data not yet avalaible. return yield. */
3632 if (ret == 0) {
3633 si_applet_cant_get(si);
3634 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3635 }
3636
3637 /* End of data: commit the total strings and return. */
3638 if (ret < 0) {
3639 luaL_pushresult(&appctx->b);
3640 return 1;
3641 }
3642
3643 /* Ensure that the block 2 length is usable. */
3644 if (ret == 1)
3645 len2 = 0;
3646
3647 if (len == -1) {
3648
3649 /* If len == -1, catenate all the data avalaile and
3650 * yield because we want to get all the data until
3651 * the end of data stream.
3652 */
3653 luaL_addlstring(&appctx->b, blk1, len1);
3654 luaL_addlstring(&appctx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02003655 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003656 si_applet_cant_get(si);
3657 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3658
3659 } else {
3660
3661 /* Copy the fisrt block caping to the length required. */
3662 if (len1 > len)
3663 len1 = len;
3664 luaL_addlstring(&appctx->b, blk1, len1);
3665 len -= len1;
3666
3667 /* Copy the second block. */
3668 if (len2 > len)
3669 len2 = len;
3670 luaL_addlstring(&appctx->b, blk2, len2);
3671 len -= len2;
3672
3673 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003674 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003675
3676 /* If we are no other data avalaible, yield waiting for new data. */
3677 if (len > 0) {
3678 lua_pushinteger(L, len);
3679 lua_replace(L, 2);
3680 si_applet_cant_get(si);
3681 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3682 }
3683
3684 /* return the result. */
3685 luaL_pushresult(&appctx->b);
3686 return 1;
3687 }
3688
3689 /* we never executes this */
3690 hlua_pusherror(L, "Lua: internal error");
3691 WILL_LJMP(lua_error(L));
3692 return 0;
3693}
3694
3695/* Check arguments for the fucntion "hlua_channel_get_yield". */
3696__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3697{
3698 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3699 int len = -1;
3700
3701 if (lua_gettop(L) > 2)
3702 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3703 if (lua_gettop(L) >= 2) {
3704 len = MAY_LJMP(luaL_checkinteger(L, 2));
3705 lua_pop(L, 1);
3706 }
3707
3708 /* Confirm or set the required length */
3709 lua_pushinteger(L, len);
3710
3711 /* Initialise the string catenation. */
3712 luaL_buffinit(L, &appctx->b);
3713
3714 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3715}
3716
3717/* Append data in the output side of the buffer. This data is immediatly
3718 * sent. The fcuntion returns the ammount of data writed. If the buffer
3719 * cannot contains the data, the function yield. The function returns -1
3720 * if the channel is closed.
3721 */
3722__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3723{
3724 size_t len;
3725 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3726 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3727 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3728 struct stream_interface *si = appctx->appctx->owner;
3729 struct channel *chn = si_ic(si);
3730 int max;
3731
3732 /* Get the max amount of data which can write as input in the channel. */
3733 max = channel_recv_max(chn);
3734 if (max > (len - l))
3735 max = len - l;
3736
3737 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003738 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003739
3740 /* update counters. */
3741 l += max;
3742 lua_pop(L, 1);
3743 lua_pushinteger(L, l);
3744
3745 /* If some data is not send, declares the situation to the
3746 * applet, and returns a yield.
3747 */
3748 if (l < len) {
3749 si_applet_cant_put(si);
3750 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3751 }
3752
3753 return 1;
3754}
3755
3756/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3757 * yield the LUA process, and resume it without checking the
3758 * input arguments.
3759 */
3760__LJMP static int hlua_applet_tcp_send(lua_State *L)
3761{
3762 MAY_LJMP(check_args(L, 2, "send"));
3763 lua_pushinteger(L, 0);
3764
3765 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3766}
3767
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003768/*
3769 *
3770 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003771 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003772 *
3773 *
3774 */
3775
3776/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003777 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003778 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003779__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003780{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003781 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003782}
3783
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003784/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003785 * according with a current TXN.
3786 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003787static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003788{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003789 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003790 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003791 struct stream_interface *si = ctx->owner;
3792 struct stream *s = si_strm(si);
3793 struct proxy *px = s->be;
3794 struct http_txn *txn = s->txn;
3795 const char *path;
3796 const char *end;
3797 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003798
3799 /* Check stack size. */
3800 if (!lua_checkstack(L, 3))
3801 return 0;
3802
3803 /* Create the object: obj[0] = userdata.
3804 * Note that the base of the Converters object is the
3805 * same than the TXN object.
3806 */
3807 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003808 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003809 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003810 appctx->appctx = ctx;
3811 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003812 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003813 appctx->htxn.s = s;
3814 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003815
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003816 /* Create the "f" field that contains a list of fetches. */
3817 lua_pushstring(L, "f");
3818 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3819 return 0;
3820 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003821
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003822 /* Create the "sf" field that contains a list of stringsafe fetches. */
3823 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003824 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003825 return 0;
3826 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003827
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003828 /* Create the "c" field that contains a list of converters. */
3829 lua_pushstring(L, "c");
3830 if (!hlua_converters_new(L, &appctx->htxn, 0))
3831 return 0;
3832 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003833
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003834 /* Create the "sc" field that contains a list of stringsafe converters. */
3835 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003836 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003837 return 0;
3838 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003839
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003840 /* Stores the request method. */
3841 lua_pushstring(L, "method");
3842 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3843 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003844
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003845 /* Stores the http version. */
3846 lua_pushstring(L, "version");
3847 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3848 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003849
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003850 /* creates an array of headers. hlua_http_get_headers() crates and push
3851 * the array on the top of the stack.
3852 */
3853 lua_pushstring(L, "headers");
3854 htxn.s = s;
3855 htxn.p = px;
3856 htxn.dir = SMP_OPT_DIR_REQ;
3857 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3858 return 0;
3859 lua_settable(L, -3);
3860
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003861 /* Get path and qs */
3862 path = http_get_path(txn);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003863 if (path) {
3864 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3865 p = path;
3866 while (p < end && *p != '?')
3867 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003868
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003869 /* Stores the request path. */
3870 lua_pushstring(L, "path");
3871 lua_pushlstring(L, path, p - path);
3872 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003873
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003874 /* Stores the query string. */
3875 lua_pushstring(L, "qs");
3876 if (*p == '?')
3877 p++;
3878 lua_pushlstring(L, p, end - p);
3879 lua_settable(L, -3);
3880 }
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003881
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003882 /* Stores the request path. */
3883 lua_pushstring(L, "length");
3884 lua_pushinteger(L, txn->req.body_len);
3885 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003886
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003887 /* Create an array of HTTP request headers. */
3888 lua_pushstring(L, "headers");
3889 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3890 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003891
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003892 /* Create an empty array of HTTP request headers. */
3893 lua_pushstring(L, "response");
3894 lua_newtable(L);
3895 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003896
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003897 /* Pop a class stream metatable and affect it to the table. */
3898 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3899 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003900
3901 return 1;
3902}
3903
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003904__LJMP static int hlua_applet_http_set_var(lua_State *L)
3905{
3906 struct hlua_appctx *appctx;
3907 struct stream *s;
3908 const char *name;
3909 size_t len;
3910 struct sample smp;
3911
3912 MAY_LJMP(check_args(L, 3, "set_var"));
3913
3914 /* It is useles to retrieve the stream, but this function
3915 * runs only in a stream context.
3916 */
3917 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3918 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3919 s = appctx->htxn.s;
3920
3921 /* Converts the third argument in a sample. */
3922 hlua_lua2smp(L, 3, &smp);
3923
3924 /* Store the sample in a variable. */
3925 smp_set_owner(&smp, s->be, s->sess, s, 0);
3926 vars_set_by_name(name, len, &smp);
3927 return 0;
3928}
3929
3930__LJMP static int hlua_applet_http_unset_var(lua_State *L)
3931{
3932 struct hlua_appctx *appctx;
3933 struct stream *s;
3934 const char *name;
3935 size_t len;
3936 struct sample smp;
3937
3938 MAY_LJMP(check_args(L, 2, "unset_var"));
3939
3940 /* It is useles to retrieve the stream, but this function
3941 * runs only in a stream context.
3942 */
3943 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3944 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3945 s = appctx->htxn.s;
3946
3947 /* Unset the variable. */
3948 smp_set_owner(&smp, s->be, s->sess, s, 0);
3949 vars_unset_by_name(name, len, &smp);
3950 return 0;
3951}
3952
3953__LJMP static int hlua_applet_http_get_var(lua_State *L)
3954{
3955 struct hlua_appctx *appctx;
3956 struct stream *s;
3957 const char *name;
3958 size_t len;
3959 struct sample smp;
3960
3961 MAY_LJMP(check_args(L, 2, "get_var"));
3962
3963 /* It is useles to retrieve the stream, but this function
3964 * runs only in a stream context.
3965 */
3966 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3967 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3968 s = appctx->htxn.s;
3969
3970 smp_set_owner(&smp, s->be, s->sess, s, 0);
3971 if (!vars_get_by_name(name, len, &smp)) {
3972 lua_pushnil(L);
3973 return 1;
3974 }
3975
3976 return hlua_smp2lua(L, &smp);
3977}
3978
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003979__LJMP static int hlua_applet_http_set_priv(lua_State *L)
3980{
3981 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3982 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003983 struct hlua *hlua;
3984
3985 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003986 if (!s->hlua)
3987 return 0;
3988 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003989
3990 MAY_LJMP(check_args(L, 2, "set_priv"));
3991
3992 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003993 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003994
3995 /* Get and store new value. */
3996 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3997 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3998
3999 return 0;
4000}
4001
4002__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4003{
4004 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4005 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004006 struct hlua *hlua;
4007
4008 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004009 if (!s->hlua) {
4010 lua_pushnil(L);
4011 return 1;
4012 }
4013 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004014
4015 /* Push configuration index in the stack. */
4016 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4017
4018 return 1;
4019}
4020
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004021/* If expected data not yet available, it returns a yield. This function
4022 * consumes the data in the buffer. It returns a string containing the
4023 * data. This string can be empty.
4024 */
4025__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004026{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004027 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4028 struct stream_interface *si = appctx->appctx->owner;
4029 struct channel *chn = si_ic(si);
4030 int ret;
4031 char *blk1;
4032 int len1;
4033 char *blk2;
4034 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004035
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004036 /* Maybe we cant send a 100-continue ? */
4037 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau06d80a92017-10-19 14:32:15 +02004038 ret = ci_putblk(chn, HTTP_100C, strlen(HTTP_100C));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004039 /* if ret == -2 or -3 the channel closed or the message si too
4040 * big for the buffers. We cant send anything. So, we ignoring
4041 * the error, considers that the 100-continue is sent, and try
4042 * to receive.
4043 * If ret is -1, we dont have room in the buffer, so we yield.
4044 */
4045 if (ret == -1) {
4046 si_applet_cant_put(si);
4047 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
4048 }
4049 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4050 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004051
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004052 /* Check for the end of the data. */
4053 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
4054 luaL_pushresult(&appctx->b);
4055 return 1;
4056 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004057
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004058 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004059 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004060
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004061 /* Data not yet avalaible. return yield. */
4062 if (ret == 0) {
4063 si_applet_cant_get(si);
4064 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
4065 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004066
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004067 /* End of data: commit the total strings and return. */
4068 if (ret < 0) {
4069 luaL_pushresult(&appctx->b);
4070 return 1;
4071 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004072
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004073 /* Ensure that the block 2 length is usable. */
4074 if (ret == 1)
4075 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004076
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004077 /* Copy the fisrt block caping to the length required. */
4078 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4079 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4080 luaL_addlstring(&appctx->b, blk1, len1);
4081 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004082
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004083 /* Copy the second block. */
4084 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4085 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4086 luaL_addlstring(&appctx->b, blk2, len2);
4087 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004088
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004089 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004090 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004091 luaL_pushresult(&appctx->b);
4092 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004093}
4094
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004095/* Check arguments for the fucntion "hlua_channel_get_yield". */
4096__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004097{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004098 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004099
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004100 /* Initialise the string catenation. */
4101 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004102
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004103 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004104}
4105
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004106/* If expected data not yet available, it returns a yield. This function
4107 * consumes the data in the buffer. It returns a string containing the
4108 * data. This string can be empty.
4109 */
4110__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004111{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004112 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4113 struct stream_interface *si = appctx->appctx->owner;
4114 int len = MAY_LJMP(luaL_checkinteger(L, 2));
4115 struct channel *chn = si_ic(si);
4116 int ret;
4117 char *blk1;
4118 int len1;
4119 char *blk2;
4120 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004121
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004122 /* Maybe we cant send a 100-continue ? */
4123 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau06d80a92017-10-19 14:32:15 +02004124 ret = ci_putblk(chn, HTTP_100C, strlen(HTTP_100C));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004125 /* if ret == -2 or -3 the channel closed or the message si too
4126 * big for the buffers. We cant send anything. So, we ignoring
4127 * the error, considers that the 100-continue is sent, and try
4128 * to receive.
4129 * If ret is -1, we dont have room in the buffer, so we yield.
4130 */
4131 if (ret == -1) {
4132 si_applet_cant_put(si);
4133 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4134 }
4135 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4136 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004137
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004138 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004139 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004140
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004141 /* Data not yet avalaible. return yield. */
4142 if (ret == 0) {
4143 si_applet_cant_get(si);
4144 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4145 }
4146
4147 /* End of data: commit the total strings and return. */
4148 if (ret < 0) {
4149 luaL_pushresult(&appctx->b);
4150 return 1;
4151 }
4152
4153 /* Ensure that the block 2 length is usable. */
4154 if (ret == 1)
4155 len2 = 0;
4156
4157 /* Copy the fisrt block caping to the length required. */
4158 if (len1 > len)
4159 len1 = len;
4160 luaL_addlstring(&appctx->b, blk1, len1);
4161 len -= len1;
4162
4163 /* Copy the second block. */
4164 if (len2 > len)
4165 len2 = len;
4166 luaL_addlstring(&appctx->b, blk2, len2);
4167 len -= len2;
4168
4169 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004170 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004171 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
4172 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
4173
4174 /* If we are no other data avalaible, yield waiting for new data. */
4175 if (len > 0) {
4176 lua_pushinteger(L, len);
4177 lua_replace(L, 2);
4178 si_applet_cant_get(si);
4179 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4180 }
4181
4182 /* return the result. */
4183 luaL_pushresult(&appctx->b);
4184 return 1;
4185}
4186
4187/* Check arguments for the fucntion "hlua_channel_get_yield". */
4188__LJMP static int hlua_applet_http_recv(lua_State *L)
4189{
4190 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4191 int len = -1;
4192
4193 /* Check arguments. */
4194 if (lua_gettop(L) > 2)
4195 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4196 if (lua_gettop(L) >= 2) {
4197 len = MAY_LJMP(luaL_checkinteger(L, 2));
4198 lua_pop(L, 1);
4199 }
4200
4201 /* Check the required length */
4202 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4203 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4204 lua_pushinteger(L, len);
4205
4206 /* Initialise the string catenation. */
4207 luaL_buffinit(L, &appctx->b);
4208
4209 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4210}
4211
4212/* Append data in the output side of the buffer. This data is immediatly
4213 * sent. The fcuntion returns the ammount of data writed. If the buffer
4214 * cannot contains the data, the function yield. The function returns -1
4215 * if the channel is closed.
4216 */
4217__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4218{
4219 size_t len;
4220 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4221 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4222 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4223 struct stream_interface *si = appctx->appctx->owner;
4224 struct channel *chn = si_ic(si);
4225 int max;
4226
4227 /* Get the max amount of data which can write as input in the channel. */
4228 max = channel_recv_max(chn);
4229 if (max > (len - l))
4230 max = len - l;
4231
4232 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004233 ci_putblk(chn, str + l, max);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004234
4235 /* update counters. */
4236 l += max;
4237 lua_pop(L, 1);
4238 lua_pushinteger(L, l);
4239
4240 /* If some data is not send, declares the situation to the
4241 * applet, and returns a yield.
4242 */
4243 if (l < len) {
4244 si_applet_cant_put(si);
4245 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
4246 }
4247
4248 return 1;
4249}
4250
4251/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4252 * yield the LUA process, and resume it without checking the
4253 * input arguments.
4254 */
4255__LJMP static int hlua_applet_http_send(lua_State *L)
4256{
4257 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4258 size_t len;
4259 char hex[10];
4260
4261 MAY_LJMP(luaL_checklstring(L, 2, &len));
4262
4263 /* If transfer encoding chunked is selected, we surround the data
4264 * by chunk data.
4265 */
4266 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4267 snprintf(hex, 9, "%x", (unsigned int)len);
4268 lua_pushfstring(L, "%s\r\n", hex);
4269 lua_insert(L, 2); /* swap the last 2 entries. */
4270 lua_pushstring(L, "\r\n");
4271 lua_concat(L, 3);
4272 }
4273
4274 /* This interger is used for followinf the amount of data sent. */
4275 lua_pushinteger(L, 0);
4276
4277 /* We want to send some data. Headers must be sent. */
4278 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4279 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4280 WILL_LJMP(lua_error(L));
4281 }
4282
4283 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4284}
4285
4286__LJMP static int hlua_applet_http_addheader(lua_State *L)
4287{
4288 const char *name;
4289 int ret;
4290
4291 MAY_LJMP(hlua_checkapplet_http(L, 1));
4292 name = MAY_LJMP(luaL_checkstring(L, 2));
4293 MAY_LJMP(luaL_checkstring(L, 3));
4294
4295 /* Push in the stack the "response" entry. */
4296 ret = lua_getfield(L, 1, "response");
4297 if (ret != LUA_TTABLE) {
4298 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4299 "is expected as an array. %s found", lua_typename(L, ret));
4300 WILL_LJMP(lua_error(L));
4301 }
4302
4303 /* check if the header is already registered if it is not
4304 * the case, register it.
4305 */
4306 ret = lua_getfield(L, -1, name);
4307 if (ret == LUA_TNIL) {
4308
4309 /* Entry not found. */
4310 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4311
4312 /* Insert the new header name in the array in the top of the stack.
4313 * It left the new array in the top of the stack.
4314 */
4315 lua_newtable(L);
4316 lua_pushvalue(L, 2);
4317 lua_pushvalue(L, -2);
4318 lua_settable(L, -4);
4319
4320 } else if (ret != LUA_TTABLE) {
4321
4322 /* corruption error. */
4323 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4324 "is expected as an array. %s found", name, lua_typename(L, ret));
4325 WILL_LJMP(lua_error(L));
4326 }
4327
4328 /* Now the top od thestack is an array of values. We push
4329 * the header value as new entry.
4330 */
4331 lua_pushvalue(L, 3);
4332 ret = lua_rawlen(L, -2);
4333 lua_rawseti(L, -2, ret + 1);
4334 lua_pushboolean(L, 1);
4335 return 1;
4336}
4337
4338__LJMP static int hlua_applet_http_status(lua_State *L)
4339{
4340 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4341 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004342 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004343
4344 if (status < 100 || status > 599) {
4345 lua_pushboolean(L, 0);
4346 return 1;
4347 }
4348
4349 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004350 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004351 lua_pushboolean(L, 1);
4352 return 1;
4353}
4354
4355/* We will build the status line and the headers of the HTTP response.
4356 * We will try send at once if its not possible, we give back the hand
4357 * waiting for more room.
4358 */
4359__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4360{
4361 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4362 struct stream_interface *si = appctx->appctx->owner;
4363 struct channel *chn = si_ic(si);
4364 int ret;
4365 size_t len;
4366 const char *msg;
4367
4368 /* Get the message as the first argument on the stack. */
4369 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4370
4371 /* Send the message at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004372 ret = ci_putblk(chn, msg, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004373
4374 /* if ret == -2 or -3 the channel closed or the message si too
4375 * big for the buffers.
4376 */
4377 if (ret == -2 || ret == -3) {
4378 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4379 WILL_LJMP(lua_error(L));
4380 }
4381
4382 /* If ret is -1, we dont have room in the buffer, so we yield. */
4383 if (ret == -1) {
4384 si_applet_cant_put(si);
4385 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
4386 }
4387
4388 /* Headers sent, set the flag. */
4389 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4390 return 0;
4391}
4392
4393__LJMP static int hlua_applet_http_start_response(lua_State *L)
4394{
4395 struct chunk *tmp = get_trash_chunk();
4396 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004397 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02004398 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004399 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02004400 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004401 int id;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004402 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004403 int hdr_chunked = 0;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004404 const char *reason = appctx->appctx->ctx.hlua_apphttp.reason;
4405
4406 if (reason == NULL)
4407 reason = get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004408
4409 /* Use the same http version than the request. */
4410 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004411 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004412 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004413 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004414
4415 /* Get the array associated to the field "response" in the object AppletHTTP. */
4416 lua_pushvalue(L, 0);
4417 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4418 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4419 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4420 WILL_LJMP(lua_error(L));
4421 }
4422
4423 /* Browse the list of headers. */
4424 lua_pushnil(L);
4425 while(lua_next(L, -2) != 0) {
4426
4427 /* We expect a string as -2. */
4428 if (lua_type(L, -2) != LUA_TSTRING) {
4429 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4430 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4431 lua_typename(L, lua_type(L, -2)));
4432 WILL_LJMP(lua_error(L));
4433 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004434 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004435
4436 /* We expect an array as -1. */
4437 if (lua_type(L, -1) != LUA_TTABLE) {
4438 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4439 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4440 name,
4441 lua_typename(L, lua_type(L, -1)));
4442 WILL_LJMP(lua_error(L));
4443 }
4444
4445 /* Browse the table who is on the top of the stack. */
4446 lua_pushnil(L);
4447 while(lua_next(L, -2) != 0) {
4448
4449 /* We expect a number as -2. */
4450 if (lua_type(L, -2) != LUA_TNUMBER) {
4451 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4452 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4453 name,
4454 lua_typename(L, lua_type(L, -2)));
4455 WILL_LJMP(lua_error(L));
4456 }
4457 id = lua_tointeger(L, -2);
4458
4459 /* We expect a string as -2. */
4460 if (lua_type(L, -1) != LUA_TSTRING) {
4461 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4462 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4463 name, id,
4464 lua_typename(L, lua_type(L, -1)));
4465 WILL_LJMP(lua_error(L));
4466 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004467 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004468
4469 /* Catenate a new header. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004470 if (tmp->len + name_len + 2 + value_len + 2 < tmp->size) {
4471 memcpy(tmp->str + tmp->len, name, name_len);
4472 tmp->len += name_len;
4473 tmp->str[tmp->len++] = ':';
4474 tmp->str[tmp->len++] = ' ';
4475
4476 memcpy(tmp->str + tmp->len, value, value_len);
4477 tmp->len += value_len;
4478 tmp->str[tmp->len++] = '\r';
4479 tmp->str[tmp->len++] = '\n';
4480 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004481
4482 /* Protocol checks. */
4483
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004484 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004485 * is done without control. If it contains a bad value,
4486 * the content-length remains negative so that we can
4487 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004488 */
Willy Tarreaua3294632017-08-23 11:24:47 +02004489 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004490 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004491
4492 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004493 if (name_len == 17 && value_len == 7 &&
4494 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004495 strcasecmp("chunked", value) == 0)
4496 hdr_chunked = 1;
4497
4498 /* Remove the array from the stack, and get next element with a remaining string. */
4499 lua_pop(L, 1);
4500 }
4501
4502 /* Remove the array from the stack, and get next element with a remaining string. */
4503 lua_pop(L, 1);
4504 }
4505
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004506 /* If we dont have a content-length set, and the HTTP version is 1.1
4507 * and the status code implies the presence of a message body, we must
4508 * announce a transfer encoding chunked. This is required by haproxy
4509 * for the keepalive compliance. If the applet annouces a transfer-encoding
4510 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004511 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004512 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004513 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
4514 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4515 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4516 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004517 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4518 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4519 }
4520
4521 /* Finalize headers. */
4522 chunk_appendf(tmp, "\r\n");
4523
4524 /* Remove the last entry and the array of headers */
4525 lua_pop(L, 2);
4526
4527 /* Push the headers block. */
4528 lua_pushlstring(L, tmp->str, tmp->len);
4529
4530 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4531}
4532
4533/*
4534 *
4535 *
4536 * Class HTTP
4537 *
4538 *
4539 */
4540
4541/* Returns a struct hlua_txn if the stack entry "ud" is
4542 * a class stream, otherwise it throws an error.
4543 */
4544__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4545{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004546 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004547}
4548
4549/* This function creates and push in the stack a HTTP object
4550 * according with a current TXN.
4551 */
4552static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4553{
4554 struct hlua_txn *htxn;
4555
4556 /* Check stack size. */
4557 if (!lua_checkstack(L, 3))
4558 return 0;
4559
4560 /* Create the object: obj[0] = userdata.
4561 * Note that the base of the Converters object is the
4562 * same than the TXN object.
4563 */
4564 lua_newtable(L);
4565 htxn = lua_newuserdata(L, sizeof(*htxn));
4566 lua_rawseti(L, -2, 0);
4567
4568 htxn->s = txn->s;
4569 htxn->p = txn->p;
4570
4571 /* Pop a class stream metatable and affect it to the table. */
4572 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4573 lua_setmetatable(L, -2);
4574
4575 return 1;
4576}
4577
4578/* This function creates ans returns an array of HTTP headers.
4579 * This function does not fails. It is used as wrapper with the
4580 * 2 following functions.
4581 */
4582__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4583{
4584 const char *cur_ptr, *cur_next, *p;
4585 int old_idx, cur_idx;
4586 struct hdr_idx_elem *cur_hdr;
4587 const char *hn, *hv;
4588 int hnl, hvl;
4589 int type;
4590 const char *in;
4591 char *out;
4592 int len;
4593
4594 /* Create the table. */
4595 lua_newtable(L);
4596
4597 if (!htxn->s->txn)
4598 return 1;
4599
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004600 /* Check if a valid response is parsed */
4601 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4602 return 1;
4603
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004604 /* Build array of headers. */
4605 old_idx = 0;
4606 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4607
4608 while (1) {
4609 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4610 if (!cur_idx)
4611 break;
4612 old_idx = cur_idx;
4613
4614 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4615 cur_ptr = cur_next;
4616 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4617
4618 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4619 * and the next header starts at cur_next. We'll check
4620 * this header in the list as well as against the default
4621 * rule.
4622 */
4623
4624 /* look for ': *'. */
4625 hn = cur_ptr;
4626 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4627 if (p >= cur_ptr+cur_hdr->len)
4628 continue;
4629 hnl = p - hn;
4630 p++;
4631 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4632 p++;
4633 if (p >= cur_ptr+cur_hdr->len)
4634 continue;
4635 hv = p;
4636 hvl = cur_ptr+cur_hdr->len-p;
4637
4638 /* Lowercase the key. Don't check the size of trash, it have
4639 * the size of one buffer and the input data contains in one
4640 * buffer.
4641 */
4642 out = trash.str;
4643 for (in=hn; in<hn+hnl; in++, out++)
4644 *out = tolower(*in);
4645 *out = '\0';
4646
4647 /* Check for existing entry:
4648 * assume that the table is on the top of the stack, and
4649 * push the key in the stack, the function lua_gettable()
4650 * perform the lookup.
4651 */
4652 lua_pushlstring(L, trash.str, hnl);
4653 lua_gettable(L, -2);
4654 type = lua_type(L, -1);
4655
4656 switch (type) {
4657 case LUA_TNIL:
4658 /* Table not found, create it. */
4659 lua_pop(L, 1); /* remove the nil value. */
4660 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4661 lua_newtable(L); /* create and push empty table. */
4662 lua_pushlstring(L, hv, hvl); /* push header value. */
4663 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4664 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4665 break;
4666
4667 case LUA_TTABLE:
4668 /* Entry found: push the value in the table. */
4669 len = lua_rawlen(L, -1);
4670 lua_pushlstring(L, hv, hvl); /* push header value. */
4671 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4672 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4673 break;
4674
4675 default:
4676 /* Other cases are errors. */
4677 hlua_pusherror(L, "internal error during the parsing of headers.");
4678 WILL_LJMP(lua_error(L));
4679 }
4680 }
4681
4682 return 1;
4683}
4684
4685__LJMP static int hlua_http_req_get_headers(lua_State *L)
4686{
4687 struct hlua_txn *htxn;
4688
4689 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4690 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4691
4692 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4693}
4694
4695__LJMP static int hlua_http_res_get_headers(lua_State *L)
4696{
4697 struct hlua_txn *htxn;
4698
4699 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4700 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4701
4702 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4703}
4704
4705/* This function replace full header, or just a value in
4706 * the request or in the response. It is a wrapper fir the
4707 * 4 following functions.
4708 */
4709__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4710 struct http_msg *msg, int action)
4711{
4712 size_t name_len;
4713 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4714 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4715 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4716 struct my_regex re;
4717
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004718 /* Check if a valid response is parsed */
4719 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4720 return 0;
4721
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004722 if (!regex_comp(reg, &re, 1, 1, NULL))
4723 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4724
4725 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4726 regex_free(&re);
4727 return 0;
4728}
4729
4730__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4731{
4732 struct hlua_txn *htxn;
4733
4734 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4735 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4736
4737 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4738}
4739
4740__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4741{
4742 struct hlua_txn *htxn;
4743
4744 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4745 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4746
4747 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4748}
4749
4750__LJMP static int hlua_http_req_rep_val(lua_State *L)
4751{
4752 struct hlua_txn *htxn;
4753
4754 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4755 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4756
4757 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4758}
4759
4760__LJMP static int hlua_http_res_rep_val(lua_State *L)
4761{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004762 struct hlua_txn *htxn;
4763
4764 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4765 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4766
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004767 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004768}
4769
4770/* This function deletes all the occurences of an header.
4771 * It is a wrapper for the 2 following functions.
4772 */
4773__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4774{
4775 size_t len;
4776 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4777 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004778 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004779
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004780 /* Check if a valid response is parsed */
4781 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4782 return 0;
4783
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004784 ctx.idx = 0;
4785 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4786 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4787 return 0;
4788}
4789
4790__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4791{
4792 struct hlua_txn *htxn;
4793
4794 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4795 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4796
Willy Tarreaueee5b512015-04-03 23:46:31 +02004797 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004798}
4799
4800__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4801{
4802 struct hlua_txn *htxn;
4803
4804 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4805 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4806
Willy Tarreaueee5b512015-04-03 23:46:31 +02004807 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004808}
4809
4810/* This function adds an header. It is a wrapper used by
4811 * the 2 following functions.
4812 */
4813__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4814{
4815 size_t name_len;
4816 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4817 size_t value_len;
4818 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4819 char *p;
4820
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004821 /* Check if a valid message is parsed */
4822 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4823 return 0;
4824
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004825 /* Check length. */
4826 trash.len = value_len + name_len + 2;
4827 if (trash.len > trash.size)
4828 return 0;
4829
4830 /* Creates the header string. */
4831 p = trash.str;
4832 memcpy(p, name, name_len);
4833 p += name_len;
4834 *p = ':';
4835 p++;
4836 *p = ' ';
4837 p++;
4838 memcpy(p, value, value_len);
4839
Willy Tarreaueee5b512015-04-03 23:46:31 +02004840 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004841 trash.str, trash.len) != 0);
4842
4843 return 0;
4844}
4845
4846__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4847{
4848 struct hlua_txn *htxn;
4849
4850 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4851 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4852
Willy Tarreaueee5b512015-04-03 23:46:31 +02004853 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004854}
4855
4856__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4857{
4858 struct hlua_txn *htxn;
4859
4860 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4861 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4862
Willy Tarreaueee5b512015-04-03 23:46:31 +02004863 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004864}
4865
4866static int hlua_http_req_set_hdr(lua_State *L)
4867{
4868 struct hlua_txn *htxn;
4869
4870 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4871 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4872
Willy Tarreaueee5b512015-04-03 23:46:31 +02004873 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4874 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004875}
4876
4877static int hlua_http_res_set_hdr(lua_State *L)
4878{
4879 struct hlua_txn *htxn;
4880
4881 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4882 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4883
Willy Tarreaueee5b512015-04-03 23:46:31 +02004884 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4885 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004886}
4887
4888/* This function set the method. */
4889static int hlua_http_req_set_meth(lua_State *L)
4890{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004891 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004892 size_t name_len;
4893 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004894
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004895 /* Check if a valid request is parsed */
4896 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4897 lua_pushboolean(L, 0);
4898 return 1;
4899 }
4900
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004901 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004902 return 1;
4903}
4904
4905/* This function set the method. */
4906static int hlua_http_req_set_path(lua_State *L)
4907{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004908 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004909 size_t name_len;
4910 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004911
4912 /* Check if a valid request is parsed */
4913 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4914 lua_pushboolean(L, 0);
4915 return 1;
4916 }
4917
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004918 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004919 return 1;
4920}
4921
4922/* This function set the query-string. */
4923static int hlua_http_req_set_query(lua_State *L)
4924{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004925 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004926 size_t name_len;
4927 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004928
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004929 /* Check if a valid request is parsed */
4930 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4931 lua_pushboolean(L, 0);
4932 return 1;
4933 }
4934
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004935 /* Check length. */
4936 if (name_len > trash.size - 1) {
4937 lua_pushboolean(L, 0);
4938 return 1;
4939 }
4940
4941 /* Add the mark question as prefix. */
4942 chunk_reset(&trash);
4943 trash.str[trash.len++] = '?';
4944 memcpy(trash.str + trash.len, name, name_len);
4945 trash.len += name_len;
4946
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004947 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004948 return 1;
4949}
4950
4951/* This function set the uri. */
4952static int hlua_http_req_set_uri(lua_State *L)
4953{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004954 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004955 size_t name_len;
4956 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004957
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004958 /* Check if a valid request is parsed */
4959 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4960 lua_pushboolean(L, 0);
4961 return 1;
4962 }
4963
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004964 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004965 return 1;
4966}
4967
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004968/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004969static int hlua_http_res_set_status(lua_State *L)
4970{
4971 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4972 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004973 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004974
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004975 /* Check if a valid response is parsed */
4976 if (unlikely(htxn->s->txn->rsp.msg_state < HTTP_MSG_BODY))
4977 return 0;
4978
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004979 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004980 return 0;
4981}
4982
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004983/*
4984 *
4985 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004986 * Class TXN
4987 *
4988 *
4989 */
4990
4991/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004992 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004993 */
4994__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
4995{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004996 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004997}
4998
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004999__LJMP static int hlua_set_var(lua_State *L)
5000{
5001 struct hlua_txn *htxn;
5002 const char *name;
5003 size_t len;
5004 struct sample smp;
5005
5006 MAY_LJMP(check_args(L, 3, "set_var"));
5007
5008 /* It is useles to retrieve the stream, but this function
5009 * runs only in a stream context.
5010 */
5011 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5012 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5013
5014 /* Converts the third argument in a sample. */
5015 hlua_lua2smp(L, 3, &smp);
5016
5017 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005018 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005019 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005020 return 0;
5021}
5022
Christopher Faulet85d79c92016-11-09 16:54:56 +01005023__LJMP static int hlua_unset_var(lua_State *L)
5024{
5025 struct hlua_txn *htxn;
5026 const char *name;
5027 size_t len;
5028 struct sample smp;
5029
5030 MAY_LJMP(check_args(L, 2, "unset_var"));
5031
5032 /* It is useles to retrieve the stream, but this function
5033 * runs only in a stream context.
5034 */
5035 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5036 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5037
5038 /* Unset the variable. */
5039 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
5040 vars_unset_by_name(name, len, &smp);
5041 return 0;
5042}
5043
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005044__LJMP static int hlua_get_var(lua_State *L)
5045{
5046 struct hlua_txn *htxn;
5047 const char *name;
5048 size_t len;
5049 struct sample smp;
5050
5051 MAY_LJMP(check_args(L, 2, "get_var"));
5052
5053 /* It is useles to retrieve the stream, but this function
5054 * runs only in a stream context.
5055 */
5056 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5057 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5058
Willy Tarreau7560dd42016-03-10 16:28:58 +01005059 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005060 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005061 lua_pushnil(L);
5062 return 1;
5063 }
5064
5065 return hlua_smp2lua(L, &smp);
5066}
5067
Willy Tarreau59551662015-03-10 14:23:13 +01005068__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005069{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005070 struct hlua *hlua;
5071
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005072 MAY_LJMP(check_args(L, 2, "set_priv"));
5073
Willy Tarreau87b09662015-04-03 00:22:06 +02005074 /* It is useles to retrieve the stream, but this function
5075 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005076 */
5077 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005078 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005079
5080 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005081 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005082
5083 /* Get and store new value. */
5084 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5085 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5086
5087 return 0;
5088}
5089
Willy Tarreau59551662015-03-10 14:23:13 +01005090__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005091{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005092 struct hlua *hlua;
5093
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005094 MAY_LJMP(check_args(L, 1, "get_priv"));
5095
Willy Tarreau87b09662015-04-03 00:22:06 +02005096 /* It is useles to retrieve the stream, but this function
5097 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005098 */
5099 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005100 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005101
5102 /* Push configuration index in the stack. */
5103 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5104
5105 return 1;
5106}
5107
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005108/* Create stack entry containing a class TXN. This function
5109 * return 0 if the stack does not contains free slots,
5110 * otherwise it returns 1.
5111 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005112static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005113{
Willy Tarreaude491382015-04-06 11:04:28 +02005114 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005115
5116 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005117 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005118 return 0;
5119
5120 /* NOTE: The allocation never fails. The failure
5121 * throw an error, and the function never returns.
5122 * if the throw is not avalaible, the process is aborted.
5123 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005124 /* Create the object: obj[0] = userdata. */
5125 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005126 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005127 lua_rawseti(L, -2, 0);
5128
Willy Tarreaude491382015-04-06 11:04:28 +02005129 htxn->s = s;
5130 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005131 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005132 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005133
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005134 /* Create the "f" field that contains a list of fetches. */
5135 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005136 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005137 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005138 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005139
5140 /* Create the "sf" field that contains a list of stringsafe fetches. */
5141 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005142 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005143 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005144 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005145
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005146 /* Create the "c" field that contains a list of converters. */
5147 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005148 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005149 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005150 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005151
5152 /* Create the "sc" field that contains a list of stringsafe converters. */
5153 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005154 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005155 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005156 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005157
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005158 /* Create the "req" field that contains the request channel object. */
5159 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005160 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005161 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005162 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005163
5164 /* Create the "res" field that contains the response channel object. */
5165 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005166 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005167 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005168 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005169
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005170 /* Creates the HTTP object is the current proxy allows http. */
5171 lua_pushstring(L, "http");
5172 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005173 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005174 return 0;
5175 }
5176 else
5177 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005178 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005179
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005180 /* Pop a class sesison metatable and affect it to the userdata. */
5181 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5182 lua_setmetatable(L, -2);
5183
5184 return 1;
5185}
5186
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005187__LJMP static int hlua_txn_deflog(lua_State *L)
5188{
5189 const char *msg;
5190 struct hlua_txn *htxn;
5191
5192 MAY_LJMP(check_args(L, 2, "deflog"));
5193 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5194 msg = MAY_LJMP(luaL_checkstring(L, 2));
5195
5196 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5197 return 0;
5198}
5199
5200__LJMP static int hlua_txn_log(lua_State *L)
5201{
5202 int level;
5203 const char *msg;
5204 struct hlua_txn *htxn;
5205
5206 MAY_LJMP(check_args(L, 3, "log"));
5207 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5208 level = MAY_LJMP(luaL_checkinteger(L, 2));
5209 msg = MAY_LJMP(luaL_checkstring(L, 3));
5210
5211 if (level < 0 || level >= NB_LOG_LEVELS)
5212 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5213
5214 hlua_sendlog(htxn->s->be, level, msg);
5215 return 0;
5216}
5217
5218__LJMP static int hlua_txn_log_debug(lua_State *L)
5219{
5220 const char *msg;
5221 struct hlua_txn *htxn;
5222
5223 MAY_LJMP(check_args(L, 2, "Debug"));
5224 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5225 msg = MAY_LJMP(luaL_checkstring(L, 2));
5226 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5227 return 0;
5228}
5229
5230__LJMP static int hlua_txn_log_info(lua_State *L)
5231{
5232 const char *msg;
5233 struct hlua_txn *htxn;
5234
5235 MAY_LJMP(check_args(L, 2, "Info"));
5236 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5237 msg = MAY_LJMP(luaL_checkstring(L, 2));
5238 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5239 return 0;
5240}
5241
5242__LJMP static int hlua_txn_log_warning(lua_State *L)
5243{
5244 const char *msg;
5245 struct hlua_txn *htxn;
5246
5247 MAY_LJMP(check_args(L, 2, "Warning"));
5248 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5249 msg = MAY_LJMP(luaL_checkstring(L, 2));
5250 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5251 return 0;
5252}
5253
5254__LJMP static int hlua_txn_log_alert(lua_State *L)
5255{
5256 const char *msg;
5257 struct hlua_txn *htxn;
5258
5259 MAY_LJMP(check_args(L, 2, "Alert"));
5260 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5261 msg = MAY_LJMP(luaL_checkstring(L, 2));
5262 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5263 return 0;
5264}
5265
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005266__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5267{
5268 struct hlua_txn *htxn;
5269 int ll;
5270
5271 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5272 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5273 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5274
5275 if (ll < 0 || ll > 7)
5276 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5277
5278 htxn->s->logs.level = ll;
5279 return 0;
5280}
5281
5282__LJMP static int hlua_txn_set_tos(lua_State *L)
5283{
5284 struct hlua_txn *htxn;
5285 struct connection *cli_conn;
5286 int tos;
5287
5288 MAY_LJMP(check_args(L, 2, "set_tos"));
5289 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5290 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5291
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005292 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005293 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005294
5295 return 0;
5296}
5297
5298__LJMP static int hlua_txn_set_mark(lua_State *L)
5299{
5300#ifdef SO_MARK
5301 struct hlua_txn *htxn;
5302 struct connection *cli_conn;
5303 int mark;
5304
5305 MAY_LJMP(check_args(L, 2, "set_mark"));
5306 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5307 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5308
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005309 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005310 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005311#endif
5312 return 0;
5313}
5314
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005315/* This function is an Lua binding that send pending data
5316 * to the client, and close the stream interface.
5317 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005318__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005319{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005320 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005321 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01005322 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005323
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005324 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005325 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005326 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005327
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005328 /* If the flags NOTERM is set, we cannot terminate the http
5329 * session, so we just end the execution of the current
5330 * lua code.
5331 */
5332 if (htxn->flags & HLUA_TXN_NOTERM) {
5333 WILL_LJMP(hlua_done(L));
5334 return 0;
5335 }
5336
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005337 ic = &htxn->s->req;
5338 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005339
Willy Tarreau630ef452015-08-28 10:06:15 +02005340 if (htxn->s->txn) {
5341 /* HTTP mode, let's stay in sync with the stream */
5342 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
5343 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
5344 htxn->s->txn->req.sov = 0;
5345 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
5346 oc->analysers = AN_RES_HTTP_XFER_BODY;
5347 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
5348 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
5349
Willy Tarreau630ef452015-08-28 10:06:15 +02005350 /* Note that if we want to support keep-alive, we need
5351 * to bypass the close/shutr_now calls below, but that
5352 * may only be done if the HTTP request was already
5353 * processed and the connection header is known (ie
5354 * not during TCP rules).
5355 */
5356 }
5357
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005358 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01005359 channel_abort(ic);
5360 channel_auto_close(ic);
5361 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005362
5363 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01005364 channel_auto_read(oc);
5365 channel_auto_close(oc);
5366 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005367
Willy Tarreau0458b082015-08-28 09:40:04 +02005368 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005369
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005370 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005371 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005372 return 0;
5373}
5374
5375__LJMP static int hlua_log(lua_State *L)
5376{
5377 int level;
5378 const char *msg;
5379
5380 MAY_LJMP(check_args(L, 2, "log"));
5381 level = MAY_LJMP(luaL_checkinteger(L, 1));
5382 msg = MAY_LJMP(luaL_checkstring(L, 2));
5383
5384 if (level < 0 || level >= NB_LOG_LEVELS)
5385 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5386
5387 hlua_sendlog(NULL, level, msg);
5388 return 0;
5389}
5390
5391__LJMP static int hlua_log_debug(lua_State *L)
5392{
5393 const char *msg;
5394
5395 MAY_LJMP(check_args(L, 1, "debug"));
5396 msg = MAY_LJMP(luaL_checkstring(L, 1));
5397 hlua_sendlog(NULL, LOG_DEBUG, msg);
5398 return 0;
5399}
5400
5401__LJMP static int hlua_log_info(lua_State *L)
5402{
5403 const char *msg;
5404
5405 MAY_LJMP(check_args(L, 1, "info"));
5406 msg = MAY_LJMP(luaL_checkstring(L, 1));
5407 hlua_sendlog(NULL, LOG_INFO, msg);
5408 return 0;
5409}
5410
5411__LJMP static int hlua_log_warning(lua_State *L)
5412{
5413 const char *msg;
5414
5415 MAY_LJMP(check_args(L, 1, "warning"));
5416 msg = MAY_LJMP(luaL_checkstring(L, 1));
5417 hlua_sendlog(NULL, LOG_WARNING, msg);
5418 return 0;
5419}
5420
5421__LJMP static int hlua_log_alert(lua_State *L)
5422{
5423 const char *msg;
5424
5425 MAY_LJMP(check_args(L, 1, "alert"));
5426 msg = MAY_LJMP(luaL_checkstring(L, 1));
5427 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005428 return 0;
5429}
5430
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005431__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005432{
5433 int wakeup_ms = lua_tointeger(L, -1);
5434 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005435 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005436 return 0;
5437}
5438
5439__LJMP static int hlua_sleep(lua_State *L)
5440{
5441 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005442 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005443
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005444 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005445
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005446 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005447 wakeup_ms = tick_add(now_ms, delay);
5448 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005449
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005450 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5451 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005452}
5453
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005454__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005455{
5456 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005457 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005458
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005459 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005460
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005461 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005462 wakeup_ms = tick_add(now_ms, delay);
5463 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005464
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005465 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5466 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005467}
5468
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005469/* This functionis an LUA binding. it permits to give back
5470 * the hand at the HAProxy scheduler. It is used when the
5471 * LUA processing consumes a lot of time.
5472 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005473__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005474{
5475 return 0;
5476}
5477
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005478__LJMP static int hlua_yield(lua_State *L)
5479{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005480 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
5481 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005482}
5483
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005484/* This function change the nice of the currently executed
5485 * task. It is used set low or high priority at the current
5486 * task.
5487 */
Willy Tarreau59551662015-03-10 14:23:13 +01005488__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005489{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005490 struct hlua *hlua;
5491 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005492
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005493 MAY_LJMP(check_args(L, 1, "set_nice"));
5494 hlua = hlua_gethlua(L);
5495 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005496
5497 /* If he task is not set, I'm in a start mode. */
5498 if (!hlua || !hlua->task)
5499 return 0;
5500
5501 if (nice < -1024)
5502 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005503 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005504 nice = 1024;
5505
5506 hlua->task->nice = nice;
5507 return 0;
5508}
5509
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005510/* This function is used as a calback of a task. It is called by the
5511 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5512 * return an E_AGAIN signal, the emmiter of this signal must set a
5513 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005514 *
5515 * Task wrapper are longjmp safe because the only one Lua code
5516 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005517 */
5518static struct task *hlua_process_task(struct task *task)
5519{
5520 struct hlua *hlua = task->context;
5521 enum hlua_exec status;
5522
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005523 /* If it is the first call to the task, we must initialize the
5524 * execution timeouts.
5525 */
5526 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005527 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005528
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005529 /* Execute the Lua code. */
5530 status = hlua_ctx_resume(hlua, 1);
5531
5532 switch (status) {
5533 /* finished or yield */
5534 case HLUA_E_OK:
5535 hlua_ctx_destroy(hlua);
5536 task_delete(task);
5537 task_free(task);
5538 break;
5539
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005540 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01005541 notification_gc(&hlua->com);
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005542 if (hlua->wake_time != TICK_ETERNITY)
Emeric Brun253e53e2017-10-17 18:58:40 +02005543 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005544 break;
5545
5546 /* finished with error. */
5547 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005548 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005549 hlua_ctx_destroy(hlua);
5550 task_delete(task);
5551 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02005552 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005553 break;
5554
5555 case HLUA_E_ERR:
5556 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005557 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005558 hlua_ctx_destroy(hlua);
5559 task_delete(task);
5560 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02005561 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005562 break;
5563 }
Emeric Brun253e53e2017-10-17 18:58:40 +02005564 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005565}
5566
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005567/* This function is an LUA binding that register LUA function to be
5568 * executed after the HAProxy configuration parsing and before the
5569 * HAProxy scheduler starts. This function expect only one LUA
5570 * argument that is a function. This function returns nothing, but
5571 * throws if an error is encountered.
5572 */
5573__LJMP static int hlua_register_init(lua_State *L)
5574{
5575 struct hlua_init_function *init;
5576 int ref;
5577
5578 MAY_LJMP(check_args(L, 1, "register_init"));
5579
5580 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5581
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005582 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005583 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005584 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005585
5586 init->function_ref = ref;
5587 LIST_ADDQ(&hlua_init_functions, &init->l);
5588 return 0;
5589}
5590
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005591/* This functio is an LUA binding. It permits to register a task
5592 * executed in parallel of the main HAroxy activity. The task is
5593 * created and it is set in the HAProxy scheduler. It can be called
5594 * from the "init" section, "post init" or during the runtime.
5595 *
5596 * Lua prototype:
5597 *
5598 * <none> core.register_task(<function>)
5599 */
5600static int hlua_register_task(lua_State *L)
5601{
5602 struct hlua *hlua;
5603 struct task *task;
5604 int ref;
5605
5606 MAY_LJMP(check_args(L, 1, "register_task"));
5607
5608 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5609
Willy Tarreaubafbe012017-11-24 17:34:44 +01005610 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005611 if (!hlua)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005612 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005613
Emeric Brunc60def82017-09-27 14:59:38 +02005614 task = task_new(MAX_THREADS_MASK);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005615 task->context = hlua;
5616 task->process = hlua_process_task;
5617
5618 if (!hlua_ctx_init(hlua, task))
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005619 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005620
5621 /* Restore the function in the stack. */
5622 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5623 hlua->nargs = 0;
5624
5625 /* Schedule task. */
5626 task_schedule(task, now_ms);
5627
5628 return 0;
5629}
5630
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005631/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5632 * doesn't allow "yield" functions because the HAProxy engine cannot
5633 * resume converters.
5634 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005635static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005636{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005637 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005638 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005639 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005640
Willy Tarreaube508f12016-03-10 11:47:01 +01005641 if (!stream)
5642 return 0;
5643
Willy Tarreau87b09662015-04-03 00:22:06 +02005644 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005645 * Lua context can be not initialized. This behavior
5646 * permits to save performances because a systematic
5647 * Lua initialization cause 5% performances loss.
5648 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005649 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005650 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005651 if (!stream->hlua) {
5652 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5653 return 0;
5654 }
5655 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5656 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5657 return 0;
5658 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005659 }
5660
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005661 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005662 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005663
5664 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005665 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5666 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5667 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005668 else
5669 error = "critical error";
5670 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005671 return 0;
5672 }
5673
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005674 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005675 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005676 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005677 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005678 return 0;
5679 }
5680
5681 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005682 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005683
5684 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005685 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005686 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005687 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005688 return 0;
5689 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005690 hlua_smp2lua(stream->hlua->T, smp);
5691 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005692
5693 /* push keywords in the stack. */
5694 if (arg_p) {
5695 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005696 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005697 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005698 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005699 return 0;
5700 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005701 hlua_arg2lua(stream->hlua->T, arg_p);
5702 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005703 }
5704 }
5705
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005706 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005707 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005708
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005709 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005710 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005711 }
5712
5713 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005714 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005715 /* finished. */
5716 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005717 /* If the stack is empty, the function fails. */
5718 if (lua_gettop(stream->hlua->T) <= 0)
5719 return 0;
5720
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005721 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005722 hlua_lua2smp(stream->hlua->T, -1, smp);
5723 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005724 return 1;
5725
5726 /* yield. */
5727 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005728 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005729 return 0;
5730
5731 /* finished with error. */
5732 case HLUA_E_ERRMSG:
5733 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005734 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005735 fcn->name, lua_tostring(stream->hlua->T, -1));
5736 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005737 return 0;
5738
5739 case HLUA_E_ERR:
5740 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005741 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005742
5743 default:
5744 return 0;
5745 }
5746}
5747
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005748/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5749 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005750 * resume sample-fetches. This function will be called by the sample
5751 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005752 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005753static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5754 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005755{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005756 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005757 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005758 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005759 const struct chunk msg = { .len = 0 };
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005760
Willy Tarreaube508f12016-03-10 11:47:01 +01005761 if (!stream)
5762 return 0;
5763
Willy Tarreau87b09662015-04-03 00:22:06 +02005764 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005765 * Lua context can be not initialized. This behavior
5766 * permits to save performances because a systematic
5767 * Lua initialization cause 5% performances loss.
5768 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005769 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005770 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005771 if (!stream->hlua) {
5772 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5773 return 0;
5774 }
5775 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5776 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5777 return 0;
5778 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005779 }
5780
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005781 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005782
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005783 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005784 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005785
5786 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005787 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5788 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5789 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005790 else
5791 error = "critical error";
5792 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005793 return 0;
5794 }
5795
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005796 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005797 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005798 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005799 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005800 return 0;
5801 }
5802
5803 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005804 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005805
5806 /* push arguments in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005807 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR,
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005808 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005809 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005810 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005811 return 0;
5812 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005813 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005814
5815 /* push keywords in the stack. */
5816 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5817 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005818 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005819 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005820 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005821 return 0;
5822 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005823 hlua_arg2lua(stream->hlua->T, arg_p);
5824 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005825 }
5826
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005827 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005828 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005829
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005830 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005831 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005832 }
5833
5834 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005835 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005836 /* finished. */
5837 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005838 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005839 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005840 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005841 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005842 /* If the stack is empty, the function fails. */
5843 if (lua_gettop(stream->hlua->T) <= 0)
5844 return 0;
5845
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005846 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005847 hlua_lua2smp(stream->hlua->T, -1, smp);
5848 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005849
5850 /* Set the end of execution flag. */
5851 smp->flags &= ~SMP_F_MAY_CHANGE;
5852 return 1;
5853
5854 /* yield. */
5855 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005856 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005857 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005858 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005859 return 0;
5860
5861 /* finished with error. */
5862 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005863 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005864 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005865 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005866 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005867 fcn->name, lua_tostring(stream->hlua->T, -1));
5868 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005869 return 0;
5870
5871 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005872 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005873 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005874 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005875 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005876
5877 default:
5878 return 0;
5879 }
5880}
5881
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005882/* This function is an LUA binding used for registering
5883 * "sample-conv" functions. It expects a converter name used
5884 * in the haproxy configuration file, and an LUA function.
5885 */
5886__LJMP static int hlua_register_converters(lua_State *L)
5887{
5888 struct sample_conv_kw_list *sck;
5889 const char *name;
5890 int ref;
5891 int len;
5892 struct hlua_function *fcn;
5893
5894 MAY_LJMP(check_args(L, 2, "register_converters"));
5895
5896 /* First argument : converter name. */
5897 name = MAY_LJMP(luaL_checkstring(L, 1));
5898
5899 /* Second argument : lua function. */
5900 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5901
5902 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005903 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005904 if (!sck)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005905 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005906 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005907 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005908 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005909
5910 /* Fill fcn. */
5911 fcn->name = strdup(name);
5912 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005913 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005914 fcn->function_ref = ref;
5915
5916 /* List head */
5917 sck->list.n = sck->list.p = NULL;
5918
5919 /* converter keyword. */
5920 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005921 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005922 if (!sck->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005923 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005924
5925 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5926 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005927 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 +01005928 sck->kw[0].val_args = NULL;
5929 sck->kw[0].in_type = SMP_T_STR;
5930 sck->kw[0].out_type = SMP_T_STR;
5931 sck->kw[0].private = fcn;
5932
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005933 /* Register this new converter */
5934 sample_register_convs(sck);
5935
5936 return 0;
5937}
5938
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005939/* This fucntion is an LUA binding used for registering
5940 * "sample-fetch" functions. It expects a converter name used
5941 * in the haproxy configuration file, and an LUA function.
5942 */
5943__LJMP static int hlua_register_fetches(lua_State *L)
5944{
5945 const char *name;
5946 int ref;
5947 int len;
5948 struct sample_fetch_kw_list *sfk;
5949 struct hlua_function *fcn;
5950
5951 MAY_LJMP(check_args(L, 2, "register_fetches"));
5952
5953 /* First argument : sample-fetch name. */
5954 name = MAY_LJMP(luaL_checkstring(L, 1));
5955
5956 /* Second argument : lua function. */
5957 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5958
5959 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005960 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005961 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005962 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005963 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005964 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005965 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005966
5967 /* Fill fcn. */
5968 fcn->name = strdup(name);
5969 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005970 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005971 fcn->function_ref = ref;
5972
5973 /* List head */
5974 sfk->list.n = sfk->list.p = NULL;
5975
5976 /* sample-fetch keyword. */
5977 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005978 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005979 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005980 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005981
5982 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
5983 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005984 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 +01005985 sfk->kw[0].val_args = NULL;
5986 sfk->kw[0].out_type = SMP_T_STR;
5987 sfk->kw[0].use = SMP_USE_HTTP_ANY;
5988 sfk->kw[0].val = 0;
5989 sfk->kw[0].private = fcn;
5990
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005991 /* Register this new fetch. */
5992 sample_register_fetches(sfk);
5993
5994 return 0;
5995}
5996
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005997/* This function is a wrapper to execute each LUA function declared
5998 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005999 * return ACT_RET_CONT if the processing is finished (with or without
6000 * error) and return ACT_RET_YIELD if the function must be called again
6001 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006002 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006003static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006004 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006005{
6006 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006007 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006008 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006009 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006010 const struct chunk msg = { .len = 0 };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006011
6012 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01006013 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
6014 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
6015 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
6016 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006017 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006018 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006019 return ACT_RET_CONT;
6020 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006021
Willy Tarreau87b09662015-04-03 00:22:06 +02006022 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006023 * Lua context can be not initialized. This behavior
6024 * permits to save performances because a systematic
6025 * Lua initialization cause 5% performances loss.
6026 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006027 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006028 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006029 if (!s->hlua) {
6030 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6031 rule->arg.hlua_rule->fcn.name);
6032 return ACT_RET_CONT;
6033 }
6034 if (!hlua_ctx_init(s->hlua, s->task)) {
6035 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6036 rule->arg.hlua_rule->fcn.name);
6037 return ACT_RET_CONT;
6038 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006039 }
6040
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006041 consistency_set(s, dir, &s->hlua->cons);
6042
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006043 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006044 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006045
6046 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006047 if (!SET_SAFE_LJMP(s->hlua->T)) {
6048 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6049 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006050 else
6051 error = "critical error";
6052 SEND_ERR(px, "Lua function '%s': %s.\n",
6053 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006054 return ACT_RET_CONT;
6055 }
6056
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006057 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006058 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006059 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006060 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006061 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006062 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006063 }
6064
6065 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006066 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006067
Willy Tarreau87b09662015-04-03 00:22:06 +02006068 /* Create and and push object stream in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006069 if (!hlua_txn_new(s->hlua->T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006070 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006071 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006072 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006073 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006074 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006075 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006076
6077 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006078 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006079 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006080 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006081 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006082 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006083 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006084 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006085 lua_pushstring(s->hlua->T, *arg);
6086 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006087 }
6088
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006089 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006090 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006091
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006092 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006093 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006094 }
6095
6096 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006097 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006098 /* finished. */
6099 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006100 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006101 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006102 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006103 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006104 if (s->hlua->flags & HLUA_STOP)
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006105 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006106 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006107
6108 /* yield. */
6109 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006110 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006111 if (s->hlua->wake_time != TICK_ETERNITY) {
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006112 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006113 s->req.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006114 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006115 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006116 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006117 /* Some actions can be wake up when a "write" event
6118 * is detected on a response channel. This is useful
6119 * only for actions targetted on the requests.
6120 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006121 if (HLUA_IS_WAKERESWR(s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006122 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01006123 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006124 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006125 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006126 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006127 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006128 /* We can quit the fcuntion without consistency check
6129 * because HAProxy is not able to manipulate data, it
6130 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006131 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006132
6133 /* finished with error. */
6134 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006135 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006136 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006137 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006138 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006139 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006140 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006141 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6142 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006143 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006144
6145 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006146 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006147 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006148 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006149 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006150 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006151 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006152 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006153
6154 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006155 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006156 }
6157}
6158
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006159struct task *hlua_applet_wakeup(struct task *t)
6160{
6161 struct appctx *ctx = t->context;
6162 struct stream_interface *si = ctx->owner;
6163
6164 /* If the applet is wake up without any expected work, the sheduler
6165 * remove it from the run queue. This flag indicate that the applet
6166 * is waiting for write. If the buffer is full, the main processing
6167 * will send some data and after call the applet, otherwise it call
6168 * the applet ASAP.
6169 */
6170 si_applet_cant_put(si);
6171 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006172 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006173 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006174}
6175
6176static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6177{
6178 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006179 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006180 struct task *task;
6181 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006182 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006183
Willy Tarreaubafbe012017-11-24 17:34:44 +01006184 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006185 if (!hlua) {
6186 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6187 ctx->rule->arg.hlua_rule->fcn.name);
6188 return 0;
6189 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006190 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006191 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006192 ctx->ctx.hlua_apptcp.flags = 0;
6193
6194 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006195 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006196 if (!task) {
6197 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6198 ctx->rule->arg.hlua_rule->fcn.name);
6199 return 0;
6200 }
6201 task->nice = 0;
6202 task->context = ctx;
6203 task->process = hlua_applet_wakeup;
6204 ctx->ctx.hlua_apptcp.task = task;
6205
6206 /* In the execution wrappers linked with a stream, the
6207 * Lua context can be not initialized. This behavior
6208 * permits to save performances because a systematic
6209 * Lua initialization cause 5% performances loss.
6210 */
6211 if (!hlua_ctx_init(hlua, task)) {
6212 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6213 ctx->rule->arg.hlua_rule->fcn.name);
6214 return 0;
6215 }
6216
6217 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006218 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006219
6220 /* The following Lua calls can fail. */
6221 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006222 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6223 error = lua_tostring(hlua->T, -1);
6224 else
6225 error = "critical error";
6226 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6227 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006228 RESET_SAFE_LJMP(hlua->T);
6229 return 0;
6230 }
6231
6232 /* Check stack available size. */
6233 if (!lua_checkstack(hlua->T, 1)) {
6234 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6235 ctx->rule->arg.hlua_rule->fcn.name);
6236 RESET_SAFE_LJMP(hlua->T);
6237 return 0;
6238 }
6239
6240 /* Restore the function in the stack. */
6241 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6242
6243 /* Create and and push object stream in the stack. */
6244 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
6245 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6246 ctx->rule->arg.hlua_rule->fcn.name);
6247 RESET_SAFE_LJMP(hlua->T);
6248 return 0;
6249 }
6250 hlua->nargs = 1;
6251
6252 /* push keywords in the stack. */
6253 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6254 if (!lua_checkstack(hlua->T, 1)) {
6255 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6256 ctx->rule->arg.hlua_rule->fcn.name);
6257 RESET_SAFE_LJMP(hlua->T);
6258 return 0;
6259 }
6260 lua_pushstring(hlua->T, *arg);
6261 hlua->nargs++;
6262 }
6263
6264 RESET_SAFE_LJMP(hlua->T);
6265
6266 /* Wakeup the applet ASAP. */
6267 si_applet_cant_get(si);
6268 si_applet_cant_put(si);
6269
6270 return 1;
6271}
6272
6273static void hlua_applet_tcp_fct(struct appctx *ctx)
6274{
6275 struct stream_interface *si = ctx->owner;
6276 struct stream *strm = si_strm(si);
6277 struct channel *res = si_ic(si);
6278 struct act_rule *rule = ctx->rule;
6279 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006280 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006281
6282 /* The applet execution is already done. */
6283 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
6284 return;
6285
6286 /* If the stream is disconnect or closed, ldo nothing. */
6287 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6288 return;
6289
6290 /* Execute the function. */
6291 switch (hlua_ctx_resume(hlua, 1)) {
6292 /* finished. */
6293 case HLUA_E_OK:
6294 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6295
6296 /* log time */
6297 strm->logs.tv_request = now;
6298
6299 /* eat the whole request */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006300 co_skip(si_oc(si), si_ob(si)->o);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006301 res->flags |= CF_READ_NULL;
6302 si_shutr(si);
6303 return;
6304
6305 /* yield. */
6306 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006307 if (hlua->wake_time != TICK_ETERNITY)
6308 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006309 return;
6310
6311 /* finished with error. */
6312 case HLUA_E_ERRMSG:
6313 /* Display log. */
6314 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6315 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6316 lua_pop(hlua->T, 1);
6317 goto error;
6318
6319 case HLUA_E_ERR:
6320 /* Display log. */
6321 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6322 rule->arg.hlua_rule->fcn.name);
6323 goto error;
6324
6325 default:
6326 goto error;
6327 }
6328
6329error:
6330
6331 /* For all other cases, just close the stream. */
6332 si_shutw(si);
6333 si_shutr(si);
6334 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6335}
6336
6337static void hlua_applet_tcp_release(struct appctx *ctx)
6338{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006339 task_delete(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006340 task_free(ctx->ctx.hlua_apptcp.task);
6341 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006342 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006343 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006344}
6345
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006346/* The function returns 1 if the initialisation is complete, 0 if
6347 * an errors occurs and -1 if more data are required for initializing
6348 * the applet.
6349 */
6350static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6351{
6352 struct stream_interface *si = ctx->owner;
6353 struct channel *req = si_oc(si);
6354 struct http_msg *msg;
6355 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006356 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006357 char **arg;
6358 struct hdr_ctx hdr;
6359 struct task *task;
6360 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01006361 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006362
6363 /* Wait for a full HTTP request. */
6364 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
6365 if (smp.flags & SMP_F_MAY_CHANGE)
6366 return -1;
6367 return 0;
6368 }
6369 txn = strm->txn;
6370 msg = &txn->req;
6371
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006372 /* We want two things in HTTP mode :
6373 * - enforce server-close mode if we were in keep-alive, so that the
6374 * applet is released after each response ;
6375 * - enable request body transfer to the applet in order to resync
6376 * with the response body.
6377 */
6378 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
6379 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006380
Willy Tarreaubafbe012017-11-24 17:34:44 +01006381 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006382 if (!hlua) {
6383 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6384 ctx->rule->arg.hlua_rule->fcn.name);
6385 return 0;
6386 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006387 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006388 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006389 ctx->ctx.hlua_apphttp.left_bytes = -1;
6390 ctx->ctx.hlua_apphttp.flags = 0;
6391
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006392 if (txn->req.flags & HTTP_MSGF_VER_11)
6393 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6394
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006395 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006396 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006397 if (!task) {
6398 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6399 ctx->rule->arg.hlua_rule->fcn.name);
6400 return 0;
6401 }
6402 task->nice = 0;
6403 task->context = ctx;
6404 task->process = hlua_applet_wakeup;
6405 ctx->ctx.hlua_apphttp.task = task;
6406
6407 /* In the execution wrappers linked with a stream, the
6408 * Lua context can be not initialized. This behavior
6409 * permits to save performances because a systematic
6410 * Lua initialization cause 5% performances loss.
6411 */
6412 if (!hlua_ctx_init(hlua, task)) {
6413 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6414 ctx->rule->arg.hlua_rule->fcn.name);
6415 return 0;
6416 }
6417
6418 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006419 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006420
6421 /* The following Lua calls can fail. */
6422 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006423 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6424 error = lua_tostring(hlua->T, -1);
6425 else
6426 error = "critical error";
6427 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6428 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006429 return 0;
6430 }
6431
6432 /* Check stack available size. */
6433 if (!lua_checkstack(hlua->T, 1)) {
6434 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6435 ctx->rule->arg.hlua_rule->fcn.name);
6436 RESET_SAFE_LJMP(hlua->T);
6437 return 0;
6438 }
6439
6440 /* Restore the function in the stack. */
6441 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6442
6443 /* Create and and push object stream in the stack. */
6444 if (!hlua_applet_http_new(hlua->T, ctx)) {
6445 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6446 ctx->rule->arg.hlua_rule->fcn.name);
6447 RESET_SAFE_LJMP(hlua->T);
6448 return 0;
6449 }
6450 hlua->nargs = 1;
6451
6452 /* Look for a 100-continue expected. */
6453 if (msg->flags & HTTP_MSGF_VER_11) {
6454 hdr.idx = 0;
6455 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
6456 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
6457 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
6458 }
6459
6460 /* push keywords in the stack. */
6461 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6462 if (!lua_checkstack(hlua->T, 1)) {
6463 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6464 ctx->rule->arg.hlua_rule->fcn.name);
6465 RESET_SAFE_LJMP(hlua->T);
6466 return 0;
6467 }
6468 lua_pushstring(hlua->T, *arg);
6469 hlua->nargs++;
6470 }
6471
6472 RESET_SAFE_LJMP(hlua->T);
6473
6474 /* Wakeup the applet when data is ready for read. */
6475 si_applet_cant_get(si);
6476
6477 return 1;
6478}
6479
6480static void hlua_applet_http_fct(struct appctx *ctx)
6481{
6482 struct stream_interface *si = ctx->owner;
6483 struct stream *strm = si_strm(si);
6484 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006485 struct act_rule *rule = ctx->rule;
6486 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006487 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006488 char *blk1;
6489 int len1;
6490 char *blk2;
6491 int len2;
6492 int ret;
6493
6494 /* If the stream is disconnect or closed, ldo nothing. */
6495 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6496 return;
6497
6498 /* Set the currently running flag. */
6499 if (!HLUA_IS_RUNNING(hlua) &&
6500 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6501
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006502 /* Wait for full HTTP analysys. */
6503 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6504 si_applet_cant_get(si);
6505 return;
6506 }
6507
6508 /* Store the max amount of bytes that we can read. */
6509 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6510
6511 /* We need to flush the request header. This left the body
6512 * for the Lua.
6513 */
6514
6515 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006516 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006517 if (ret == -1)
6518 return;
6519
6520 /* No data available, ask for more data. */
6521 if (ret == 1)
6522 len2 = 0;
6523 if (ret == 0)
6524 len1 = 0;
6525 if (len1 + len2 < strm->txn->req.eoh + 2) {
6526 si_applet_cant_get(si);
6527 return;
6528 }
6529
6530 /* skip the requests bytes. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006531 co_skip(si_oc(si), strm->txn->req.eoh + 2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006532 }
6533
6534 /* Executes The applet if it is not done. */
6535 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6536
6537 /* Execute the function. */
6538 switch (hlua_ctx_resume(hlua, 1)) {
6539 /* finished. */
6540 case HLUA_E_OK:
6541 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6542 break;
6543
6544 /* yield. */
6545 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006546 if (hlua->wake_time != TICK_ETERNITY)
6547 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006548 return;
6549
6550 /* finished with error. */
6551 case HLUA_E_ERRMSG:
6552 /* Display log. */
6553 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6554 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6555 lua_pop(hlua->T, 1);
6556 goto error;
6557
6558 case HLUA_E_ERR:
6559 /* Display log. */
6560 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6561 rule->arg.hlua_rule->fcn.name);
6562 goto error;
6563
6564 default:
6565 goto error;
6566 }
6567 }
6568
6569 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6570
6571 /* We must send the final chunk. */
6572 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6573 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6574
6575 /* sent last chunk at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006576 ret = ci_putblk(res, "0\r\n\r\n", 5);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006577
6578 /* critical error. */
6579 if (ret == -2 || ret == -3) {
6580 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6581 rule->arg.hlua_rule->fcn.name);
6582 goto error;
6583 }
6584
6585 /* no enough space error. */
6586 if (ret == -1) {
6587 si_applet_cant_put(si);
6588 return;
6589 }
6590
6591 /* set the last chunk sent. */
6592 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6593 }
6594
6595 /* close the connection. */
6596
6597 /* status / log */
6598 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6599 strm->logs.tv_request = now;
6600
6601 /* eat the whole request */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006602 co_skip(si_oc(si), si_ob(si)->o);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006603 res->flags |= CF_READ_NULL;
6604 si_shutr(si);
6605
6606 return;
6607 }
6608
6609error:
6610
6611 /* If we are in HTTP mode, and we are not send any
6612 * data, return a 500 server error in best effort:
6613 * if there are no room avalaible in the buffer,
6614 * just close the connection.
6615 */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006616 ci_putblk(res, error_500, strlen(error_500));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006617 if (!(strm->flags & SF_ERR_MASK))
6618 strm->flags |= SF_ERR_RESOURCE;
6619 si_shutw(si);
6620 si_shutr(si);
6621 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6622}
6623
6624static void hlua_applet_http_release(struct appctx *ctx)
6625{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006626 task_delete(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006627 task_free(ctx->ctx.hlua_apphttp.task);
6628 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006629 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006630 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006631}
6632
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006633/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6634 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006635 *
6636 * This function can fail with an abort() due to an Lua critical error.
6637 * We are in the configuration parsing process of HAProxy, this abort() is
6638 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006639 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006640static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6641 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006642{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006643 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006644 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006645
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006646 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006647 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006648 if (!rule->arg.hlua_rule) {
6649 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006650 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006651 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006652
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006653 /* Memory for arguments. */
6654 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
6655 if (!rule->arg.hlua_rule->args) {
6656 memprintf(err, "out of memory error");
6657 return ACT_RET_PRS_ERR;
6658 }
6659
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006660 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006661 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006662
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006663 /* Expect some arguments */
6664 for (i = 0; i < fcn->nargs; i++) {
6665 if (*args[i+1] == '\0') {
6666 memprintf(err, "expect %d arguments", fcn->nargs);
6667 return ACT_RET_PRS_ERR;
6668 }
6669 rule->arg.hlua_rule->args[i] = strdup(args[i + 1]);
6670 if (!rule->arg.hlua_rule->args[i]) {
6671 memprintf(err, "out of memory error");
6672 return ACT_RET_PRS_ERR;
6673 }
6674 (*cur_arg)++;
6675 }
6676 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006677
Thierry FOURNIER42148732015-09-02 17:17:33 +02006678 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006679 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006680 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006681}
6682
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006683static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6684 struct act_rule *rule, char **err)
6685{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006686 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006687
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006688 /* HTTP applets are forbidden in tcp-request rules.
6689 * HTTP applet request requires everything initilized by
6690 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6691 * The applet will be immediately initilized, but its before
6692 * the call of this analyzer.
6693 */
6694 if (rule->from != ACT_F_HTTP_REQ) {
6695 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6696 return ACT_RET_PRS_ERR;
6697 }
6698
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006699 /* Memory for the rule. */
6700 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6701 if (!rule->arg.hlua_rule) {
6702 memprintf(err, "out of memory error");
6703 return ACT_RET_PRS_ERR;
6704 }
6705
6706 /* Reference the Lua function and store the reference. */
6707 rule->arg.hlua_rule->fcn = *fcn;
6708
6709 /* TODO: later accept arguments. */
6710 rule->arg.hlua_rule->args = NULL;
6711
6712 /* Add applet pointer in the rule. */
6713 rule->applet.obj_type = OBJ_TYPE_APPLET;
6714 rule->applet.name = fcn->name;
6715 rule->applet.init = hlua_applet_http_init;
6716 rule->applet.fct = hlua_applet_http_fct;
6717 rule->applet.release = hlua_applet_http_release;
6718 rule->applet.timeout = hlua_timeout_applet;
6719
6720 return ACT_RET_PRS_OK;
6721}
6722
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006723/* This function is an LUA binding used for registering
6724 * "sample-conv" functions. It expects a converter name used
6725 * in the haproxy configuration file, and an LUA function.
6726 */
6727__LJMP static int hlua_register_action(lua_State *L)
6728{
6729 struct action_kw_list *akl;
6730 const char *name;
6731 int ref;
6732 int len;
6733 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006734 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006735
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006736 /* Initialise the number of expected arguments at 0. */
6737 nargs = 0;
6738
6739 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6740 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006741
6742 /* First argument : converter name. */
6743 name = MAY_LJMP(luaL_checkstring(L, 1));
6744
6745 /* Second argument : environment. */
6746 if (lua_type(L, 2) != LUA_TTABLE)
6747 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6748
6749 /* Third argument : lua function. */
6750 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6751
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006752 /* Fouth argument : number of mandatories arguments expected on the configuration line. */
6753 if (lua_gettop(L) >= 4)
6754 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
6755
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006756 /* browse the second argulent as an array. */
6757 lua_pushnil(L);
6758 while (lua_next(L, 2) != 0) {
6759 if (lua_type(L, -1) != LUA_TSTRING)
6760 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6761
6762 /* Check required environment. Only accepted "http" or "tcp". */
6763 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006764 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006765 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006766 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006767 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006768 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006769 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006770
6771 /* Fill fcn. */
6772 fcn->name = strdup(name);
6773 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006774 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006775 fcn->function_ref = ref;
6776
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006777 /* Set the expected number od arguments. */
6778 fcn->nargs = nargs;
6779
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006780 /* List head */
6781 akl->list.n = akl->list.p = NULL;
6782
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006783 /* action keyword. */
6784 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006785 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006786 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006787 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006788
6789 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6790
6791 akl->kw[0].match_pfx = 0;
6792 akl->kw[0].private = fcn;
6793 akl->kw[0].parse = action_register_lua;
6794
6795 /* select the action registering point. */
6796 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6797 tcp_req_cont_keywords_register(akl);
6798 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6799 tcp_res_cont_keywords_register(akl);
6800 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6801 http_req_keywords_register(akl);
6802 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6803 http_res_keywords_register(akl);
6804 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006805 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006806 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6807 "are expected.", lua_tostring(L, -1)));
6808
6809 /* pop the environment string. */
6810 lua_pop(L, 1);
6811 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006812 return ACT_RET_PRS_OK;
6813}
6814
6815static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6816 struct act_rule *rule, char **err)
6817{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006818 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006819
6820 /* Memory for the rule. */
6821 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6822 if (!rule->arg.hlua_rule) {
6823 memprintf(err, "out of memory error");
6824 return ACT_RET_PRS_ERR;
6825 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006826
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006827 /* Reference the Lua function and store the reference. */
6828 rule->arg.hlua_rule->fcn = *fcn;
6829
6830 /* TODO: later accept arguments. */
6831 rule->arg.hlua_rule->args = NULL;
6832
6833 /* Add applet pointer in the rule. */
6834 rule->applet.obj_type = OBJ_TYPE_APPLET;
6835 rule->applet.name = fcn->name;
6836 rule->applet.init = hlua_applet_tcp_init;
6837 rule->applet.fct = hlua_applet_tcp_fct;
6838 rule->applet.release = hlua_applet_tcp_release;
6839 rule->applet.timeout = hlua_timeout_applet;
6840
6841 return 0;
6842}
6843
6844/* This function is an LUA binding used for registering
6845 * "sample-conv" functions. It expects a converter name used
6846 * in the haproxy configuration file, and an LUA function.
6847 */
6848__LJMP static int hlua_register_service(lua_State *L)
6849{
6850 struct action_kw_list *akl;
6851 const char *name;
6852 const char *env;
6853 int ref;
6854 int len;
6855 struct hlua_function *fcn;
6856
6857 MAY_LJMP(check_args(L, 3, "register_service"));
6858
6859 /* First argument : converter name. */
6860 name = MAY_LJMP(luaL_checkstring(L, 1));
6861
6862 /* Second argument : environment. */
6863 env = MAY_LJMP(luaL_checkstring(L, 2));
6864
6865 /* Third argument : lua function. */
6866 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6867
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006868 /* Allocate and fill the sample fetch keyword struct. */
6869 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6870 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006871 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006872 fcn = calloc(1, sizeof(*fcn));
6873 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006874 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006875
6876 /* Fill fcn. */
6877 len = strlen("<lua.>") + strlen(name) + 1;
6878 fcn->name = calloc(1, len);
6879 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006880 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006881 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6882 fcn->function_ref = ref;
6883
6884 /* List head */
6885 akl->list.n = akl->list.p = NULL;
6886
6887 /* converter keyword. */
6888 len = strlen("lua.") + strlen(name) + 1;
6889 akl->kw[0].kw = calloc(1, len);
6890 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006891 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006892
6893 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6894
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01006895 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006896 if (strcmp(env, "tcp") == 0)
6897 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006898 else if (strcmp(env, "http") == 0)
6899 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006900 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006901 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01006902 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006903
6904 akl->kw[0].match_pfx = 0;
6905 akl->kw[0].private = fcn;
6906
6907 /* End of array. */
6908 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6909
6910 /* Register this new converter */
6911 service_keywords_register(akl);
6912
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006913 return 0;
6914}
6915
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006916/* This function initialises Lua cli handler. It copies the
6917 * arguments in the Lua stack and create channel IO objects.
6918 */
6919static int hlua_cli_parse_fct(char **args, struct appctx *appctx, void *private)
6920{
6921 struct hlua *hlua;
6922 struct hlua_function *fcn;
6923 int i;
6924 const char *error;
6925
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006926 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006927 appctx->ctx.hlua_cli.fcn = private;
6928
Willy Tarreaubafbe012017-11-24 17:34:44 +01006929 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006930 if (!hlua) {
6931 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006932 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006933 }
6934 HLUA_INIT(hlua);
6935 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006936
6937 /* Create task used by signal to wakeup applets.
6938 * We use the same wakeup fonction than the Lua applet_tcp and
6939 * applet_http. It is absolutely compatible.
6940 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006941 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006942 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01006943 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006944 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006945 }
6946 appctx->ctx.hlua_cli.task->nice = 0;
6947 appctx->ctx.hlua_cli.task->context = appctx;
6948 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
6949
6950 /* Initialises the Lua context */
6951 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
6952 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006953 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006954 }
6955
6956 /* The following Lua calls can fail. */
6957 if (!SET_SAFE_LJMP(hlua->T)) {
6958 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6959 error = lua_tostring(hlua->T, -1);
6960 else
6961 error = "critical error";
6962 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
6963 goto error;
6964 }
6965
6966 /* Check stack available size. */
6967 if (!lua_checkstack(hlua->T, 2)) {
6968 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6969 goto error;
6970 }
6971
6972 /* Restore the function in the stack. */
6973 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
6974
6975 /* Once the arguments parsed, the CLI is like an AppletTCP,
6976 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006977 */
6978 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
6979 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6980 goto error;
6981 }
6982 hlua->nargs = 1;
6983
6984 /* push keywords in the stack. */
6985 for (i = 0; *args[i]; i++) {
6986 /* Check stack available size. */
6987 if (!lua_checkstack(hlua->T, 1)) {
6988 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6989 goto error;
6990 }
6991 lua_pushstring(hlua->T, args[i]);
6992 hlua->nargs++;
6993 }
6994
6995 /* We must initialize the execution timeouts. */
6996 hlua->max_time = hlua_timeout_session;
6997
6998 /* At this point the execution is safe. */
6999 RESET_SAFE_LJMP(hlua->T);
7000
7001 /* It's ok */
7002 return 0;
7003
7004 /* It's not ok. */
7005error:
7006 RESET_SAFE_LJMP(hlua->T);
7007 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007008 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007009 return 1;
7010}
7011
7012static int hlua_cli_io_handler_fct(struct appctx *appctx)
7013{
7014 struct hlua *hlua;
7015 struct stream_interface *si;
7016 struct hlua_function *fcn;
7017
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007018 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007019 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01007020 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007021
7022 /* If the stream is disconnect or closed, ldo nothing. */
7023 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7024 return 1;
7025
7026 /* Execute the function. */
7027 switch (hlua_ctx_resume(hlua, 1)) {
7028
7029 /* finished. */
7030 case HLUA_E_OK:
7031 return 1;
7032
7033 /* yield. */
7034 case HLUA_E_AGAIN:
7035 /* We want write. */
7036 if (HLUA_IS_WAKERESWR(hlua))
7037 si_applet_cant_put(si);
7038 /* Set the timeout. */
7039 if (hlua->wake_time != TICK_ETERNITY)
7040 task_schedule(hlua->task, hlua->wake_time);
7041 return 0;
7042
7043 /* finished with error. */
7044 case HLUA_E_ERRMSG:
7045 /* Display log. */
7046 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
7047 fcn->name, lua_tostring(hlua->T, -1));
7048 lua_pop(hlua->T, 1);
7049 return 1;
7050
7051 case HLUA_E_ERR:
7052 /* Display log. */
7053 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
7054 fcn->name);
7055 return 1;
7056
7057 default:
7058 return 1;
7059 }
7060
7061 return 1;
7062}
7063
7064static void hlua_cli_io_release_fct(struct appctx *appctx)
7065{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007066 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007067 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007068}
7069
7070/* This function is an LUA binding used for registering
7071 * new keywords in the cli. It expects a list of keywords
7072 * which are the "path". It is limited to 5 keywords. A
7073 * description of the command, a function to be executed
7074 * for the parsing and a function for io handlers.
7075 */
7076__LJMP static int hlua_register_cli(lua_State *L)
7077{
7078 struct cli_kw_list *cli_kws;
7079 const char *message;
7080 int ref_io;
7081 int len;
7082 struct hlua_function *fcn;
7083 int index;
7084 int i;
7085
7086 MAY_LJMP(check_args(L, 3, "register_cli"));
7087
7088 /* First argument : an array of maximum 5 keywords. */
7089 if (!lua_istable(L, 1))
7090 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
7091
7092 /* Second argument : string with contextual message. */
7093 message = MAY_LJMP(luaL_checkstring(L, 2));
7094
7095 /* Third and fourth argument : lua function. */
7096 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
7097
7098 /* Allocate and fill the sample fetch keyword struct. */
7099 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
7100 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007101 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007102 fcn = calloc(1, sizeof(*fcn));
7103 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007104 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007105
7106 /* Fill path. */
7107 index = 0;
7108 lua_pushnil(L);
7109 while(lua_next(L, 1) != 0) {
7110 if (index >= 5)
7111 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
7112 if (lua_type(L, -1) != LUA_TSTRING)
7113 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
7114 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
7115 if (!cli_kws->kw[0].str_kw[index])
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007116 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007117 index++;
7118 lua_pop(L, 1);
7119 }
7120
7121 /* Copy help message. */
7122 cli_kws->kw[0].usage = strdup(message);
7123 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007124 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007125
7126 /* Fill fcn io handler. */
7127 len = strlen("<lua.cli>") + 1;
7128 for (i = 0; i < index; i++)
7129 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
7130 fcn->name = calloc(1, len);
7131 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007132 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007133 strncat((char *)fcn->name, "<lua.cli", len);
7134 for (i = 0; i < index; i++) {
7135 strncat((char *)fcn->name, ".", len);
7136 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
7137 }
7138 strncat((char *)fcn->name, ">", len);
7139 fcn->function_ref = ref_io;
7140
7141 /* Fill last entries. */
7142 cli_kws->kw[0].private = fcn;
7143 cli_kws->kw[0].parse = hlua_cli_parse_fct;
7144 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
7145 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
7146
7147 /* Register this new converter */
7148 cli_register_kw(cli_kws);
7149
7150 return 0;
7151}
7152
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007153static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
7154 struct proxy *defpx, const char *file, int line,
7155 char **err, unsigned int *timeout)
7156{
7157 const char *error;
7158
7159 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
7160 if (error && *error != '\0') {
7161 memprintf(err, "%s: invalid timeout", args[0]);
7162 return -1;
7163 }
7164 return 0;
7165}
7166
7167static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
7168 struct proxy *defpx, const char *file, int line,
7169 char **err)
7170{
7171 return hlua_read_timeout(args, section_type, curpx, defpx,
7172 file, line, err, &hlua_timeout_session);
7173}
7174
7175static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
7176 struct proxy *defpx, const char *file, int line,
7177 char **err)
7178{
7179 return hlua_read_timeout(args, section_type, curpx, defpx,
7180 file, line, err, &hlua_timeout_task);
7181}
7182
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007183static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
7184 struct proxy *defpx, const char *file, int line,
7185 char **err)
7186{
7187 return hlua_read_timeout(args, section_type, curpx, defpx,
7188 file, line, err, &hlua_timeout_applet);
7189}
7190
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007191static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
7192 struct proxy *defpx, const char *file, int line,
7193 char **err)
7194{
7195 char *error;
7196
7197 hlua_nb_instruction = strtoll(args[1], &error, 10);
7198 if (*error != '\0') {
7199 memprintf(err, "%s: invalid number", args[0]);
7200 return -1;
7201 }
7202 return 0;
7203}
7204
Willy Tarreau32f61e22015-03-18 17:54:59 +01007205static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
7206 struct proxy *defpx, const char *file, int line,
7207 char **err)
7208{
7209 char *error;
7210
7211 if (*(args[1]) == 0) {
7212 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
7213 return -1;
7214 }
7215 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
7216 if (*error != '\0') {
7217 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
7218 return -1;
7219 }
7220 return 0;
7221}
7222
7223
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007224/* This function is called by the main configuration key "lua-load". It loads and
7225 * execute an lua file during the parsing of the HAProxy configuration file. It is
7226 * the main lua entry point.
7227 *
7228 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
7229 * occured, otherwise it returns 0.
7230 *
7231 * In some error case, LUA set an error message in top of the stack. This function
7232 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007233 *
7234 * This function can fail with an abort() due to an Lua critical error.
7235 * We are in the configuration parsing process of HAProxy, this abort() is
7236 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007237 */
7238static int hlua_load(char **args, int section_type, struct proxy *curpx,
7239 struct proxy *defpx, const char *file, int line,
7240 char **err)
7241{
7242 int error;
7243
7244 /* Just load and compile the file. */
7245 error = luaL_loadfile(gL.T, args[1]);
7246 if (error) {
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007247 memprintf(err, "error in Lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007248 lua_pop(gL.T, 1);
7249 return -1;
7250 }
7251
7252 /* If no syntax error where detected, execute the code. */
7253 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
7254 switch (error) {
7255 case LUA_OK:
7256 break;
7257 case LUA_ERRRUN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007258 memprintf(err, "Lua runtime error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007259 lua_pop(gL.T, 1);
7260 return -1;
7261 case LUA_ERRMEM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007262 memprintf(err, "Lua out of memory error.n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007263 return -1;
7264 case LUA_ERRERR:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007265 memprintf(err, "Lua message handler error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007266 lua_pop(gL.T, 1);
7267 return -1;
7268 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007269 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007270 lua_pop(gL.T, 1);
7271 return -1;
7272 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007273 memprintf(err, "Lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007274 lua_pop(gL.T, 1);
7275 return -1;
7276 }
7277
7278 return 0;
7279}
7280
7281/* configuration keywords declaration */
7282static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007283 { CFG_GLOBAL, "lua-load", hlua_load },
7284 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
7285 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02007286 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007287 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01007288 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007289 { 0, NULL, NULL },
7290}};
7291
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007292/* This function can fail with an abort() due to an Lua critical error.
7293 * We are in the initialisation process of HAProxy, this abort() is
7294 * tolerated.
7295 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007296int hlua_post_init()
7297{
7298 struct hlua_init_function *init;
7299 const char *msg;
7300 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007301 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007302
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007303 /* Call post initialisation function in safe environement. */
7304 if (!SET_SAFE_LJMP(gL.T)) {
7305 if (lua_type(gL.T, -1) == LUA_TSTRING)
7306 error = lua_tostring(gL.T, -1);
7307 else
7308 error = "critical error";
7309 fprintf(stderr, "Lua post-init: %s.\n", error);
7310 exit(1);
7311 }
7312 hlua_fcn_post_init(gL.T);
7313 RESET_SAFE_LJMP(gL.T);
7314
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007315 list_for_each_entry(init, &hlua_init_functions, l) {
7316 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7317 ret = hlua_ctx_resume(&gL, 0);
7318 switch (ret) {
7319 case HLUA_E_OK:
7320 lua_pop(gL.T, -1);
7321 return 1;
7322 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007323 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007324 return 0;
7325 case HLUA_E_ERRMSG:
7326 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01007327 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007328 return 0;
7329 case HLUA_E_ERR:
7330 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007331 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007332 return 0;
7333 }
7334 }
7335 return 1;
7336}
7337
Willy Tarreau32f61e22015-03-18 17:54:59 +01007338/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7339 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7340 * is the previously allocated size or the kind of object in case of a new
7341 * allocation. <nsize> is the requested new size.
7342 */
7343static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7344{
7345 struct hlua_mem_allocator *zone = ud;
7346
7347 if (nsize == 0) {
7348 /* it's a free */
7349 if (ptr)
7350 zone->allocated -= osize;
7351 free(ptr);
7352 return NULL;
7353 }
7354
7355 if (!ptr) {
7356 /* it's a new allocation */
7357 if (zone->limit && zone->allocated + nsize > zone->limit)
7358 return NULL;
7359
7360 ptr = malloc(nsize);
7361 if (ptr)
7362 zone->allocated += nsize;
7363 return ptr;
7364 }
7365
7366 /* it's a realloc */
7367 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7368 return NULL;
7369
7370 ptr = realloc(ptr, nsize);
7371 if (ptr)
7372 zone->allocated += nsize - osize;
7373 return ptr;
7374}
7375
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007376/* Ithis function can fail with an abort() due to an Lua critical error.
7377 * We are in the initialisation process of HAProxy, this abort() is
7378 * tolerated.
7379 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007380void hlua_init(void)
7381{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007382 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007383 int idx;
7384 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007385 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007386 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007387 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007388#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007389 struct srv_kw *kw;
7390 int tmp_error;
7391 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007392 char *args[] = { /* SSL client configuration. */
7393 "ssl",
7394 "verify",
7395 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007396 NULL
7397 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007398#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007399
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007400 HA_SPIN_INIT(&hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02007401
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007402 /* Initialise struct hlua and com signals pool */
Willy Tarreaubafbe012017-11-24 17:34:44 +01007403 pool_head_hlua = create_pool("hlua", sizeof(struct hlua), MEM_F_SHARED);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007404
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007405 /* Register configuration keywords. */
7406 cfg_register_keywords(&cfg_kws);
7407
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007408 /* Init main lua stack. */
7409 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01007410 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007411 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02007412 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007413 hlua_sethlua(&gL);
7414 gL.Tref = LUA_REFNIL;
7415 gL.task = NULL;
7416
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007417 /* From this point, until the end of the initialisation fucntion,
7418 * the Lua function can fail with an abort. We are in the initialisation
7419 * process of HAProxy, this abort() is tolerated.
7420 */
7421
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007422 /* Initialise lua. */
7423 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007424
Thierry Fournier75933d42016-01-21 09:30:18 +01007425 /* Set safe environment for the initialisation. */
7426 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007427 if (lua_type(gL.T, -1) == LUA_TSTRING)
7428 error_msg = lua_tostring(gL.T, -1);
7429 else
7430 error_msg = "critical error";
7431 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01007432 exit(1);
7433 }
7434
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007435 /*
7436 *
7437 * Create "core" object.
7438 *
7439 */
7440
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01007441 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007442 lua_newtable(gL.T);
7443
7444 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007445 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007446 hlua_class_const_int(gL.T, log_levels[i], i);
7447
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007448 /* Register special functions. */
7449 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007450 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007451 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007452 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007453 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007454 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007455 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007456 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01007457 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007458 hlua_class_function(gL.T, "sleep", hlua_sleep);
7459 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01007460 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
7461 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
7462 hlua_class_function(gL.T, "set_map", hlua_set_map);
7463 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007464 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007465 hlua_class_function(gL.T, "log", hlua_log);
7466 hlua_class_function(gL.T, "Debug", hlua_log_debug);
7467 hlua_class_function(gL.T, "Info", hlua_log_info);
7468 hlua_class_function(gL.T, "Warning", hlua_log_warning);
7469 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02007470 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01007471 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007472
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007473 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007474
7475 /*
7476 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007477 * Register class Map
7478 *
7479 */
7480
7481 /* This table entry is the object "Map" base. */
7482 lua_newtable(gL.T);
7483
7484 /* register pattern types. */
7485 for (i=0; i<PAT_MATCH_NUM; i++)
7486 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007487 for (i=0; i<PAT_MATCH_NUM; i++) {
7488 snprintf(trash.str, trash.size, "_%s", pat_match_names[i]);
7489 hlua_class_const_int(gL.T, trash.str, i);
7490 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007491
7492 /* register constructor. */
7493 hlua_class_function(gL.T, "new", hlua_map_new);
7494
7495 /* Create and fill the metatable. */
7496 lua_newtable(gL.T);
7497
7498 /* Create and fille the __index entry. */
7499 lua_pushstring(gL.T, "__index");
7500 lua_newtable(gL.T);
7501
7502 /* Register . */
7503 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
7504 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
7505
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007506 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007507
Thierry Fournier45e78d72016-02-19 18:34:46 +01007508 /* Register previous table in the registry with reference and named entry.
7509 * The function hlua_register_metatable() pops the stack, so we
7510 * previously create a copy of the table.
7511 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007512 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007513 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007514
7515 /* Assign the metatable to the mai Map object. */
7516 lua_setmetatable(gL.T, -2);
7517
7518 /* Set a name to the table. */
7519 lua_setglobal(gL.T, "Map");
7520
7521 /*
7522 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007523 * Register class Channel
7524 *
7525 */
7526
7527 /* Create and fill the metatable. */
7528 lua_newtable(gL.T);
7529
7530 /* Create and fille the __index entry. */
7531 lua_pushstring(gL.T, "__index");
7532 lua_newtable(gL.T);
7533
7534 /* Register . */
7535 hlua_class_function(gL.T, "get", hlua_channel_get);
7536 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7537 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7538 hlua_class_function(gL.T, "set", hlua_channel_set);
7539 hlua_class_function(gL.T, "append", hlua_channel_append);
7540 hlua_class_function(gL.T, "send", hlua_channel_send);
7541 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7542 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7543 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007544 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007545
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007546 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007547
7548 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007549 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007550
7551 /*
7552 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007553 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007554 *
7555 */
7556
7557 /* Create and fill the metatable. */
7558 lua_newtable(gL.T);
7559
7560 /* Create and fille the __index entry. */
7561 lua_pushstring(gL.T, "__index");
7562 lua_newtable(gL.T);
7563
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007564 /* Browse existing fetches and create the associated
7565 * object method.
7566 */
7567 sf = NULL;
7568 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7569
7570 /* Dont register the keywork if the arguments check function are
7571 * not safe during the runtime.
7572 */
7573 if ((sf->val_args != NULL) &&
7574 (sf->val_args != val_payload_lv) &&
7575 (sf->val_args != val_hdr))
7576 continue;
7577
7578 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7579 * by an underscore.
7580 */
7581 strncpy(trash.str, sf->kw, trash.size);
7582 trash.str[trash.size - 1] = '\0';
7583 for (p = trash.str; *p; p++)
7584 if (*p == '.' || *p == '-' || *p == '+')
7585 *p = '_';
7586
7587 /* Register the function. */
7588 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007589 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007590 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007591 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007592 }
7593
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007594 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007595
7596 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007597 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007598
7599 /*
7600 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007601 * Register class Converters
7602 *
7603 */
7604
7605 /* Create and fill the metatable. */
7606 lua_newtable(gL.T);
7607
7608 /* Create and fill the __index entry. */
7609 lua_pushstring(gL.T, "__index");
7610 lua_newtable(gL.T);
7611
7612 /* Browse existing converters and create the associated
7613 * object method.
7614 */
7615 sc = NULL;
7616 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7617 /* Dont register the keywork if the arguments check function are
7618 * not safe during the runtime.
7619 */
7620 if (sc->val_args != NULL)
7621 continue;
7622
7623 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7624 * by an underscore.
7625 */
7626 strncpy(trash.str, sc->kw, trash.size);
7627 trash.str[trash.size - 1] = '\0';
7628 for (p = trash.str; *p; p++)
7629 if (*p == '.' || *p == '-' || *p == '+')
7630 *p = '_';
7631
7632 /* Register the function. */
7633 lua_pushstring(gL.T, trash.str);
7634 lua_pushlightuserdata(gL.T, sc);
7635 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007636 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007637 }
7638
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007639 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007640
7641 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007642 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007643
7644 /*
7645 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007646 * Register class HTTP
7647 *
7648 */
7649
7650 /* Create and fill the metatable. */
7651 lua_newtable(gL.T);
7652
7653 /* Create and fille the __index entry. */
7654 lua_pushstring(gL.T, "__index");
7655 lua_newtable(gL.T);
7656
7657 /* Register Lua functions. */
7658 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7659 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7660 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7661 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7662 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7663 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7664 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7665 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7666 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7667 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7668
7669 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7670 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7671 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7672 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7673 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7674 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007675 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007676
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007677 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007678
7679 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007680 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007681
7682 /*
7683 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007684 * Register class AppletTCP
7685 *
7686 */
7687
7688 /* Create and fill the metatable. */
7689 lua_newtable(gL.T);
7690
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007691 /* Create and fille the __index entry. */
7692 lua_pushstring(gL.T, "__index");
7693 lua_newtable(gL.T);
7694
7695 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01007696 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7697 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7698 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7699 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7700 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007701 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
7702 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
7703 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007704
7705 lua_settable(gL.T, -3);
7706
7707 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007708 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007709
7710 /*
7711 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007712 * Register class AppletHTTP
7713 *
7714 */
7715
7716 /* Create and fill the metatable. */
7717 lua_newtable(gL.T);
7718
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007719 /* Create and fille the __index entry. */
7720 lua_pushstring(gL.T, "__index");
7721 lua_newtable(gL.T);
7722
7723 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007724 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7725 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007726 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
7727 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
7728 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007729 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7730 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7731 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7732 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7733 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7734 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7735
7736 lua_settable(gL.T, -3);
7737
7738 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007739 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007740
7741 /*
7742 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007743 * Register class TXN
7744 *
7745 */
7746
7747 /* Create and fill the metatable. */
7748 lua_newtable(gL.T);
7749
7750 /* Create and fille the __index entry. */
7751 lua_pushstring(gL.T, "__index");
7752 lua_newtable(gL.T);
7753
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007754 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01007755 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7756 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007757 hlua_class_function(gL.T, "set_var", hlua_set_var);
Christopher Faulet85d79c92016-11-09 16:54:56 +01007758 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007759 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007760 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007761 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
7762 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7763 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007764 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7765 hlua_class_function(gL.T, "log", hlua_txn_log);
7766 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7767 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7768 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7769 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007770
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007771 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007772
7773 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007774 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007775
7776 /*
7777 *
7778 * Register class Socket
7779 *
7780 */
7781
7782 /* Create and fill the metatable. */
7783 lua_newtable(gL.T);
7784
7785 /* Create and fille the __index entry. */
7786 lua_pushstring(gL.T, "__index");
7787 lua_newtable(gL.T);
7788
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007789#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007790 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007791#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007792 hlua_class_function(gL.T, "connect", hlua_socket_connect);
7793 hlua_class_function(gL.T, "send", hlua_socket_send);
7794 hlua_class_function(gL.T, "receive", hlua_socket_receive);
7795 hlua_class_function(gL.T, "close", hlua_socket_close);
7796 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
7797 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
7798 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
7799 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
7800
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007801 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007802
7803 /* Register the garbage collector entry. */
7804 lua_pushstring(gL.T, "__gc");
7805 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007806 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007807
7808 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007809 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007810
7811 /* Proxy and server configuration initialisation. */
7812 memset(&socket_proxy, 0, sizeof(socket_proxy));
7813 init_new_proxy(&socket_proxy);
7814 socket_proxy.parent = NULL;
7815 socket_proxy.last_change = now.tv_sec;
7816 socket_proxy.id = "LUA-SOCKET";
7817 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
7818 socket_proxy.maxconn = 0;
7819 socket_proxy.accept = NULL;
7820 socket_proxy.options2 |= PR_O2_INDEPSTR;
7821 socket_proxy.srv = NULL;
7822 socket_proxy.conn_retries = 0;
7823 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
7824
7825 /* Init TCP server: unchanged parameters */
7826 memset(&socket_tcp, 0, sizeof(socket_tcp));
7827 socket_tcp.next = NULL;
7828 socket_tcp.proxy = &socket_proxy;
7829 socket_tcp.obj_type = OBJ_TYPE_SERVER;
7830 LIST_INIT(&socket_tcp.actconns);
7831 LIST_INIT(&socket_tcp.pendconns);
Christopher Faulet40a007c2017-07-03 15:41:01 +02007832 socket_tcp.priv_conns = NULL;
7833 socket_tcp.idle_conns = NULL;
7834 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02007835 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007836 socket_tcp.last_change = 0;
7837 socket_tcp.id = "LUA-TCP-CONN";
7838 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7839 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7840 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
7841
7842 /* XXX: Copy default parameter from default server,
7843 * but the default server is not initialized.
7844 */
7845 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
7846 socket_tcp.minconn = socket_proxy.defsrv.minconn;
7847 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
7848 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
7849 socket_tcp.onerror = socket_proxy.defsrv.onerror;
7850 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7851 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
7852 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7853 socket_tcp.uweight = socket_proxy.defsrv.iweight;
7854 socket_tcp.iweight = socket_proxy.defsrv.iweight;
7855
7856 socket_tcp.check.status = HCHK_STATUS_INI;
7857 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
7858 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
7859 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
7860 socket_tcp.check.server = &socket_tcp;
7861
7862 socket_tcp.agent.status = HCHK_STATUS_INI;
7863 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
7864 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
7865 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
7866 socket_tcp.agent.server = &socket_tcp;
7867
Willy Tarreaua261e9b2016-12-22 20:44:00 +01007868 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007869
7870#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007871 /* Init TCP server: unchanged parameters */
7872 memset(&socket_ssl, 0, sizeof(socket_ssl));
7873 socket_ssl.next = NULL;
7874 socket_ssl.proxy = &socket_proxy;
7875 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7876 LIST_INIT(&socket_ssl.actconns);
7877 LIST_INIT(&socket_ssl.pendconns);
Christopher Faulet40a007c2017-07-03 15:41:01 +02007878 socket_tcp.priv_conns = NULL;
7879 socket_tcp.idle_conns = NULL;
7880 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02007881 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007882 socket_ssl.last_change = 0;
7883 socket_ssl.id = "LUA-SSL-CONN";
7884 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7885 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7886 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7887
7888 /* XXX: Copy default parameter from default server,
7889 * but the default server is not initialized.
7890 */
7891 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7892 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7893 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7894 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7895 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7896 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7897 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7898 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7899 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7900 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7901
7902 socket_ssl.check.status = HCHK_STATUS_INI;
7903 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7904 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7905 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7906 socket_ssl.check.server = &socket_ssl;
7907
7908 socket_ssl.agent.status = HCHK_STATUS_INI;
7909 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7910 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7911 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7912 socket_ssl.agent.server = &socket_ssl;
7913
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007914 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01007915 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007916
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007917 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007918 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7919 /*
7920 *
7921 * If the keyword is not known, we can search in the registered
7922 * server keywords. This is usefull to configure special SSL
7923 * features like client certificates and ssl_verify.
7924 *
7925 */
7926 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7927 if (tmp_error != 0) {
7928 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7929 abort(); /* This must be never arrives because the command line
7930 not editable by the user. */
7931 }
7932 idx += kw->skip;
7933 }
7934 }
7935
7936 /* Initialize SSL server. */
Willy Tarreau17d45382016-12-22 21:16:08 +01007937 if (socket_ssl.xprt->prepare_srv)
7938 socket_ssl.xprt->prepare_srv(&socket_ssl);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007939#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01007940
7941 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007942}
Willy Tarreaubb57d942016-12-21 19:04:56 +01007943
7944__attribute__((constructor))
7945static void __hlua_init(void)
7946{
7947 char *ptr = NULL;
7948 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
7949 hap_register_build_opts(ptr, 1);
7950}