blob: ebe8c92b1743bad4d8fdb623990e081dba5b0b4b [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)) {
272 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
273 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
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100300/* This fucntion push an error string prefixed by the file name
301 * 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.
1899 * This fucntion returns a yield if no space are available.
1900 */
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 FOURNIER94a6bfc2017-07-12 12:10:44 +02002477 /* Check if we run on the same thread than the xreator thread.
2478 * We cannot access to the socket if the thread is different.
2479 */
2480 if (socket->tid != tid)
2481 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2482
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002483 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002484 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002485 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002486 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2487 WILL_LJMP(lua_error(L));
2488 return 0;
2489 }
2490 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2491 si = appctx->owner;
2492 s = si_strm(si);
2493
2494 s->req.rto = tmout;
2495 s->req.wto = tmout;
2496 s->res.rto = tmout;
2497 s->res.wto = tmout;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002498 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002499
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002500 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002501}
2502
2503__LJMP static int hlua_socket_new(lua_State *L)
2504{
2505 struct hlua_socket *socket;
2506 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002507 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002508 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002509
2510 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002511 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002512 hlua_pusherror(L, "socket: full stack");
2513 goto out_fail_conf;
2514 }
2515
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002516 /* Create the object: obj[0] = userdata. */
2517 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002518 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002519 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002520 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002521 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002522
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002523 /* Check if the various memory pools are intialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002524 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002525 hlua_pusherror(L, "socket: uninitialized pools.");
2526 goto out_fail_conf;
2527 }
2528
Willy Tarreau87b09662015-04-03 00:22:06 +02002529 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002530 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2531 lua_setmetatable(L, -2);
2532
Willy Tarreaud420a972015-04-06 00:39:18 +02002533 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002534 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002535 if (!appctx) {
2536 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002537 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002538 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002539
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002540 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002541 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002542 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2543 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002544
Willy Tarreaud420a972015-04-06 00:39:18 +02002545 /* Now create a session, task and stream for this applet */
2546 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2547 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002548 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002549 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002550 }
2551
Willy Tarreau87787ac2017-08-28 16:22:54 +02002552 strm = stream_new(sess, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002553 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002554 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002555 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002556 }
2557
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002558 /* Initialise cross reference between stream and Lua socket object. */
2559 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002560
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002561 /* Configure "right" stream interface. this "si" is used to connect
2562 * and retrieve data from the server. The connection is initialized
2563 * with the "struct server".
2564 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002565 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002566
2567 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002568 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2569 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002570
Willy Tarreau87787ac2017-08-28 16:22:54 +02002571 task_wakeup(strm->task, TASK_WOKEN_INIT);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002572 /* Return yield waiting for connection. */
2573 return 1;
2574
Willy Tarreaud420a972015-04-06 00:39:18 +02002575 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002576 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002577 out_fail_sess:
2578 appctx_free(appctx);
2579 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002580 WILL_LJMP(lua_error(L));
2581 return 0;
2582}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002583
2584/*
2585 *
2586 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002587 * Class Channel
2588 *
2589 *
2590 */
2591
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002592/* The state between the channel data and the HTTP parser state can be
2593 * unconsistent, so reset the parser and call it again. Warning, this
2594 * action not revalidate the request and not send a 400 if the modified
2595 * resuest is not valid.
2596 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002597 * This function never fails. The direction is set using dir, which equals
2598 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002599 */
2600static void hlua_resynchonize_proto(struct stream *stream, int dir)
2601{
2602 /* Protocol HTTP. */
2603 if (stream->be->mode == PR_MODE_HTTP) {
2604
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002605 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002606 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002607 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002608 http_txn_reset_res(stream->txn);
2609
2610 if (stream->txn->hdr_idx.v)
2611 hdr_idx_init(&stream->txn->hdr_idx);
2612
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002613 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002614 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002615 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002616 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2617 }
2618}
2619
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002620/* This function is called before the Lua execution. It stores
2621 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002622 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002623static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002624{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002625 c->mode = stream->be->mode;
2626 switch (c->mode) {
2627 case PR_MODE_HTTP:
2628 c->data.http.dir = opt & SMP_OPT_DIR;
2629 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2630 c->data.http.state = stream->txn->req.msg_state;
2631 else
2632 c->data.http.state = stream->txn->rsp.msg_state;
2633 break;
2634 default:
2635 break;
2636 }
2637}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002638
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002639/* This function is called after the Lua execution. it
2640 * returns true if the parser state is consistent, otherwise,
2641 * it return false.
2642 *
2643 * In HTTP mode, the parser state must be in the same state
2644 * or greater when we exit the function. Even if we do a
2645 * control yield. This prevent to break the HTTP message
2646 * from the Lua code.
2647 */
2648static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2649{
2650 if (c->mode != stream->be->mode)
2651 return 0;
2652
2653 switch (c->mode) {
2654 case PR_MODE_HTTP:
2655 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002656 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002657 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2658 return stream->txn->req.msg_state >= c->data.http.state;
2659 else
2660 return stream->txn->rsp.msg_state >= c->data.http.state;
2661 default:
2662 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002663 }
2664 return 1;
2665}
2666
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002667/* Returns the struct hlua_channel join to the class channel in the
2668 * stack entry "ud" or throws an argument error.
2669 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002670__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002671{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002672 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002673}
2674
Willy Tarreau47860ed2015-03-10 14:07:50 +01002675/* Pushes the channel onto the top of the stack. If the stask does not have a
2676 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002677 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002678static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002679{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002680 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002681 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002682 return 0;
2683
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002684 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002685 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002686 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002687
2688 /* Pop a class sesison metatable and affect it to the userdata. */
2689 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2690 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002691 return 1;
2692}
2693
2694/* Duplicate all the data present in the input channel and put it
2695 * in a string LUA variables. Returns -1 and push a nil value in
2696 * the stack if the channel is closed and all the data are consumed,
2697 * returns 0 if no data are available, otherwise it returns the length
2698 * of the builded string.
2699 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002700static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002701{
2702 char *blk1;
2703 char *blk2;
2704 int len1;
2705 int len2;
2706 int ret;
2707 luaL_Buffer b;
2708
Willy Tarreau06d80a92017-10-19 14:32:15 +02002709 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002710 if (unlikely(ret == 0))
2711 return 0;
2712
2713 if (unlikely(ret < 0)) {
2714 lua_pushnil(L);
2715 return -1;
2716 }
2717
2718 luaL_buffinit(L, &b);
2719 luaL_addlstring(&b, blk1, len1);
2720 if (unlikely(ret == 2))
2721 luaL_addlstring(&b, blk2, len2);
2722 luaL_pushresult(&b);
2723
2724 if (unlikely(ret == 2))
2725 return len1 + len2;
2726 return len1;
2727}
2728
2729/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2730 * a yield. This function keep the data in the buffer.
2731 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002732__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002733{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002734 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002735
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002736 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2737
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002738 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002739 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002740 return 1;
2741}
2742
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002743/* Check arguments for the function "hlua_channel_dup_yield". */
2744__LJMP static int hlua_channel_dup(lua_State *L)
2745{
2746 MAY_LJMP(check_args(L, 1, "dup"));
2747 MAY_LJMP(hlua_checkchannel(L, 1));
2748 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2749}
2750
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002751/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2752 * a yield. This function consumes the data in the buffer. It returns
2753 * a string containing the data or a nil pointer if no data are available
2754 * and the channel is closed.
2755 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002756__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002757{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002758 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002759 int ret;
2760
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002761 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002762
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002763 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002764 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002765 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002766
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002767 if (unlikely(ret == -1))
2768 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002769
Willy Tarreau47860ed2015-03-10 14:07:50 +01002770 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002771 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002772 return 1;
2773}
2774
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002775/* Check arguments for the fucntion "hlua_channel_get_yield". */
2776__LJMP static int hlua_channel_get(lua_State *L)
2777{
2778 MAY_LJMP(check_args(L, 1, "get"));
2779 MAY_LJMP(hlua_checkchannel(L, 1));
2780 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2781}
2782
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002783/* This functions consumes and returns one line. If the channel is closed,
2784 * and the last data does not contains a final '\n', the data are returned
2785 * without the final '\n'. When no more data are avalaible, it returns nil
2786 * value.
2787 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002788__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002789{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002790 char *blk1;
2791 char *blk2;
2792 int len1;
2793 int len2;
2794 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002795 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002796 int ret;
2797 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002798
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002799 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2800
Willy Tarreau06d80a92017-10-19 14:32:15 +02002801 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002802 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002803 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002804
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002805 if (ret == -1) {
2806 lua_pushnil(L);
2807 return 1;
2808 }
2809
2810 luaL_buffinit(L, &b);
2811 luaL_addlstring(&b, blk1, len1);
2812 len = len1;
2813 if (unlikely(ret == 2)) {
2814 luaL_addlstring(&b, blk2, len2);
2815 len += len2;
2816 }
2817 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002818 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002819 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002820 return 1;
2821}
2822
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002823/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2824__LJMP static int hlua_channel_getline(lua_State *L)
2825{
2826 MAY_LJMP(check_args(L, 1, "getline"));
2827 MAY_LJMP(hlua_checkchannel(L, 1));
2828 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2829}
2830
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002831/* This function takes a string as input, and append it at the
2832 * input side of channel. If the data is too big, but a space
2833 * is probably available after sending some data, the function
2834 * yield. If the data is bigger than the buffer, or if the
2835 * channel is closed, it returns -1. otherwise, it returns the
2836 * amount of data writed.
2837 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002838__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002839{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002840 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002841 size_t len;
2842 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2843 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2844 int ret;
2845 int max;
2846
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002847 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2848 * the request buffer if its not required.
2849 */
2850 if (chn->buf->size == 0) {
2851 si_applet_cant_put(chn_prod(chn));
2852 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
2853 }
2854
Willy Tarreau47860ed2015-03-10 14:07:50 +01002855 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002856 if (max > len - l)
2857 max = len - l;
2858
Willy Tarreau06d80a92017-10-19 14:32:15 +02002859 ret = ci_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002860 if (ret == -2 || ret == -3) {
2861 lua_pushinteger(L, -1);
2862 return 1;
2863 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002864 if (ret == -1) {
2865 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002866 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002867 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002868 l += ret;
2869 lua_pop(L, 1);
2870 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002871 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002872
Willy Tarreau47860ed2015-03-10 14:07:50 +01002873 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2874 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002875 /* There are no space avalaible, and the output buffer is empty.
2876 * in this case, we cannot add more data, so we cannot yield,
2877 * we return the amount of copyied data.
2878 */
2879 return 1;
2880 }
2881 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002882 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002883 return 1;
2884}
2885
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002886/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002887 * of the writed string, or -1 if the channel is closed or if the
2888 * buffer size is too little for the data.
2889 */
2890__LJMP static int hlua_channel_append(lua_State *L)
2891{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002892 size_t len;
2893
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002894 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002895 MAY_LJMP(hlua_checkchannel(L, 1));
2896 MAY_LJMP(luaL_checklstring(L, 2, &len));
2897 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002898 lua_pushinteger(L, 0);
2899
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002900 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002901}
2902
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002903/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002904 * his process by cleaning the buffer. The result is a replacement
2905 * of the current data. It returns the length of the writed string,
2906 * or -1 if the channel is closed or if the buffer size is too
2907 * little for the data.
2908 */
2909__LJMP static int hlua_channel_set(lua_State *L)
2910{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002911 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002912
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002913 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002914 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002915 lua_pushinteger(L, 0);
2916
Willy Tarreau47860ed2015-03-10 14:07:50 +01002917 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002918
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002919 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002920}
2921
2922/* Append data in the output side of the buffer. This data is immediatly
2923 * sent. The fcuntion returns the ammount of data writed. If the buffer
2924 * cannot contains the data, the function yield. The function returns -1
2925 * if the channel is closed.
2926 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002927__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002928{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002929 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002930 size_t len;
2931 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2932 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2933 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002934 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002935
Willy Tarreau47860ed2015-03-10 14:07:50 +01002936 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002937 lua_pushinteger(L, -1);
2938 return 1;
2939 }
2940
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002941 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2942 * the request buffer if its not required.
2943 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002944 if (chn->buf->size == 0) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002945 si_applet_cant_put(chn_prod(chn));
2946 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002947 }
2948
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002949 /* the writed data will be immediatly sent, so we can check
2950 * the avalaible space without taking in account the reserve.
2951 * The reserve is guaranted for the processing of incoming
2952 * data, because the buffer will be flushed.
2953 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002954 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002955
2956 /* If there are no space avalaible, and the output buffer is empty.
2957 * in this case, we cannot add more data, so we cannot yield,
2958 * we return the amount of copyied data.
2959 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002960 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002961 return 1;
2962
2963 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002964 if (max > len - l)
2965 max = len - l;
2966
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002967 /* The buffer avalaible size may be not contiguous. This test
2968 * detects a non contiguous buffer and realign it.
2969 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002970 if (bi_space_for_replace(chn->buf) < max)
2971 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002972
2973 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002974 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002975
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002976 /* buffer replace considers that the input part is filled.
2977 * so, I must forward these new data in the output part.
2978 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002979 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002980
2981 l += max;
2982 lua_pop(L, 1);
2983 lua_pushinteger(L, l);
2984
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002985 /* If there are no space avalaible, and the output buffer is empty.
2986 * in this case, we cannot add more data, so we cannot yield,
2987 * we return the amount of copyied data.
2988 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002989 max = chn->buf->size - buffer_len(chn->buf);
2990 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002991 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002992
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002993 if (l < len) {
2994 /* If we are waiting for space in the response buffer, we
2995 * must set the flag WAKERESWR. This flag required the task
2996 * wake up if any activity is detected on the response buffer.
2997 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002998 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002999 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003000 else
3001 HLUA_SET_WAKEREQWR(hlua);
3002 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003003 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003004
3005 return 1;
3006}
3007
3008/* Just a wraper of "_hlua_channel_send". This wrapper permits
3009 * yield the LUA process, and resume it without checking the
3010 * input arguments.
3011 */
3012__LJMP static int hlua_channel_send(lua_State *L)
3013{
3014 MAY_LJMP(check_args(L, 2, "send"));
3015 lua_pushinteger(L, 0);
3016
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003017 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003018}
3019
3020/* This function forward and amount of butes. The data pass from
3021 * the input side of the buffer to the output side, and can be
3022 * forwarded. This function never fails.
3023 *
3024 * The Lua function takes an amount of bytes to be forwarded in
3025 * imput. It returns the number of bytes forwarded.
3026 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003027__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003028{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003029 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003030 int len;
3031 int l;
3032 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003033 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003034
3035 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3036 len = MAY_LJMP(luaL_checkinteger(L, 2));
3037 l = MAY_LJMP(luaL_checkinteger(L, -1));
3038
3039 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01003040 if (max > chn->buf->i)
3041 max = chn->buf->i;
3042 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003043 l += max;
3044
3045 lua_pop(L, 1);
3046 lua_pushinteger(L, l);
3047
3048 /* Check if it miss bytes to forward. */
3049 if (l < len) {
3050 /* The the input channel or the output channel are closed, we
3051 * must return the amount of data forwarded.
3052 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003053 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003054 return 1;
3055
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003056 /* If we are waiting for space data in the response buffer, we
3057 * must set the flag WAKERESWR. This flag required the task
3058 * wake up if any activity is detected on the response buffer.
3059 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003060 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003061 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003062 else
3063 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003064
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003065 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01003066 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003067 }
3068
3069 return 1;
3070}
3071
3072/* Just check the input and prepare the stack for the previous
3073 * function "hlua_channel_forward_yield"
3074 */
3075__LJMP static int hlua_channel_forward(lua_State *L)
3076{
3077 MAY_LJMP(check_args(L, 2, "forward"));
3078 MAY_LJMP(hlua_checkchannel(L, 1));
3079 MAY_LJMP(luaL_checkinteger(L, 2));
3080
3081 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003082 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003083}
3084
3085/* Just returns the number of bytes available in the input
3086 * side of the buffer. This function never fails.
3087 */
3088__LJMP static int hlua_channel_get_in_len(lua_State *L)
3089{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003090 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003091
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003092 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003093 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01003094 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003095 return 1;
3096}
3097
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003098/* Returns true if the channel is full. */
3099__LJMP static int hlua_channel_is_full(lua_State *L)
3100{
3101 struct channel *chn;
3102 int rem;
3103
3104 MAY_LJMP(check_args(L, 1, "is_full"));
3105 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3106
3107 rem = chn->buf->size;
3108 rem -= chn->buf->o; /* Output size */
3109 rem -= chn->buf->i; /* Input size */
3110 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
3111
3112 lua_pushboolean(L, rem <= 0);
3113 return 1;
3114}
3115
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003116/* Just returns the number of bytes available in the output
3117 * side of the buffer. This function never fails.
3118 */
3119__LJMP static int hlua_channel_get_out_len(lua_State *L)
3120{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003121 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003122
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003123 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003124 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01003125 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003126 return 1;
3127}
3128
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003129/*
3130 *
3131 *
3132 * Class Fetches
3133 *
3134 *
3135 */
3136
3137/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003138 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003139 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003140__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003141{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003142 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003143}
3144
3145/* This function creates and push in the stack a fetch object according
3146 * with a current TXN.
3147 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003148static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003149{
Willy Tarreau7073c472015-04-06 11:15:40 +02003150 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003151
3152 /* Check stack size. */
3153 if (!lua_checkstack(L, 3))
3154 return 0;
3155
3156 /* Create the object: obj[0] = userdata.
3157 * Note that the base of the Fetches object is the
3158 * transaction object.
3159 */
3160 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003161 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003162 lua_rawseti(L, -2, 0);
3163
Willy Tarreau7073c472015-04-06 11:15:40 +02003164 hsmp->s = txn->s;
3165 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003166 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003167 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003168
3169 /* Pop a class sesison metatable and affect it to the userdata. */
3170 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3171 lua_setmetatable(L, -2);
3172
3173 return 1;
3174}
3175
3176/* This function is an LUA binding. It is called with each sample-fetch.
3177 * It uses closure argument to store the associated sample-fetch. It
3178 * returns only one argument or throws an error. An error is thrown
3179 * only if an error is encountered during the argument parsing. If
3180 * the "sample-fetch" function fails, nil is returned.
3181 */
3182__LJMP static int hlua_run_sample_fetch(lua_State *L)
3183{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003184 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003185 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003186 struct arg args[ARGM_NBARGS + 1];
3187 int i;
3188 struct sample smp;
3189
3190 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003191 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003192
3193 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003194 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003195
Thierry FOURNIERca988662015-12-20 18:43:03 +01003196 /* Check execution authorization. */
3197 if (f->use & SMP_USE_HTTP_ANY &&
3198 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3199 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3200 "is not available in Lua services", f->kw);
3201 WILL_LJMP(lua_error(L));
3202 }
3203
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003204 /* Get extra arguments. */
3205 for (i = 0; i < lua_gettop(L) - 1; i++) {
3206 if (i >= ARGM_NBARGS)
3207 break;
3208 hlua_lua2arg(L, i + 2, &args[i]);
3209 }
3210 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003211 args[i].data.str.str = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003212
3213 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003214 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003215
3216 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003217 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003218 lua_pushfstring(L, "error in arguments");
3219 WILL_LJMP(lua_error(L));
3220 }
3221
3222 /* Initialise the sample. */
3223 memset(&smp, 0, sizeof(smp));
3224
3225 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003226 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003227 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003228 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003229 lua_pushstring(L, "");
3230 else
3231 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003232 return 1;
3233 }
3234
3235 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003236 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003237 hlua_smp2lua_str(L, &smp);
3238 else
3239 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003240 return 1;
3241}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003242
3243/*
3244 *
3245 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003246 * Class Converters
3247 *
3248 *
3249 */
3250
3251/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003252 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003253 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003254__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003255{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003256 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003257}
3258
3259/* This function creates and push in the stack a Converters object
3260 * according with a current TXN.
3261 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003262static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003263{
Willy Tarreau7073c472015-04-06 11:15:40 +02003264 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003265
3266 /* Check stack size. */
3267 if (!lua_checkstack(L, 3))
3268 return 0;
3269
3270 /* Create the object: obj[0] = userdata.
3271 * Note that the base of the Converters object is the
3272 * same than the TXN object.
3273 */
3274 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003275 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003276 lua_rawseti(L, -2, 0);
3277
Willy Tarreau7073c472015-04-06 11:15:40 +02003278 hsmp->s = txn->s;
3279 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003280 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003281 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003282
Willy Tarreau87b09662015-04-03 00:22:06 +02003283 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003284 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3285 lua_setmetatable(L, -2);
3286
3287 return 1;
3288}
3289
3290/* This function is an LUA binding. It is called with each converter.
3291 * It uses closure argument to store the associated converter. It
3292 * returns only one argument or throws an error. An error is thrown
3293 * only if an error is encountered during the argument parsing. If
3294 * the converter function function fails, nil is returned.
3295 */
3296__LJMP static int hlua_run_sample_conv(lua_State *L)
3297{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003298 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003299 struct sample_conv *conv;
3300 struct arg args[ARGM_NBARGS + 1];
3301 int i;
3302 struct sample smp;
3303
3304 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003305 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003306
3307 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003308 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003309
3310 /* Get extra arguments. */
3311 for (i = 0; i < lua_gettop(L) - 2; i++) {
3312 if (i >= ARGM_NBARGS)
3313 break;
3314 hlua_lua2arg(L, i + 3, &args[i]);
3315 }
3316 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003317 args[i].data.str.str = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003318
3319 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003320 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003321
3322 /* Run the special args checker. */
3323 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3324 hlua_pusherror(L, "error in arguments");
3325 WILL_LJMP(lua_error(L));
3326 }
3327
3328 /* Initialise the sample. */
3329 if (!hlua_lua2smp(L, 2, &smp)) {
3330 hlua_pusherror(L, "error in the input argument");
3331 WILL_LJMP(lua_error(L));
3332 }
3333
Willy Tarreau1777ea62016-03-10 16:15:46 +01003334 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3335
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003336 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003337 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003338 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003339 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003340 WILL_LJMP(lua_error(L));
3341 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003342 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3343 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003344 hlua_pusherror(L, "error during the input argument casting");
3345 WILL_LJMP(lua_error(L));
3346 }
3347
3348 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003349 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003350 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003351 lua_pushstring(L, "");
3352 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003353 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003354 return 1;
3355 }
3356
3357 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003358 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003359 hlua_smp2lua_str(L, &smp);
3360 else
3361 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003362 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003363}
3364
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003365/*
3366 *
3367 *
3368 * Class AppletTCP
3369 *
3370 *
3371 */
3372
3373/* Returns a struct hlua_txn if the stack entry "ud" is
3374 * a class stream, otherwise it throws an error.
3375 */
3376__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3377{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003378 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003379}
3380
3381/* This function creates and push in the stack an Applet object
3382 * according with a current TXN.
3383 */
3384static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3385{
3386 struct hlua_appctx *appctx;
3387 struct stream_interface *si = ctx->owner;
3388 struct stream *s = si_strm(si);
3389 struct proxy *p = s->be;
3390
3391 /* Check stack size. */
3392 if (!lua_checkstack(L, 3))
3393 return 0;
3394
3395 /* Create the object: obj[0] = userdata.
3396 * Note that the base of the Converters object is the
3397 * same than the TXN object.
3398 */
3399 lua_newtable(L);
3400 appctx = lua_newuserdata(L, sizeof(*appctx));
3401 lua_rawseti(L, -2, 0);
3402 appctx->appctx = ctx;
3403 appctx->htxn.s = s;
3404 appctx->htxn.p = p;
3405
3406 /* Create the "f" field that contains a list of fetches. */
3407 lua_pushstring(L, "f");
3408 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3409 return 0;
3410 lua_settable(L, -3);
3411
3412 /* Create the "sf" field that contains a list of stringsafe fetches. */
3413 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003414 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003415 return 0;
3416 lua_settable(L, -3);
3417
3418 /* Create the "c" field that contains a list of converters. */
3419 lua_pushstring(L, "c");
3420 if (!hlua_converters_new(L, &appctx->htxn, 0))
3421 return 0;
3422 lua_settable(L, -3);
3423
3424 /* Create the "sc" field that contains a list of stringsafe converters. */
3425 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003426 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003427 return 0;
3428 lua_settable(L, -3);
3429
3430 /* Pop a class stream metatable and affect it to the table. */
3431 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3432 lua_setmetatable(L, -2);
3433
3434 return 1;
3435}
3436
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003437__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3438{
3439 struct hlua_appctx *appctx;
3440 struct stream *s;
3441 const char *name;
3442 size_t len;
3443 struct sample smp;
3444
3445 MAY_LJMP(check_args(L, 3, "set_var"));
3446
3447 /* It is useles to retrieve the stream, but this function
3448 * runs only in a stream context.
3449 */
3450 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3451 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3452 s = appctx->htxn.s;
3453
3454 /* Converts the third argument in a sample. */
3455 hlua_lua2smp(L, 3, &smp);
3456
3457 /* Store the sample in a variable. */
3458 smp_set_owner(&smp, s->be, s->sess, s, 0);
3459 vars_set_by_name(name, len, &smp);
3460 return 0;
3461}
3462
3463__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3464{
3465 struct hlua_appctx *appctx;
3466 struct stream *s;
3467 const char *name;
3468 size_t len;
3469 struct sample smp;
3470
3471 MAY_LJMP(check_args(L, 2, "unset_var"));
3472
3473 /* It is useles to retrieve the stream, but this function
3474 * runs only in a stream context.
3475 */
3476 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3477 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3478 s = appctx->htxn.s;
3479
3480 /* Unset the variable. */
3481 smp_set_owner(&smp, s->be, s->sess, s, 0);
3482 vars_unset_by_name(name, len, &smp);
3483 return 0;
3484}
3485
3486__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3487{
3488 struct hlua_appctx *appctx;
3489 struct stream *s;
3490 const char *name;
3491 size_t len;
3492 struct sample smp;
3493
3494 MAY_LJMP(check_args(L, 2, "get_var"));
3495
3496 /* It is useles to retrieve the stream, but this function
3497 * runs only in a stream context.
3498 */
3499 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3500 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3501 s = appctx->htxn.s;
3502
3503 smp_set_owner(&smp, s->be, s->sess, s, 0);
3504 if (!vars_get_by_name(name, len, &smp)) {
3505 lua_pushnil(L);
3506 return 1;
3507 }
3508
3509 return hlua_smp2lua(L, &smp);
3510}
3511
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003512__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3513{
3514 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3515 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003516 struct hlua *hlua;
3517
3518 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003519 if (!s->hlua)
3520 return 0;
3521 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003522
3523 MAY_LJMP(check_args(L, 2, "set_priv"));
3524
3525 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003526 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003527
3528 /* Get and store new value. */
3529 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3530 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3531
3532 return 0;
3533}
3534
3535__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3536{
3537 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3538 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003539 struct hlua *hlua;
3540
3541 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003542 if (!s->hlua) {
3543 lua_pushnil(L);
3544 return 1;
3545 }
3546 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003547
3548 /* Push configuration index in the stack. */
3549 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3550
3551 return 1;
3552}
3553
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003554/* If expected data not yet available, it returns a yield. This function
3555 * consumes the data in the buffer. It returns a string containing the
3556 * data. This string can be empty.
3557 */
3558__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3559{
3560 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3561 struct stream_interface *si = appctx->appctx->owner;
3562 int ret;
3563 char *blk1;
3564 int len1;
3565 char *blk2;
3566 int len2;
3567
3568 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003569 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003570
3571 /* Data not yet avalaible. return yield. */
3572 if (ret == 0) {
3573 si_applet_cant_get(si);
3574 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3575 }
3576
3577 /* End of data: commit the total strings and return. */
3578 if (ret < 0) {
3579 luaL_pushresult(&appctx->b);
3580 return 1;
3581 }
3582
3583 /* Ensure that the block 2 length is usable. */
3584 if (ret == 1)
3585 len2 = 0;
3586
3587 /* dont check the max length read and dont check. */
3588 luaL_addlstring(&appctx->b, blk1, len1);
3589 luaL_addlstring(&appctx->b, blk2, len2);
3590
3591 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003592 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003593 luaL_pushresult(&appctx->b);
3594 return 1;
3595}
3596
3597/* Check arguments for the fucntion "hlua_channel_get_yield". */
3598__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3599{
3600 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3601
3602 /* Initialise the string catenation. */
3603 luaL_buffinit(L, &appctx->b);
3604
3605 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3606}
3607
3608/* If expected data not yet available, it returns a yield. This function
3609 * consumes the data in the buffer. It returns a string containing the
3610 * data. This string can be empty.
3611 */
3612__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3613{
3614 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3615 struct stream_interface *si = appctx->appctx->owner;
3616 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3617 int ret;
3618 char *blk1;
3619 int len1;
3620 char *blk2;
3621 int len2;
3622
3623 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003624 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003625
3626 /* Data not yet avalaible. return yield. */
3627 if (ret == 0) {
3628 si_applet_cant_get(si);
3629 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3630 }
3631
3632 /* End of data: commit the total strings and return. */
3633 if (ret < 0) {
3634 luaL_pushresult(&appctx->b);
3635 return 1;
3636 }
3637
3638 /* Ensure that the block 2 length is usable. */
3639 if (ret == 1)
3640 len2 = 0;
3641
3642 if (len == -1) {
3643
3644 /* If len == -1, catenate all the data avalaile and
3645 * yield because we want to get all the data until
3646 * the end of data stream.
3647 */
3648 luaL_addlstring(&appctx->b, blk1, len1);
3649 luaL_addlstring(&appctx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02003650 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003651 si_applet_cant_get(si);
3652 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3653
3654 } else {
3655
3656 /* Copy the fisrt block caping to the length required. */
3657 if (len1 > len)
3658 len1 = len;
3659 luaL_addlstring(&appctx->b, blk1, len1);
3660 len -= len1;
3661
3662 /* Copy the second block. */
3663 if (len2 > len)
3664 len2 = len;
3665 luaL_addlstring(&appctx->b, blk2, len2);
3666 len -= len2;
3667
3668 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003669 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003670
3671 /* If we are no other data avalaible, yield waiting for new data. */
3672 if (len > 0) {
3673 lua_pushinteger(L, len);
3674 lua_replace(L, 2);
3675 si_applet_cant_get(si);
3676 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3677 }
3678
3679 /* return the result. */
3680 luaL_pushresult(&appctx->b);
3681 return 1;
3682 }
3683
3684 /* we never executes this */
3685 hlua_pusherror(L, "Lua: internal error");
3686 WILL_LJMP(lua_error(L));
3687 return 0;
3688}
3689
3690/* Check arguments for the fucntion "hlua_channel_get_yield". */
3691__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3692{
3693 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3694 int len = -1;
3695
3696 if (lua_gettop(L) > 2)
3697 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3698 if (lua_gettop(L) >= 2) {
3699 len = MAY_LJMP(luaL_checkinteger(L, 2));
3700 lua_pop(L, 1);
3701 }
3702
3703 /* Confirm or set the required length */
3704 lua_pushinteger(L, len);
3705
3706 /* Initialise the string catenation. */
3707 luaL_buffinit(L, &appctx->b);
3708
3709 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3710}
3711
3712/* Append data in the output side of the buffer. This data is immediatly
3713 * sent. The fcuntion returns the ammount of data writed. If the buffer
3714 * cannot contains the data, the function yield. The function returns -1
3715 * if the channel is closed.
3716 */
3717__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3718{
3719 size_t len;
3720 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3721 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3722 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3723 struct stream_interface *si = appctx->appctx->owner;
3724 struct channel *chn = si_ic(si);
3725 int max;
3726
3727 /* Get the max amount of data which can write as input in the channel. */
3728 max = channel_recv_max(chn);
3729 if (max > (len - l))
3730 max = len - l;
3731
3732 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003733 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003734
3735 /* update counters. */
3736 l += max;
3737 lua_pop(L, 1);
3738 lua_pushinteger(L, l);
3739
3740 /* If some data is not send, declares the situation to the
3741 * applet, and returns a yield.
3742 */
3743 if (l < len) {
3744 si_applet_cant_put(si);
3745 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3746 }
3747
3748 return 1;
3749}
3750
3751/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3752 * yield the LUA process, and resume it without checking the
3753 * input arguments.
3754 */
3755__LJMP static int hlua_applet_tcp_send(lua_State *L)
3756{
3757 MAY_LJMP(check_args(L, 2, "send"));
3758 lua_pushinteger(L, 0);
3759
3760 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3761}
3762
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003763/*
3764 *
3765 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003766 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003767 *
3768 *
3769 */
3770
3771/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003772 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003773 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003774__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003775{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003776 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003777}
3778
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003779/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003780 * according with a current TXN.
3781 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003782static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003783{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003784 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003785 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003786 struct stream_interface *si = ctx->owner;
3787 struct stream *s = si_strm(si);
3788 struct proxy *px = s->be;
3789 struct http_txn *txn = s->txn;
3790 const char *path;
3791 const char *end;
3792 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003793
3794 /* Check stack size. */
3795 if (!lua_checkstack(L, 3))
3796 return 0;
3797
3798 /* Create the object: obj[0] = userdata.
3799 * Note that the base of the Converters object is the
3800 * same than the TXN object.
3801 */
3802 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003803 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003804 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003805 appctx->appctx = ctx;
3806 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003807 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003808 appctx->htxn.s = s;
3809 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003810
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003811 /* Create the "f" field that contains a list of fetches. */
3812 lua_pushstring(L, "f");
3813 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3814 return 0;
3815 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003816
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003817 /* Create the "sf" field that contains a list of stringsafe fetches. */
3818 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003819 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003820 return 0;
3821 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003822
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003823 /* Create the "c" field that contains a list of converters. */
3824 lua_pushstring(L, "c");
3825 if (!hlua_converters_new(L, &appctx->htxn, 0))
3826 return 0;
3827 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003828
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003829 /* Create the "sc" field that contains a list of stringsafe converters. */
3830 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003831 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003832 return 0;
3833 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003834
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003835 /* Stores the request method. */
3836 lua_pushstring(L, "method");
3837 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3838 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003839
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003840 /* Stores the http version. */
3841 lua_pushstring(L, "version");
3842 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3843 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003844
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003845 /* creates an array of headers. hlua_http_get_headers() crates and push
3846 * the array on the top of the stack.
3847 */
3848 lua_pushstring(L, "headers");
3849 htxn.s = s;
3850 htxn.p = px;
3851 htxn.dir = SMP_OPT_DIR_REQ;
3852 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3853 return 0;
3854 lua_settable(L, -3);
3855
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003856 /* Get path and qs */
3857 path = http_get_path(txn);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003858 if (path) {
3859 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3860 p = path;
3861 while (p < end && *p != '?')
3862 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003863
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003864 /* Stores the request path. */
3865 lua_pushstring(L, "path");
3866 lua_pushlstring(L, path, p - path);
3867 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003868
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003869 /* Stores the query string. */
3870 lua_pushstring(L, "qs");
3871 if (*p == '?')
3872 p++;
3873 lua_pushlstring(L, p, end - p);
3874 lua_settable(L, -3);
3875 }
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003876
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003877 /* Stores the request path. */
3878 lua_pushstring(L, "length");
3879 lua_pushinteger(L, txn->req.body_len);
3880 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003881
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003882 /* Create an array of HTTP request headers. */
3883 lua_pushstring(L, "headers");
3884 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3885 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003886
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003887 /* Create an empty array of HTTP request headers. */
3888 lua_pushstring(L, "response");
3889 lua_newtable(L);
3890 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003891
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003892 /* Pop a class stream metatable and affect it to the table. */
3893 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3894 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003895
3896 return 1;
3897}
3898
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003899__LJMP static int hlua_applet_http_set_var(lua_State *L)
3900{
3901 struct hlua_appctx *appctx;
3902 struct stream *s;
3903 const char *name;
3904 size_t len;
3905 struct sample smp;
3906
3907 MAY_LJMP(check_args(L, 3, "set_var"));
3908
3909 /* It is useles to retrieve the stream, but this function
3910 * runs only in a stream context.
3911 */
3912 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3913 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3914 s = appctx->htxn.s;
3915
3916 /* Converts the third argument in a sample. */
3917 hlua_lua2smp(L, 3, &smp);
3918
3919 /* Store the sample in a variable. */
3920 smp_set_owner(&smp, s->be, s->sess, s, 0);
3921 vars_set_by_name(name, len, &smp);
3922 return 0;
3923}
3924
3925__LJMP static int hlua_applet_http_unset_var(lua_State *L)
3926{
3927 struct hlua_appctx *appctx;
3928 struct stream *s;
3929 const char *name;
3930 size_t len;
3931 struct sample smp;
3932
3933 MAY_LJMP(check_args(L, 2, "unset_var"));
3934
3935 /* It is useles to retrieve the stream, but this function
3936 * runs only in a stream context.
3937 */
3938 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3939 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3940 s = appctx->htxn.s;
3941
3942 /* Unset the variable. */
3943 smp_set_owner(&smp, s->be, s->sess, s, 0);
3944 vars_unset_by_name(name, len, &smp);
3945 return 0;
3946}
3947
3948__LJMP static int hlua_applet_http_get_var(lua_State *L)
3949{
3950 struct hlua_appctx *appctx;
3951 struct stream *s;
3952 const char *name;
3953 size_t len;
3954 struct sample smp;
3955
3956 MAY_LJMP(check_args(L, 2, "get_var"));
3957
3958 /* It is useles to retrieve the stream, but this function
3959 * runs only in a stream context.
3960 */
3961 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3962 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3963 s = appctx->htxn.s;
3964
3965 smp_set_owner(&smp, s->be, s->sess, s, 0);
3966 if (!vars_get_by_name(name, len, &smp)) {
3967 lua_pushnil(L);
3968 return 1;
3969 }
3970
3971 return hlua_smp2lua(L, &smp);
3972}
3973
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003974__LJMP static int hlua_applet_http_set_priv(lua_State *L)
3975{
3976 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3977 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003978 struct hlua *hlua;
3979
3980 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003981 if (!s->hlua)
3982 return 0;
3983 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003984
3985 MAY_LJMP(check_args(L, 2, "set_priv"));
3986
3987 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003988 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003989
3990 /* Get and store new value. */
3991 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3992 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3993
3994 return 0;
3995}
3996
3997__LJMP static int hlua_applet_http_get_priv(lua_State *L)
3998{
3999 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4000 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004001 struct hlua *hlua;
4002
4003 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004004 if (!s->hlua) {
4005 lua_pushnil(L);
4006 return 1;
4007 }
4008 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004009
4010 /* Push configuration index in the stack. */
4011 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4012
4013 return 1;
4014}
4015
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004016/* If expected data not yet available, it returns a yield. This function
4017 * consumes the data in the buffer. It returns a string containing the
4018 * data. This string can be empty.
4019 */
4020__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004021{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004022 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4023 struct stream_interface *si = appctx->appctx->owner;
4024 struct channel *chn = si_ic(si);
4025 int ret;
4026 char *blk1;
4027 int len1;
4028 char *blk2;
4029 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004030
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004031 /* Maybe we cant send a 100-continue ? */
4032 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau06d80a92017-10-19 14:32:15 +02004033 ret = ci_putblk(chn, HTTP_100C, strlen(HTTP_100C));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004034 /* if ret == -2 or -3 the channel closed or the message si too
4035 * big for the buffers. We cant send anything. So, we ignoring
4036 * the error, considers that the 100-continue is sent, and try
4037 * to receive.
4038 * If ret is -1, we dont have room in the buffer, so we yield.
4039 */
4040 if (ret == -1) {
4041 si_applet_cant_put(si);
4042 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
4043 }
4044 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4045 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004046
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004047 /* Check for the end of the data. */
4048 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
4049 luaL_pushresult(&appctx->b);
4050 return 1;
4051 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004052
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004053 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004054 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004055
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004056 /* Data not yet avalaible. return yield. */
4057 if (ret == 0) {
4058 si_applet_cant_get(si);
4059 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
4060 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004061
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004062 /* End of data: commit the total strings and return. */
4063 if (ret < 0) {
4064 luaL_pushresult(&appctx->b);
4065 return 1;
4066 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004067
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004068 /* Ensure that the block 2 length is usable. */
4069 if (ret == 1)
4070 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004071
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004072 /* Copy the fisrt block caping to the length required. */
4073 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4074 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4075 luaL_addlstring(&appctx->b, blk1, len1);
4076 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004077
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004078 /* Copy the second block. */
4079 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4080 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4081 luaL_addlstring(&appctx->b, blk2, len2);
4082 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004083
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004084 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004085 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004086 luaL_pushresult(&appctx->b);
4087 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004088}
4089
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004090/* Check arguments for the fucntion "hlua_channel_get_yield". */
4091__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004092{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004093 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004094
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004095 /* Initialise the string catenation. */
4096 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004097
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004098 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004099}
4100
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004101/* If expected data not yet available, it returns a yield. This function
4102 * consumes the data in the buffer. It returns a string containing the
4103 * data. This string can be empty.
4104 */
4105__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004106{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004107 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4108 struct stream_interface *si = appctx->appctx->owner;
4109 int len = MAY_LJMP(luaL_checkinteger(L, 2));
4110 struct channel *chn = si_ic(si);
4111 int ret;
4112 char *blk1;
4113 int len1;
4114 char *blk2;
4115 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004116
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004117 /* Maybe we cant send a 100-continue ? */
4118 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau06d80a92017-10-19 14:32:15 +02004119 ret = ci_putblk(chn, HTTP_100C, strlen(HTTP_100C));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004120 /* if ret == -2 or -3 the channel closed or the message si too
4121 * big for the buffers. We cant send anything. So, we ignoring
4122 * the error, considers that the 100-continue is sent, and try
4123 * to receive.
4124 * If ret is -1, we dont have room in the buffer, so we yield.
4125 */
4126 if (ret == -1) {
4127 si_applet_cant_put(si);
4128 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4129 }
4130 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4131 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004132
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004133 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004134 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004135
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004136 /* Data not yet avalaible. return yield. */
4137 if (ret == 0) {
4138 si_applet_cant_get(si);
4139 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4140 }
4141
4142 /* End of data: commit the total strings and return. */
4143 if (ret < 0) {
4144 luaL_pushresult(&appctx->b);
4145 return 1;
4146 }
4147
4148 /* Ensure that the block 2 length is usable. */
4149 if (ret == 1)
4150 len2 = 0;
4151
4152 /* Copy the fisrt block caping to the length required. */
4153 if (len1 > len)
4154 len1 = len;
4155 luaL_addlstring(&appctx->b, blk1, len1);
4156 len -= len1;
4157
4158 /* Copy the second block. */
4159 if (len2 > len)
4160 len2 = len;
4161 luaL_addlstring(&appctx->b, blk2, len2);
4162 len -= len2;
4163
4164 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004165 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004166 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
4167 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
4168
4169 /* If we are no other data avalaible, yield waiting for new data. */
4170 if (len > 0) {
4171 lua_pushinteger(L, len);
4172 lua_replace(L, 2);
4173 si_applet_cant_get(si);
4174 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4175 }
4176
4177 /* return the result. */
4178 luaL_pushresult(&appctx->b);
4179 return 1;
4180}
4181
4182/* Check arguments for the fucntion "hlua_channel_get_yield". */
4183__LJMP static int hlua_applet_http_recv(lua_State *L)
4184{
4185 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4186 int len = -1;
4187
4188 /* Check arguments. */
4189 if (lua_gettop(L) > 2)
4190 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4191 if (lua_gettop(L) >= 2) {
4192 len = MAY_LJMP(luaL_checkinteger(L, 2));
4193 lua_pop(L, 1);
4194 }
4195
4196 /* Check the required length */
4197 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4198 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4199 lua_pushinteger(L, len);
4200
4201 /* Initialise the string catenation. */
4202 luaL_buffinit(L, &appctx->b);
4203
4204 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4205}
4206
4207/* Append data in the output side of the buffer. This data is immediatly
4208 * sent. The fcuntion returns the ammount of data writed. If the buffer
4209 * cannot contains the data, the function yield. The function returns -1
4210 * if the channel is closed.
4211 */
4212__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4213{
4214 size_t len;
4215 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4216 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4217 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4218 struct stream_interface *si = appctx->appctx->owner;
4219 struct channel *chn = si_ic(si);
4220 int max;
4221
4222 /* Get the max amount of data which can write as input in the channel. */
4223 max = channel_recv_max(chn);
4224 if (max > (len - l))
4225 max = len - l;
4226
4227 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004228 ci_putblk(chn, str + l, max);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004229
4230 /* update counters. */
4231 l += max;
4232 lua_pop(L, 1);
4233 lua_pushinteger(L, l);
4234
4235 /* If some data is not send, declares the situation to the
4236 * applet, and returns a yield.
4237 */
4238 if (l < len) {
4239 si_applet_cant_put(si);
4240 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
4241 }
4242
4243 return 1;
4244}
4245
4246/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4247 * yield the LUA process, and resume it without checking the
4248 * input arguments.
4249 */
4250__LJMP static int hlua_applet_http_send(lua_State *L)
4251{
4252 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4253 size_t len;
4254 char hex[10];
4255
4256 MAY_LJMP(luaL_checklstring(L, 2, &len));
4257
4258 /* If transfer encoding chunked is selected, we surround the data
4259 * by chunk data.
4260 */
4261 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4262 snprintf(hex, 9, "%x", (unsigned int)len);
4263 lua_pushfstring(L, "%s\r\n", hex);
4264 lua_insert(L, 2); /* swap the last 2 entries. */
4265 lua_pushstring(L, "\r\n");
4266 lua_concat(L, 3);
4267 }
4268
4269 /* This interger is used for followinf the amount of data sent. */
4270 lua_pushinteger(L, 0);
4271
4272 /* We want to send some data. Headers must be sent. */
4273 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4274 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4275 WILL_LJMP(lua_error(L));
4276 }
4277
4278 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4279}
4280
4281__LJMP static int hlua_applet_http_addheader(lua_State *L)
4282{
4283 const char *name;
4284 int ret;
4285
4286 MAY_LJMP(hlua_checkapplet_http(L, 1));
4287 name = MAY_LJMP(luaL_checkstring(L, 2));
4288 MAY_LJMP(luaL_checkstring(L, 3));
4289
4290 /* Push in the stack the "response" entry. */
4291 ret = lua_getfield(L, 1, "response");
4292 if (ret != LUA_TTABLE) {
4293 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4294 "is expected as an array. %s found", lua_typename(L, ret));
4295 WILL_LJMP(lua_error(L));
4296 }
4297
4298 /* check if the header is already registered if it is not
4299 * the case, register it.
4300 */
4301 ret = lua_getfield(L, -1, name);
4302 if (ret == LUA_TNIL) {
4303
4304 /* Entry not found. */
4305 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4306
4307 /* Insert the new header name in the array in the top of the stack.
4308 * It left the new array in the top of the stack.
4309 */
4310 lua_newtable(L);
4311 lua_pushvalue(L, 2);
4312 lua_pushvalue(L, -2);
4313 lua_settable(L, -4);
4314
4315 } else if (ret != LUA_TTABLE) {
4316
4317 /* corruption error. */
4318 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4319 "is expected as an array. %s found", name, lua_typename(L, ret));
4320 WILL_LJMP(lua_error(L));
4321 }
4322
4323 /* Now the top od thestack is an array of values. We push
4324 * the header value as new entry.
4325 */
4326 lua_pushvalue(L, 3);
4327 ret = lua_rawlen(L, -2);
4328 lua_rawseti(L, -2, ret + 1);
4329 lua_pushboolean(L, 1);
4330 return 1;
4331}
4332
4333__LJMP static int hlua_applet_http_status(lua_State *L)
4334{
4335 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4336 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004337 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004338
4339 if (status < 100 || status > 599) {
4340 lua_pushboolean(L, 0);
4341 return 1;
4342 }
4343
4344 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004345 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004346 lua_pushboolean(L, 1);
4347 return 1;
4348}
4349
4350/* We will build the status line and the headers of the HTTP response.
4351 * We will try send at once if its not possible, we give back the hand
4352 * waiting for more room.
4353 */
4354__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4355{
4356 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4357 struct stream_interface *si = appctx->appctx->owner;
4358 struct channel *chn = si_ic(si);
4359 int ret;
4360 size_t len;
4361 const char *msg;
4362
4363 /* Get the message as the first argument on the stack. */
4364 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4365
4366 /* Send the message at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004367 ret = ci_putblk(chn, msg, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004368
4369 /* if ret == -2 or -3 the channel closed or the message si too
4370 * big for the buffers.
4371 */
4372 if (ret == -2 || ret == -3) {
4373 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4374 WILL_LJMP(lua_error(L));
4375 }
4376
4377 /* If ret is -1, we dont have room in the buffer, so we yield. */
4378 if (ret == -1) {
4379 si_applet_cant_put(si);
4380 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
4381 }
4382
4383 /* Headers sent, set the flag. */
4384 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4385 return 0;
4386}
4387
4388__LJMP static int hlua_applet_http_start_response(lua_State *L)
4389{
4390 struct chunk *tmp = get_trash_chunk();
4391 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004392 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02004393 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004394 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02004395 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004396 int id;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004397 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004398 int hdr_chunked = 0;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004399 const char *reason = appctx->appctx->ctx.hlua_apphttp.reason;
4400
4401 if (reason == NULL)
4402 reason = get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004403
4404 /* Use the same http version than the request. */
4405 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004406 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004407 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004408 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004409
4410 /* Get the array associated to the field "response" in the object AppletHTTP. */
4411 lua_pushvalue(L, 0);
4412 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4413 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4414 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4415 WILL_LJMP(lua_error(L));
4416 }
4417
4418 /* Browse the list of headers. */
4419 lua_pushnil(L);
4420 while(lua_next(L, -2) != 0) {
4421
4422 /* We expect a string as -2. */
4423 if (lua_type(L, -2) != LUA_TSTRING) {
4424 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4425 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4426 lua_typename(L, lua_type(L, -2)));
4427 WILL_LJMP(lua_error(L));
4428 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004429 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004430
4431 /* We expect an array as -1. */
4432 if (lua_type(L, -1) != LUA_TTABLE) {
4433 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4434 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4435 name,
4436 lua_typename(L, lua_type(L, -1)));
4437 WILL_LJMP(lua_error(L));
4438 }
4439
4440 /* Browse the table who is on the top of the stack. */
4441 lua_pushnil(L);
4442 while(lua_next(L, -2) != 0) {
4443
4444 /* We expect a number as -2. */
4445 if (lua_type(L, -2) != LUA_TNUMBER) {
4446 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4447 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4448 name,
4449 lua_typename(L, lua_type(L, -2)));
4450 WILL_LJMP(lua_error(L));
4451 }
4452 id = lua_tointeger(L, -2);
4453
4454 /* We expect a string as -2. */
4455 if (lua_type(L, -1) != LUA_TSTRING) {
4456 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4457 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4458 name, id,
4459 lua_typename(L, lua_type(L, -1)));
4460 WILL_LJMP(lua_error(L));
4461 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004462 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004463
4464 /* Catenate a new header. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004465 if (tmp->len + name_len + 2 + value_len + 2 < tmp->size) {
4466 memcpy(tmp->str + tmp->len, name, name_len);
4467 tmp->len += name_len;
4468 tmp->str[tmp->len++] = ':';
4469 tmp->str[tmp->len++] = ' ';
4470
4471 memcpy(tmp->str + tmp->len, value, value_len);
4472 tmp->len += value_len;
4473 tmp->str[tmp->len++] = '\r';
4474 tmp->str[tmp->len++] = '\n';
4475 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004476
4477 /* Protocol checks. */
4478
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004479 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004480 * is done without control. If it contains a bad value,
4481 * the content-length remains negative so that we can
4482 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004483 */
Willy Tarreaua3294632017-08-23 11:24:47 +02004484 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004485 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004486
4487 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004488 if (name_len == 17 && value_len == 7 &&
4489 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004490 strcasecmp("chunked", value) == 0)
4491 hdr_chunked = 1;
4492
4493 /* Remove the array from the stack, and get next element with a remaining string. */
4494 lua_pop(L, 1);
4495 }
4496
4497 /* Remove the array from the stack, and get next element with a remaining string. */
4498 lua_pop(L, 1);
4499 }
4500
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004501 /* If we dont have a content-length set, and the HTTP version is 1.1
4502 * and the status code implies the presence of a message body, we must
4503 * announce a transfer encoding chunked. This is required by haproxy
4504 * for the keepalive compliance. If the applet annouces a transfer-encoding
4505 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004506 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004507 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004508 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
4509 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4510 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4511 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004512 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4513 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4514 }
4515
4516 /* Finalize headers. */
4517 chunk_appendf(tmp, "\r\n");
4518
4519 /* Remove the last entry and the array of headers */
4520 lua_pop(L, 2);
4521
4522 /* Push the headers block. */
4523 lua_pushlstring(L, tmp->str, tmp->len);
4524
4525 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4526}
4527
4528/*
4529 *
4530 *
4531 * Class HTTP
4532 *
4533 *
4534 */
4535
4536/* Returns a struct hlua_txn if the stack entry "ud" is
4537 * a class stream, otherwise it throws an error.
4538 */
4539__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4540{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004541 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004542}
4543
4544/* This function creates and push in the stack a HTTP object
4545 * according with a current TXN.
4546 */
4547static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4548{
4549 struct hlua_txn *htxn;
4550
4551 /* Check stack size. */
4552 if (!lua_checkstack(L, 3))
4553 return 0;
4554
4555 /* Create the object: obj[0] = userdata.
4556 * Note that the base of the Converters object is the
4557 * same than the TXN object.
4558 */
4559 lua_newtable(L);
4560 htxn = lua_newuserdata(L, sizeof(*htxn));
4561 lua_rawseti(L, -2, 0);
4562
4563 htxn->s = txn->s;
4564 htxn->p = txn->p;
4565
4566 /* Pop a class stream metatable and affect it to the table. */
4567 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4568 lua_setmetatable(L, -2);
4569
4570 return 1;
4571}
4572
4573/* This function creates ans returns an array of HTTP headers.
4574 * This function does not fails. It is used as wrapper with the
4575 * 2 following functions.
4576 */
4577__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4578{
4579 const char *cur_ptr, *cur_next, *p;
4580 int old_idx, cur_idx;
4581 struct hdr_idx_elem *cur_hdr;
4582 const char *hn, *hv;
4583 int hnl, hvl;
4584 int type;
4585 const char *in;
4586 char *out;
4587 int len;
4588
4589 /* Create the table. */
4590 lua_newtable(L);
4591
4592 if (!htxn->s->txn)
4593 return 1;
4594
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004595 /* Check if a valid response is parsed */
4596 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4597 return 1;
4598
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004599 /* Build array of headers. */
4600 old_idx = 0;
4601 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4602
4603 while (1) {
4604 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4605 if (!cur_idx)
4606 break;
4607 old_idx = cur_idx;
4608
4609 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4610 cur_ptr = cur_next;
4611 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4612
4613 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4614 * and the next header starts at cur_next. We'll check
4615 * this header in the list as well as against the default
4616 * rule.
4617 */
4618
4619 /* look for ': *'. */
4620 hn = cur_ptr;
4621 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4622 if (p >= cur_ptr+cur_hdr->len)
4623 continue;
4624 hnl = p - hn;
4625 p++;
4626 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4627 p++;
4628 if (p >= cur_ptr+cur_hdr->len)
4629 continue;
4630 hv = p;
4631 hvl = cur_ptr+cur_hdr->len-p;
4632
4633 /* Lowercase the key. Don't check the size of trash, it have
4634 * the size of one buffer and the input data contains in one
4635 * buffer.
4636 */
4637 out = trash.str;
4638 for (in=hn; in<hn+hnl; in++, out++)
4639 *out = tolower(*in);
4640 *out = '\0';
4641
4642 /* Check for existing entry:
4643 * assume that the table is on the top of the stack, and
4644 * push the key in the stack, the function lua_gettable()
4645 * perform the lookup.
4646 */
4647 lua_pushlstring(L, trash.str, hnl);
4648 lua_gettable(L, -2);
4649 type = lua_type(L, -1);
4650
4651 switch (type) {
4652 case LUA_TNIL:
4653 /* Table not found, create it. */
4654 lua_pop(L, 1); /* remove the nil value. */
4655 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4656 lua_newtable(L); /* create and push empty table. */
4657 lua_pushlstring(L, hv, hvl); /* push header value. */
4658 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4659 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4660 break;
4661
4662 case LUA_TTABLE:
4663 /* Entry found: push the value in the table. */
4664 len = lua_rawlen(L, -1);
4665 lua_pushlstring(L, hv, hvl); /* push header value. */
4666 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4667 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4668 break;
4669
4670 default:
4671 /* Other cases are errors. */
4672 hlua_pusherror(L, "internal error during the parsing of headers.");
4673 WILL_LJMP(lua_error(L));
4674 }
4675 }
4676
4677 return 1;
4678}
4679
4680__LJMP static int hlua_http_req_get_headers(lua_State *L)
4681{
4682 struct hlua_txn *htxn;
4683
4684 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4685 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4686
4687 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4688}
4689
4690__LJMP static int hlua_http_res_get_headers(lua_State *L)
4691{
4692 struct hlua_txn *htxn;
4693
4694 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4695 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4696
4697 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4698}
4699
4700/* This function replace full header, or just a value in
4701 * the request or in the response. It is a wrapper fir the
4702 * 4 following functions.
4703 */
4704__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4705 struct http_msg *msg, int action)
4706{
4707 size_t name_len;
4708 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4709 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4710 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4711 struct my_regex re;
4712
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004713 /* Check if a valid response is parsed */
4714 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4715 return 0;
4716
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004717 if (!regex_comp(reg, &re, 1, 1, NULL))
4718 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4719
4720 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4721 regex_free(&re);
4722 return 0;
4723}
4724
4725__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4726{
4727 struct hlua_txn *htxn;
4728
4729 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4730 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4731
4732 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4733}
4734
4735__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4736{
4737 struct hlua_txn *htxn;
4738
4739 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4740 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4741
4742 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4743}
4744
4745__LJMP static int hlua_http_req_rep_val(lua_State *L)
4746{
4747 struct hlua_txn *htxn;
4748
4749 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4750 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4751
4752 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4753}
4754
4755__LJMP static int hlua_http_res_rep_val(lua_State *L)
4756{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004757 struct hlua_txn *htxn;
4758
4759 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4760 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4761
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004762 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004763}
4764
4765/* This function deletes all the occurences of an header.
4766 * It is a wrapper for the 2 following functions.
4767 */
4768__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4769{
4770 size_t len;
4771 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4772 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004773 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004774
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004775 /* Check if a valid response is parsed */
4776 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4777 return 0;
4778
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004779 ctx.idx = 0;
4780 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4781 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4782 return 0;
4783}
4784
4785__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4786{
4787 struct hlua_txn *htxn;
4788
4789 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4790 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4791
Willy Tarreaueee5b512015-04-03 23:46:31 +02004792 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004793}
4794
4795__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4796{
4797 struct hlua_txn *htxn;
4798
4799 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4800 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4801
Willy Tarreaueee5b512015-04-03 23:46:31 +02004802 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004803}
4804
4805/* This function adds an header. It is a wrapper used by
4806 * the 2 following functions.
4807 */
4808__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4809{
4810 size_t name_len;
4811 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4812 size_t value_len;
4813 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4814 char *p;
4815
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004816 /* Check if a valid message is parsed */
4817 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4818 return 0;
4819
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004820 /* Check length. */
4821 trash.len = value_len + name_len + 2;
4822 if (trash.len > trash.size)
4823 return 0;
4824
4825 /* Creates the header string. */
4826 p = trash.str;
4827 memcpy(p, name, name_len);
4828 p += name_len;
4829 *p = ':';
4830 p++;
4831 *p = ' ';
4832 p++;
4833 memcpy(p, value, value_len);
4834
Willy Tarreaueee5b512015-04-03 23:46:31 +02004835 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004836 trash.str, trash.len) != 0);
4837
4838 return 0;
4839}
4840
4841__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4842{
4843 struct hlua_txn *htxn;
4844
4845 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4846 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4847
Willy Tarreaueee5b512015-04-03 23:46:31 +02004848 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004849}
4850
4851__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4852{
4853 struct hlua_txn *htxn;
4854
4855 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4856 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4857
Willy Tarreaueee5b512015-04-03 23:46:31 +02004858 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004859}
4860
4861static int hlua_http_req_set_hdr(lua_State *L)
4862{
4863 struct hlua_txn *htxn;
4864
4865 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4866 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4867
Willy Tarreaueee5b512015-04-03 23:46:31 +02004868 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4869 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004870}
4871
4872static int hlua_http_res_set_hdr(lua_State *L)
4873{
4874 struct hlua_txn *htxn;
4875
4876 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4877 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4878
Willy Tarreaueee5b512015-04-03 23:46:31 +02004879 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4880 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004881}
4882
4883/* This function set the method. */
4884static int hlua_http_req_set_meth(lua_State *L)
4885{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004886 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004887 size_t name_len;
4888 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004889
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004890 /* Check if a valid request is parsed */
4891 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4892 lua_pushboolean(L, 0);
4893 return 1;
4894 }
4895
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004896 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004897 return 1;
4898}
4899
4900/* This function set the method. */
4901static int hlua_http_req_set_path(lua_State *L)
4902{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004903 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004904 size_t name_len;
4905 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004906
4907 /* Check if a valid request is parsed */
4908 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4909 lua_pushboolean(L, 0);
4910 return 1;
4911 }
4912
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004913 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004914 return 1;
4915}
4916
4917/* This function set the query-string. */
4918static int hlua_http_req_set_query(lua_State *L)
4919{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004920 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004921 size_t name_len;
4922 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004923
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004924 /* Check if a valid request is parsed */
4925 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4926 lua_pushboolean(L, 0);
4927 return 1;
4928 }
4929
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004930 /* Check length. */
4931 if (name_len > trash.size - 1) {
4932 lua_pushboolean(L, 0);
4933 return 1;
4934 }
4935
4936 /* Add the mark question as prefix. */
4937 chunk_reset(&trash);
4938 trash.str[trash.len++] = '?';
4939 memcpy(trash.str + trash.len, name, name_len);
4940 trash.len += name_len;
4941
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004942 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004943 return 1;
4944}
4945
4946/* This function set the uri. */
4947static int hlua_http_req_set_uri(lua_State *L)
4948{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004949 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004950 size_t name_len;
4951 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004952
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004953 /* Check if a valid request is parsed */
4954 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4955 lua_pushboolean(L, 0);
4956 return 1;
4957 }
4958
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004959 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004960 return 1;
4961}
4962
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004963/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004964static int hlua_http_res_set_status(lua_State *L)
4965{
4966 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4967 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004968 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004969
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004970 /* Check if a valid response is parsed */
4971 if (unlikely(htxn->s->txn->rsp.msg_state < HTTP_MSG_BODY))
4972 return 0;
4973
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004974 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004975 return 0;
4976}
4977
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004978/*
4979 *
4980 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004981 * Class TXN
4982 *
4983 *
4984 */
4985
4986/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004987 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004988 */
4989__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
4990{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004991 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004992}
4993
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004994__LJMP static int hlua_set_var(lua_State *L)
4995{
4996 struct hlua_txn *htxn;
4997 const char *name;
4998 size_t len;
4999 struct sample smp;
5000
5001 MAY_LJMP(check_args(L, 3, "set_var"));
5002
5003 /* It is useles to retrieve the stream, but this function
5004 * runs only in a stream context.
5005 */
5006 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5007 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5008
5009 /* Converts the third argument in a sample. */
5010 hlua_lua2smp(L, 3, &smp);
5011
5012 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005013 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005014 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005015 return 0;
5016}
5017
Christopher Faulet85d79c92016-11-09 16:54:56 +01005018__LJMP static int hlua_unset_var(lua_State *L)
5019{
5020 struct hlua_txn *htxn;
5021 const char *name;
5022 size_t len;
5023 struct sample smp;
5024
5025 MAY_LJMP(check_args(L, 2, "unset_var"));
5026
5027 /* It is useles to retrieve the stream, but this function
5028 * runs only in a stream context.
5029 */
5030 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5031 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5032
5033 /* Unset the variable. */
5034 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
5035 vars_unset_by_name(name, len, &smp);
5036 return 0;
5037}
5038
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005039__LJMP static int hlua_get_var(lua_State *L)
5040{
5041 struct hlua_txn *htxn;
5042 const char *name;
5043 size_t len;
5044 struct sample smp;
5045
5046 MAY_LJMP(check_args(L, 2, "get_var"));
5047
5048 /* It is useles to retrieve the stream, but this function
5049 * runs only in a stream context.
5050 */
5051 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5052 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5053
Willy Tarreau7560dd42016-03-10 16:28:58 +01005054 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005055 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005056 lua_pushnil(L);
5057 return 1;
5058 }
5059
5060 return hlua_smp2lua(L, &smp);
5061}
5062
Willy Tarreau59551662015-03-10 14:23:13 +01005063__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005064{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005065 struct hlua *hlua;
5066
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005067 MAY_LJMP(check_args(L, 2, "set_priv"));
5068
Willy Tarreau87b09662015-04-03 00:22:06 +02005069 /* It is useles to retrieve the stream, but this function
5070 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005071 */
5072 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005073 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005074
5075 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005076 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005077
5078 /* Get and store new value. */
5079 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5080 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5081
5082 return 0;
5083}
5084
Willy Tarreau59551662015-03-10 14:23:13 +01005085__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005086{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005087 struct hlua *hlua;
5088
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005089 MAY_LJMP(check_args(L, 1, "get_priv"));
5090
Willy Tarreau87b09662015-04-03 00:22:06 +02005091 /* It is useles to retrieve the stream, but this function
5092 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005093 */
5094 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005095 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005096
5097 /* Push configuration index in the stack. */
5098 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5099
5100 return 1;
5101}
5102
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005103/* Create stack entry containing a class TXN. This function
5104 * return 0 if the stack does not contains free slots,
5105 * otherwise it returns 1.
5106 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005107static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005108{
Willy Tarreaude491382015-04-06 11:04:28 +02005109 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005110
5111 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005112 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005113 return 0;
5114
5115 /* NOTE: The allocation never fails. The failure
5116 * throw an error, and the function never returns.
5117 * if the throw is not avalaible, the process is aborted.
5118 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005119 /* Create the object: obj[0] = userdata. */
5120 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005121 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005122 lua_rawseti(L, -2, 0);
5123
Willy Tarreaude491382015-04-06 11:04:28 +02005124 htxn->s = s;
5125 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005126 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005127 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005128
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005129 /* Create the "f" field that contains a list of fetches. */
5130 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005131 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005132 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005133 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005134
5135 /* Create the "sf" field that contains a list of stringsafe fetches. */
5136 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005137 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005138 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005139 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005140
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005141 /* Create the "c" field that contains a list of converters. */
5142 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005143 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005144 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005145 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005146
5147 /* Create the "sc" field that contains a list of stringsafe converters. */
5148 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005149 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005150 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005151 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005152
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005153 /* Create the "req" field that contains the request channel object. */
5154 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005155 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005156 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005157 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005158
5159 /* Create the "res" field that contains the response channel object. */
5160 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005161 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005162 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005163 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005164
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005165 /* Creates the HTTP object is the current proxy allows http. */
5166 lua_pushstring(L, "http");
5167 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005168 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005169 return 0;
5170 }
5171 else
5172 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005173 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005174
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005175 /* Pop a class sesison metatable and affect it to the userdata. */
5176 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5177 lua_setmetatable(L, -2);
5178
5179 return 1;
5180}
5181
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005182__LJMP static int hlua_txn_deflog(lua_State *L)
5183{
5184 const char *msg;
5185 struct hlua_txn *htxn;
5186
5187 MAY_LJMP(check_args(L, 2, "deflog"));
5188 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5189 msg = MAY_LJMP(luaL_checkstring(L, 2));
5190
5191 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5192 return 0;
5193}
5194
5195__LJMP static int hlua_txn_log(lua_State *L)
5196{
5197 int level;
5198 const char *msg;
5199 struct hlua_txn *htxn;
5200
5201 MAY_LJMP(check_args(L, 3, "log"));
5202 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5203 level = MAY_LJMP(luaL_checkinteger(L, 2));
5204 msg = MAY_LJMP(luaL_checkstring(L, 3));
5205
5206 if (level < 0 || level >= NB_LOG_LEVELS)
5207 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5208
5209 hlua_sendlog(htxn->s->be, level, msg);
5210 return 0;
5211}
5212
5213__LJMP static int hlua_txn_log_debug(lua_State *L)
5214{
5215 const char *msg;
5216 struct hlua_txn *htxn;
5217
5218 MAY_LJMP(check_args(L, 2, "Debug"));
5219 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5220 msg = MAY_LJMP(luaL_checkstring(L, 2));
5221 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5222 return 0;
5223}
5224
5225__LJMP static int hlua_txn_log_info(lua_State *L)
5226{
5227 const char *msg;
5228 struct hlua_txn *htxn;
5229
5230 MAY_LJMP(check_args(L, 2, "Info"));
5231 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5232 msg = MAY_LJMP(luaL_checkstring(L, 2));
5233 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5234 return 0;
5235}
5236
5237__LJMP static int hlua_txn_log_warning(lua_State *L)
5238{
5239 const char *msg;
5240 struct hlua_txn *htxn;
5241
5242 MAY_LJMP(check_args(L, 2, "Warning"));
5243 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5244 msg = MAY_LJMP(luaL_checkstring(L, 2));
5245 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5246 return 0;
5247}
5248
5249__LJMP static int hlua_txn_log_alert(lua_State *L)
5250{
5251 const char *msg;
5252 struct hlua_txn *htxn;
5253
5254 MAY_LJMP(check_args(L, 2, "Alert"));
5255 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5256 msg = MAY_LJMP(luaL_checkstring(L, 2));
5257 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5258 return 0;
5259}
5260
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005261__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5262{
5263 struct hlua_txn *htxn;
5264 int ll;
5265
5266 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5267 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5268 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5269
5270 if (ll < 0 || ll > 7)
5271 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5272
5273 htxn->s->logs.level = ll;
5274 return 0;
5275}
5276
5277__LJMP static int hlua_txn_set_tos(lua_State *L)
5278{
5279 struct hlua_txn *htxn;
5280 struct connection *cli_conn;
5281 int tos;
5282
5283 MAY_LJMP(check_args(L, 2, "set_tos"));
5284 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5285 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5286
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005287 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005288 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005289
5290 return 0;
5291}
5292
5293__LJMP static int hlua_txn_set_mark(lua_State *L)
5294{
5295#ifdef SO_MARK
5296 struct hlua_txn *htxn;
5297 struct connection *cli_conn;
5298 int mark;
5299
5300 MAY_LJMP(check_args(L, 2, "set_mark"));
5301 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5302 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5303
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005304 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005305 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005306#endif
5307 return 0;
5308}
5309
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005310/* This function is an Lua binding that send pending data
5311 * to the client, and close the stream interface.
5312 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005313__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005314{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005315 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005316 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01005317 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005318
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005319 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005320 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005321 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005322
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005323 /* If the flags NOTERM is set, we cannot terminate the http
5324 * session, so we just end the execution of the current
5325 * lua code.
5326 */
5327 if (htxn->flags & HLUA_TXN_NOTERM) {
5328 WILL_LJMP(hlua_done(L));
5329 return 0;
5330 }
5331
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005332 ic = &htxn->s->req;
5333 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005334
Willy Tarreau630ef452015-08-28 10:06:15 +02005335 if (htxn->s->txn) {
5336 /* HTTP mode, let's stay in sync with the stream */
5337 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
5338 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
5339 htxn->s->txn->req.sov = 0;
5340 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
5341 oc->analysers = AN_RES_HTTP_XFER_BODY;
5342 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
5343 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
5344
Willy Tarreau630ef452015-08-28 10:06:15 +02005345 /* Note that if we want to support keep-alive, we need
5346 * to bypass the close/shutr_now calls below, but that
5347 * may only be done if the HTTP request was already
5348 * processed and the connection header is known (ie
5349 * not during TCP rules).
5350 */
5351 }
5352
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005353 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01005354 channel_abort(ic);
5355 channel_auto_close(ic);
5356 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005357
5358 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01005359 channel_auto_read(oc);
5360 channel_auto_close(oc);
5361 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005362
Willy Tarreau0458b082015-08-28 09:40:04 +02005363 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005364
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005365 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005366 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005367 return 0;
5368}
5369
5370__LJMP static int hlua_log(lua_State *L)
5371{
5372 int level;
5373 const char *msg;
5374
5375 MAY_LJMP(check_args(L, 2, "log"));
5376 level = MAY_LJMP(luaL_checkinteger(L, 1));
5377 msg = MAY_LJMP(luaL_checkstring(L, 2));
5378
5379 if (level < 0 || level >= NB_LOG_LEVELS)
5380 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5381
5382 hlua_sendlog(NULL, level, msg);
5383 return 0;
5384}
5385
5386__LJMP static int hlua_log_debug(lua_State *L)
5387{
5388 const char *msg;
5389
5390 MAY_LJMP(check_args(L, 1, "debug"));
5391 msg = MAY_LJMP(luaL_checkstring(L, 1));
5392 hlua_sendlog(NULL, LOG_DEBUG, msg);
5393 return 0;
5394}
5395
5396__LJMP static int hlua_log_info(lua_State *L)
5397{
5398 const char *msg;
5399
5400 MAY_LJMP(check_args(L, 1, "info"));
5401 msg = MAY_LJMP(luaL_checkstring(L, 1));
5402 hlua_sendlog(NULL, LOG_INFO, msg);
5403 return 0;
5404}
5405
5406__LJMP static int hlua_log_warning(lua_State *L)
5407{
5408 const char *msg;
5409
5410 MAY_LJMP(check_args(L, 1, "warning"));
5411 msg = MAY_LJMP(luaL_checkstring(L, 1));
5412 hlua_sendlog(NULL, LOG_WARNING, msg);
5413 return 0;
5414}
5415
5416__LJMP static int hlua_log_alert(lua_State *L)
5417{
5418 const char *msg;
5419
5420 MAY_LJMP(check_args(L, 1, "alert"));
5421 msg = MAY_LJMP(luaL_checkstring(L, 1));
5422 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005423 return 0;
5424}
5425
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005426__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005427{
5428 int wakeup_ms = lua_tointeger(L, -1);
5429 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005430 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005431 return 0;
5432}
5433
5434__LJMP static int hlua_sleep(lua_State *L)
5435{
5436 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005437 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005438
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005439 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005440
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005441 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005442 wakeup_ms = tick_add(now_ms, delay);
5443 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005444
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005445 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5446 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005447}
5448
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005449__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005450{
5451 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005452 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005453
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005454 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005455
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005456 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005457 wakeup_ms = tick_add(now_ms, delay);
5458 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005459
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005460 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5461 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005462}
5463
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005464/* This functionis an LUA binding. it permits to give back
5465 * the hand at the HAProxy scheduler. It is used when the
5466 * LUA processing consumes a lot of time.
5467 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005468__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005469{
5470 return 0;
5471}
5472
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005473__LJMP static int hlua_yield(lua_State *L)
5474{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005475 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
5476 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005477}
5478
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005479/* This function change the nice of the currently executed
5480 * task. It is used set low or high priority at the current
5481 * task.
5482 */
Willy Tarreau59551662015-03-10 14:23:13 +01005483__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005484{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005485 struct hlua *hlua;
5486 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005487
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005488 MAY_LJMP(check_args(L, 1, "set_nice"));
5489 hlua = hlua_gethlua(L);
5490 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005491
5492 /* If he task is not set, I'm in a start mode. */
5493 if (!hlua || !hlua->task)
5494 return 0;
5495
5496 if (nice < -1024)
5497 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005498 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005499 nice = 1024;
5500
5501 hlua->task->nice = nice;
5502 return 0;
5503}
5504
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005505/* This function is used as a calback of a task. It is called by the
5506 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5507 * return an E_AGAIN signal, the emmiter of this signal must set a
5508 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005509 *
5510 * Task wrapper are longjmp safe because the only one Lua code
5511 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005512 */
5513static struct task *hlua_process_task(struct task *task)
5514{
5515 struct hlua *hlua = task->context;
5516 enum hlua_exec status;
5517
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005518 /* If it is the first call to the task, we must initialize the
5519 * execution timeouts.
5520 */
5521 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005522 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005523
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005524 /* Execute the Lua code. */
5525 status = hlua_ctx_resume(hlua, 1);
5526
5527 switch (status) {
5528 /* finished or yield */
5529 case HLUA_E_OK:
5530 hlua_ctx_destroy(hlua);
5531 task_delete(task);
5532 task_free(task);
5533 break;
5534
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005535 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01005536 notification_gc(&hlua->com);
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005537 if (hlua->wake_time != TICK_ETERNITY)
Emeric Brun253e53e2017-10-17 18:58:40 +02005538 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005539 break;
5540
5541 /* finished with error. */
5542 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005543 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005544 hlua_ctx_destroy(hlua);
5545 task_delete(task);
5546 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02005547 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005548 break;
5549
5550 case HLUA_E_ERR:
5551 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005552 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005553 hlua_ctx_destroy(hlua);
5554 task_delete(task);
5555 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02005556 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005557 break;
5558 }
Emeric Brun253e53e2017-10-17 18:58:40 +02005559 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005560}
5561
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005562/* This function is an LUA binding that register LUA function to be
5563 * executed after the HAProxy configuration parsing and before the
5564 * HAProxy scheduler starts. This function expect only one LUA
5565 * argument that is a function. This function returns nothing, but
5566 * throws if an error is encountered.
5567 */
5568__LJMP static int hlua_register_init(lua_State *L)
5569{
5570 struct hlua_init_function *init;
5571 int ref;
5572
5573 MAY_LJMP(check_args(L, 1, "register_init"));
5574
5575 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5576
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005577 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005578 if (!init)
5579 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5580
5581 init->function_ref = ref;
5582 LIST_ADDQ(&hlua_init_functions, &init->l);
5583 return 0;
5584}
5585
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005586/* This functio is an LUA binding. It permits to register a task
5587 * executed in parallel of the main HAroxy activity. The task is
5588 * created and it is set in the HAProxy scheduler. It can be called
5589 * from the "init" section, "post init" or during the runtime.
5590 *
5591 * Lua prototype:
5592 *
5593 * <none> core.register_task(<function>)
5594 */
5595static int hlua_register_task(lua_State *L)
5596{
5597 struct hlua *hlua;
5598 struct task *task;
5599 int ref;
5600
5601 MAY_LJMP(check_args(L, 1, "register_task"));
5602
5603 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5604
Willy Tarreaubafbe012017-11-24 17:34:44 +01005605 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005606 if (!hlua)
5607 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5608
Emeric Brunc60def82017-09-27 14:59:38 +02005609 task = task_new(MAX_THREADS_MASK);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005610 task->context = hlua;
5611 task->process = hlua_process_task;
5612
5613 if (!hlua_ctx_init(hlua, task))
5614 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5615
5616 /* Restore the function in the stack. */
5617 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5618 hlua->nargs = 0;
5619
5620 /* Schedule task. */
5621 task_schedule(task, now_ms);
5622
5623 return 0;
5624}
5625
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005626/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5627 * doesn't allow "yield" functions because the HAProxy engine cannot
5628 * resume converters.
5629 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005630static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005631{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005632 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005633 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005634 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005635
Willy Tarreaube508f12016-03-10 11:47:01 +01005636 if (!stream)
5637 return 0;
5638
Willy Tarreau87b09662015-04-03 00:22:06 +02005639 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005640 * Lua context can be not initialized. This behavior
5641 * permits to save performances because a systematic
5642 * Lua initialization cause 5% performances loss.
5643 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005644 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005645 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005646 if (!stream->hlua) {
5647 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5648 return 0;
5649 }
5650 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5651 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5652 return 0;
5653 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005654 }
5655
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005656 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005657 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005658
5659 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005660 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5661 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5662 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005663 else
5664 error = "critical error";
5665 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005666 return 0;
5667 }
5668
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005669 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005670 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005671 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005672 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005673 return 0;
5674 }
5675
5676 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005677 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005678
5679 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005680 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005681 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005682 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005683 return 0;
5684 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005685 hlua_smp2lua(stream->hlua->T, smp);
5686 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005687
5688 /* push keywords in the stack. */
5689 if (arg_p) {
5690 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005691 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005692 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005693 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005694 return 0;
5695 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005696 hlua_arg2lua(stream->hlua->T, arg_p);
5697 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005698 }
5699 }
5700
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005701 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005702 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005703
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005704 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005705 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005706 }
5707
5708 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005709 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005710 /* finished. */
5711 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005712 /* If the stack is empty, the function fails. */
5713 if (lua_gettop(stream->hlua->T) <= 0)
5714 return 0;
5715
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005716 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005717 hlua_lua2smp(stream->hlua->T, -1, smp);
5718 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005719 return 1;
5720
5721 /* yield. */
5722 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005723 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005724 return 0;
5725
5726 /* finished with error. */
5727 case HLUA_E_ERRMSG:
5728 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005729 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005730 fcn->name, lua_tostring(stream->hlua->T, -1));
5731 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005732 return 0;
5733
5734 case HLUA_E_ERR:
5735 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005736 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005737
5738 default:
5739 return 0;
5740 }
5741}
5742
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005743/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5744 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005745 * resume sample-fetches. This function will be called by the sample
5746 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005747 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005748static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5749 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005750{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005751 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005752 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005753 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005754 const struct chunk msg = { .len = 0 };
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005755
Willy Tarreaube508f12016-03-10 11:47:01 +01005756 if (!stream)
5757 return 0;
5758
Willy Tarreau87b09662015-04-03 00:22:06 +02005759 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005760 * Lua context can be not initialized. This behavior
5761 * permits to save performances because a systematic
5762 * Lua initialization cause 5% performances loss.
5763 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005764 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005765 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005766 if (!stream->hlua) {
5767 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5768 return 0;
5769 }
5770 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5771 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5772 return 0;
5773 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005774 }
5775
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005776 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005777
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005778 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005779 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005780
5781 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005782 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5783 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5784 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005785 else
5786 error = "critical error";
5787 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005788 return 0;
5789 }
5790
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005791 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005792 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005793 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005794 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005795 return 0;
5796 }
5797
5798 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005799 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005800
5801 /* push arguments in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005802 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR,
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005803 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005804 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005805 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005806 return 0;
5807 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005808 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005809
5810 /* push keywords in the stack. */
5811 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5812 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005813 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005814 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005815 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005816 return 0;
5817 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005818 hlua_arg2lua(stream->hlua->T, arg_p);
5819 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005820 }
5821
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005822 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005823 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005824
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005825 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005826 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005827 }
5828
5829 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005830 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005831 /* finished. */
5832 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005833 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005834 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005835 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005836 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005837 /* If the stack is empty, the function fails. */
5838 if (lua_gettop(stream->hlua->T) <= 0)
5839 return 0;
5840
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005841 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005842 hlua_lua2smp(stream->hlua->T, -1, smp);
5843 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005844
5845 /* Set the end of execution flag. */
5846 smp->flags &= ~SMP_F_MAY_CHANGE;
5847 return 1;
5848
5849 /* yield. */
5850 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005851 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005852 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005853 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005854 return 0;
5855
5856 /* finished with error. */
5857 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005858 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005859 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005860 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005861 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005862 fcn->name, lua_tostring(stream->hlua->T, -1));
5863 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005864 return 0;
5865
5866 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005867 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005868 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005869 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005870 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005871
5872 default:
5873 return 0;
5874 }
5875}
5876
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005877/* This function is an LUA binding used for registering
5878 * "sample-conv" functions. It expects a converter name used
5879 * in the haproxy configuration file, and an LUA function.
5880 */
5881__LJMP static int hlua_register_converters(lua_State *L)
5882{
5883 struct sample_conv_kw_list *sck;
5884 const char *name;
5885 int ref;
5886 int len;
5887 struct hlua_function *fcn;
5888
5889 MAY_LJMP(check_args(L, 2, "register_converters"));
5890
5891 /* First argument : converter name. */
5892 name = MAY_LJMP(luaL_checkstring(L, 1));
5893
5894 /* Second argument : lua function. */
5895 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5896
5897 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005898 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005899 if (!sck)
5900 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005901 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005902 if (!fcn)
5903 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5904
5905 /* Fill fcn. */
5906 fcn->name = strdup(name);
5907 if (!fcn->name)
5908 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5909 fcn->function_ref = ref;
5910
5911 /* List head */
5912 sck->list.n = sck->list.p = NULL;
5913
5914 /* converter keyword. */
5915 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005916 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005917 if (!sck->kw[0].kw)
5918 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5919
5920 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5921 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005922 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 +01005923 sck->kw[0].val_args = NULL;
5924 sck->kw[0].in_type = SMP_T_STR;
5925 sck->kw[0].out_type = SMP_T_STR;
5926 sck->kw[0].private = fcn;
5927
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005928 /* Register this new converter */
5929 sample_register_convs(sck);
5930
5931 return 0;
5932}
5933
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005934/* This fucntion is an LUA binding used for registering
5935 * "sample-fetch" functions. It expects a converter name used
5936 * in the haproxy configuration file, and an LUA function.
5937 */
5938__LJMP static int hlua_register_fetches(lua_State *L)
5939{
5940 const char *name;
5941 int ref;
5942 int len;
5943 struct sample_fetch_kw_list *sfk;
5944 struct hlua_function *fcn;
5945
5946 MAY_LJMP(check_args(L, 2, "register_fetches"));
5947
5948 /* First argument : sample-fetch name. */
5949 name = MAY_LJMP(luaL_checkstring(L, 1));
5950
5951 /* Second argument : lua function. */
5952 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5953
5954 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005955 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005956 if (!sfk)
5957 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005958 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005959 if (!fcn)
5960 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5961
5962 /* Fill fcn. */
5963 fcn->name = strdup(name);
5964 if (!fcn->name)
5965 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5966 fcn->function_ref = ref;
5967
5968 /* List head */
5969 sfk->list.n = sfk->list.p = NULL;
5970
5971 /* sample-fetch keyword. */
5972 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005973 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005974 if (!sfk->kw[0].kw)
5975 return luaL_error(L, "lua out of memory error.");
5976
5977 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
5978 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005979 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 +01005980 sfk->kw[0].val_args = NULL;
5981 sfk->kw[0].out_type = SMP_T_STR;
5982 sfk->kw[0].use = SMP_USE_HTTP_ANY;
5983 sfk->kw[0].val = 0;
5984 sfk->kw[0].private = fcn;
5985
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005986 /* Register this new fetch. */
5987 sample_register_fetches(sfk);
5988
5989 return 0;
5990}
5991
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005992/* This function is a wrapper to execute each LUA function declared
5993 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005994 * return ACT_RET_CONT if the processing is finished (with or without
5995 * error) and return ACT_RET_YIELD if the function must be called again
5996 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005997 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005998static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02005999 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006000{
6001 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006002 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006003 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006004 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006005 const struct chunk msg = { .len = 0 };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006006
6007 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01006008 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
6009 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
6010 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
6011 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006012 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006013 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006014 return ACT_RET_CONT;
6015 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006016
Willy Tarreau87b09662015-04-03 00:22:06 +02006017 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006018 * Lua context can be not initialized. This behavior
6019 * permits to save performances because a systematic
6020 * Lua initialization cause 5% performances loss.
6021 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006022 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006023 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006024 if (!s->hlua) {
6025 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6026 rule->arg.hlua_rule->fcn.name);
6027 return ACT_RET_CONT;
6028 }
6029 if (!hlua_ctx_init(s->hlua, s->task)) {
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 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006034 }
6035
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006036 consistency_set(s, dir, &s->hlua->cons);
6037
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006038 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006039 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006040
6041 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006042 if (!SET_SAFE_LJMP(s->hlua->T)) {
6043 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6044 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006045 else
6046 error = "critical error";
6047 SEND_ERR(px, "Lua function '%s': %s.\n",
6048 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006049 return ACT_RET_CONT;
6050 }
6051
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006052 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006053 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006054 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006055 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006056 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006057 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006058 }
6059
6060 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006061 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006062
Willy Tarreau87b09662015-04-03 00:22:06 +02006063 /* Create and and push object stream in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006064 if (!hlua_txn_new(s->hlua->T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006065 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006066 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006067 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006068 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006069 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006070 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006071
6072 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006073 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006074 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006075 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006076 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006077 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006078 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006079 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006080 lua_pushstring(s->hlua->T, *arg);
6081 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006082 }
6083
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006084 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006085 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006086
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006087 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006088 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006089 }
6090
6091 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006092 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006093 /* finished. */
6094 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006095 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006096 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006097 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006098 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006099 if (s->hlua->flags & HLUA_STOP)
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006100 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006101 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006102
6103 /* yield. */
6104 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006105 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006106 if (s->hlua->wake_time != TICK_ETERNITY) {
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006107 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006108 s->req.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006109 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006110 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006111 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006112 /* Some actions can be wake up when a "write" event
6113 * is detected on a response channel. This is useful
6114 * only for actions targetted on the requests.
6115 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006116 if (HLUA_IS_WAKERESWR(s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006117 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01006118 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006119 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006120 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006121 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006122 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006123 /* We can quit the fcuntion without consistency check
6124 * because HAProxy is not able to manipulate data, it
6125 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006126 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006127
6128 /* finished with error. */
6129 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006130 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006131 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006132 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006133 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006134 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006135 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006136 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6137 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006138 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006139
6140 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006141 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006142 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006143 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006144 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006145 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006146 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006147 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006148
6149 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006150 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006151 }
6152}
6153
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006154struct task *hlua_applet_wakeup(struct task *t)
6155{
6156 struct appctx *ctx = t->context;
6157 struct stream_interface *si = ctx->owner;
6158
6159 /* If the applet is wake up without any expected work, the sheduler
6160 * remove it from the run queue. This flag indicate that the applet
6161 * is waiting for write. If the buffer is full, the main processing
6162 * will send some data and after call the applet, otherwise it call
6163 * the applet ASAP.
6164 */
6165 si_applet_cant_put(si);
6166 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006167 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006168 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006169}
6170
6171static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6172{
6173 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006174 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006175 struct task *task;
6176 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006177 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006178
Willy Tarreaubafbe012017-11-24 17:34:44 +01006179 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006180 if (!hlua) {
6181 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6182 ctx->rule->arg.hlua_rule->fcn.name);
6183 return 0;
6184 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006185 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006186 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006187 ctx->ctx.hlua_apptcp.flags = 0;
6188
6189 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006190 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006191 if (!task) {
6192 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6193 ctx->rule->arg.hlua_rule->fcn.name);
6194 return 0;
6195 }
6196 task->nice = 0;
6197 task->context = ctx;
6198 task->process = hlua_applet_wakeup;
6199 ctx->ctx.hlua_apptcp.task = task;
6200
6201 /* In the execution wrappers linked with a stream, the
6202 * Lua context can be not initialized. This behavior
6203 * permits to save performances because a systematic
6204 * Lua initialization cause 5% performances loss.
6205 */
6206 if (!hlua_ctx_init(hlua, task)) {
6207 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6208 ctx->rule->arg.hlua_rule->fcn.name);
6209 return 0;
6210 }
6211
6212 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006213 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006214
6215 /* The following Lua calls can fail. */
6216 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006217 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6218 error = lua_tostring(hlua->T, -1);
6219 else
6220 error = "critical error";
6221 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6222 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006223 RESET_SAFE_LJMP(hlua->T);
6224 return 0;
6225 }
6226
6227 /* Check stack available size. */
6228 if (!lua_checkstack(hlua->T, 1)) {
6229 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6230 ctx->rule->arg.hlua_rule->fcn.name);
6231 RESET_SAFE_LJMP(hlua->T);
6232 return 0;
6233 }
6234
6235 /* Restore the function in the stack. */
6236 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6237
6238 /* Create and and push object stream in the stack. */
6239 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
6240 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6241 ctx->rule->arg.hlua_rule->fcn.name);
6242 RESET_SAFE_LJMP(hlua->T);
6243 return 0;
6244 }
6245 hlua->nargs = 1;
6246
6247 /* push keywords in the stack. */
6248 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6249 if (!lua_checkstack(hlua->T, 1)) {
6250 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6251 ctx->rule->arg.hlua_rule->fcn.name);
6252 RESET_SAFE_LJMP(hlua->T);
6253 return 0;
6254 }
6255 lua_pushstring(hlua->T, *arg);
6256 hlua->nargs++;
6257 }
6258
6259 RESET_SAFE_LJMP(hlua->T);
6260
6261 /* Wakeup the applet ASAP. */
6262 si_applet_cant_get(si);
6263 si_applet_cant_put(si);
6264
6265 return 1;
6266}
6267
6268static void hlua_applet_tcp_fct(struct appctx *ctx)
6269{
6270 struct stream_interface *si = ctx->owner;
6271 struct stream *strm = si_strm(si);
6272 struct channel *res = si_ic(si);
6273 struct act_rule *rule = ctx->rule;
6274 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006275 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006276
6277 /* The applet execution is already done. */
6278 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
6279 return;
6280
6281 /* If the stream is disconnect or closed, ldo nothing. */
6282 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6283 return;
6284
6285 /* Execute the function. */
6286 switch (hlua_ctx_resume(hlua, 1)) {
6287 /* finished. */
6288 case HLUA_E_OK:
6289 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6290
6291 /* log time */
6292 strm->logs.tv_request = now;
6293
6294 /* eat the whole request */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006295 co_skip(si_oc(si), si_ob(si)->o);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006296 res->flags |= CF_READ_NULL;
6297 si_shutr(si);
6298 return;
6299
6300 /* yield. */
6301 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006302 if (hlua->wake_time != TICK_ETERNITY)
6303 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006304 return;
6305
6306 /* finished with error. */
6307 case HLUA_E_ERRMSG:
6308 /* Display log. */
6309 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6310 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6311 lua_pop(hlua->T, 1);
6312 goto error;
6313
6314 case HLUA_E_ERR:
6315 /* Display log. */
6316 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6317 rule->arg.hlua_rule->fcn.name);
6318 goto error;
6319
6320 default:
6321 goto error;
6322 }
6323
6324error:
6325
6326 /* For all other cases, just close the stream. */
6327 si_shutw(si);
6328 si_shutr(si);
6329 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6330}
6331
6332static void hlua_applet_tcp_release(struct appctx *ctx)
6333{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006334 task_delete(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006335 task_free(ctx->ctx.hlua_apptcp.task);
6336 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006337 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006338 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006339}
6340
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006341/* The function returns 1 if the initialisation is complete, 0 if
6342 * an errors occurs and -1 if more data are required for initializing
6343 * the applet.
6344 */
6345static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6346{
6347 struct stream_interface *si = ctx->owner;
6348 struct channel *req = si_oc(si);
6349 struct http_msg *msg;
6350 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006351 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006352 char **arg;
6353 struct hdr_ctx hdr;
6354 struct task *task;
6355 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01006356 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006357
6358 /* Wait for a full HTTP request. */
6359 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
6360 if (smp.flags & SMP_F_MAY_CHANGE)
6361 return -1;
6362 return 0;
6363 }
6364 txn = strm->txn;
6365 msg = &txn->req;
6366
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006367 /* We want two things in HTTP mode :
6368 * - enforce server-close mode if we were in keep-alive, so that the
6369 * applet is released after each response ;
6370 * - enable request body transfer to the applet in order to resync
6371 * with the response body.
6372 */
6373 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
6374 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006375
Willy Tarreaubafbe012017-11-24 17:34:44 +01006376 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006377 if (!hlua) {
6378 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6379 ctx->rule->arg.hlua_rule->fcn.name);
6380 return 0;
6381 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006382 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006383 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006384 ctx->ctx.hlua_apphttp.left_bytes = -1;
6385 ctx->ctx.hlua_apphttp.flags = 0;
6386
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006387 if (txn->req.flags & HTTP_MSGF_VER_11)
6388 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6389
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006390 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006391 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006392 if (!task) {
6393 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6394 ctx->rule->arg.hlua_rule->fcn.name);
6395 return 0;
6396 }
6397 task->nice = 0;
6398 task->context = ctx;
6399 task->process = hlua_applet_wakeup;
6400 ctx->ctx.hlua_apphttp.task = task;
6401
6402 /* In the execution wrappers linked with a stream, the
6403 * Lua context can be not initialized. This behavior
6404 * permits to save performances because a systematic
6405 * Lua initialization cause 5% performances loss.
6406 */
6407 if (!hlua_ctx_init(hlua, task)) {
6408 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6409 ctx->rule->arg.hlua_rule->fcn.name);
6410 return 0;
6411 }
6412
6413 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006414 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006415
6416 /* The following Lua calls can fail. */
6417 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006418 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6419 error = lua_tostring(hlua->T, -1);
6420 else
6421 error = "critical error";
6422 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6423 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006424 return 0;
6425 }
6426
6427 /* Check stack available size. */
6428 if (!lua_checkstack(hlua->T, 1)) {
6429 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6430 ctx->rule->arg.hlua_rule->fcn.name);
6431 RESET_SAFE_LJMP(hlua->T);
6432 return 0;
6433 }
6434
6435 /* Restore the function in the stack. */
6436 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6437
6438 /* Create and and push object stream in the stack. */
6439 if (!hlua_applet_http_new(hlua->T, ctx)) {
6440 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6441 ctx->rule->arg.hlua_rule->fcn.name);
6442 RESET_SAFE_LJMP(hlua->T);
6443 return 0;
6444 }
6445 hlua->nargs = 1;
6446
6447 /* Look for a 100-continue expected. */
6448 if (msg->flags & HTTP_MSGF_VER_11) {
6449 hdr.idx = 0;
6450 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
6451 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
6452 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
6453 }
6454
6455 /* push keywords in the stack. */
6456 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6457 if (!lua_checkstack(hlua->T, 1)) {
6458 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6459 ctx->rule->arg.hlua_rule->fcn.name);
6460 RESET_SAFE_LJMP(hlua->T);
6461 return 0;
6462 }
6463 lua_pushstring(hlua->T, *arg);
6464 hlua->nargs++;
6465 }
6466
6467 RESET_SAFE_LJMP(hlua->T);
6468
6469 /* Wakeup the applet when data is ready for read. */
6470 si_applet_cant_get(si);
6471
6472 return 1;
6473}
6474
6475static void hlua_applet_http_fct(struct appctx *ctx)
6476{
6477 struct stream_interface *si = ctx->owner;
6478 struct stream *strm = si_strm(si);
6479 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006480 struct act_rule *rule = ctx->rule;
6481 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006482 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006483 char *blk1;
6484 int len1;
6485 char *blk2;
6486 int len2;
6487 int ret;
6488
6489 /* If the stream is disconnect or closed, ldo nothing. */
6490 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6491 return;
6492
6493 /* Set the currently running flag. */
6494 if (!HLUA_IS_RUNNING(hlua) &&
6495 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6496
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006497 /* Wait for full HTTP analysys. */
6498 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6499 si_applet_cant_get(si);
6500 return;
6501 }
6502
6503 /* Store the max amount of bytes that we can read. */
6504 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6505
6506 /* We need to flush the request header. This left the body
6507 * for the Lua.
6508 */
6509
6510 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006511 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006512 if (ret == -1)
6513 return;
6514
6515 /* No data available, ask for more data. */
6516 if (ret == 1)
6517 len2 = 0;
6518 if (ret == 0)
6519 len1 = 0;
6520 if (len1 + len2 < strm->txn->req.eoh + 2) {
6521 si_applet_cant_get(si);
6522 return;
6523 }
6524
6525 /* skip the requests bytes. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006526 co_skip(si_oc(si), strm->txn->req.eoh + 2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006527 }
6528
6529 /* Executes The applet if it is not done. */
6530 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6531
6532 /* Execute the function. */
6533 switch (hlua_ctx_resume(hlua, 1)) {
6534 /* finished. */
6535 case HLUA_E_OK:
6536 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6537 break;
6538
6539 /* yield. */
6540 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006541 if (hlua->wake_time != TICK_ETERNITY)
6542 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006543 return;
6544
6545 /* finished with error. */
6546 case HLUA_E_ERRMSG:
6547 /* Display log. */
6548 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6549 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6550 lua_pop(hlua->T, 1);
6551 goto error;
6552
6553 case HLUA_E_ERR:
6554 /* Display log. */
6555 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6556 rule->arg.hlua_rule->fcn.name);
6557 goto error;
6558
6559 default:
6560 goto error;
6561 }
6562 }
6563
6564 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6565
6566 /* We must send the final chunk. */
6567 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6568 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6569
6570 /* sent last chunk at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006571 ret = ci_putblk(res, "0\r\n\r\n", 5);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006572
6573 /* critical error. */
6574 if (ret == -2 || ret == -3) {
6575 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6576 rule->arg.hlua_rule->fcn.name);
6577 goto error;
6578 }
6579
6580 /* no enough space error. */
6581 if (ret == -1) {
6582 si_applet_cant_put(si);
6583 return;
6584 }
6585
6586 /* set the last chunk sent. */
6587 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6588 }
6589
6590 /* close the connection. */
6591
6592 /* status / log */
6593 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6594 strm->logs.tv_request = now;
6595
6596 /* eat the whole request */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006597 co_skip(si_oc(si), si_ob(si)->o);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006598 res->flags |= CF_READ_NULL;
6599 si_shutr(si);
6600
6601 return;
6602 }
6603
6604error:
6605
6606 /* If we are in HTTP mode, and we are not send any
6607 * data, return a 500 server error in best effort:
6608 * if there are no room avalaible in the buffer,
6609 * just close the connection.
6610 */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006611 ci_putblk(res, error_500, strlen(error_500));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006612 if (!(strm->flags & SF_ERR_MASK))
6613 strm->flags |= SF_ERR_RESOURCE;
6614 si_shutw(si);
6615 si_shutr(si);
6616 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6617}
6618
6619static void hlua_applet_http_release(struct appctx *ctx)
6620{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006621 task_delete(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006622 task_free(ctx->ctx.hlua_apphttp.task);
6623 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006624 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006625 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006626}
6627
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006628/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6629 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006630 *
6631 * This function can fail with an abort() due to an Lua critical error.
6632 * We are in the configuration parsing process of HAProxy, this abort() is
6633 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006634 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006635static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6636 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006637{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006638 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006639 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006640
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006641 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006642 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006643 if (!rule->arg.hlua_rule) {
6644 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006645 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006646 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006647
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006648 /* Memory for arguments. */
6649 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
6650 if (!rule->arg.hlua_rule->args) {
6651 memprintf(err, "out of memory error");
6652 return ACT_RET_PRS_ERR;
6653 }
6654
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006655 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006656 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006657
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006658 /* Expect some arguments */
6659 for (i = 0; i < fcn->nargs; i++) {
6660 if (*args[i+1] == '\0') {
6661 memprintf(err, "expect %d arguments", fcn->nargs);
6662 return ACT_RET_PRS_ERR;
6663 }
6664 rule->arg.hlua_rule->args[i] = strdup(args[i + 1]);
6665 if (!rule->arg.hlua_rule->args[i]) {
6666 memprintf(err, "out of memory error");
6667 return ACT_RET_PRS_ERR;
6668 }
6669 (*cur_arg)++;
6670 }
6671 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006672
Thierry FOURNIER42148732015-09-02 17:17:33 +02006673 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006674 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006675 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006676}
6677
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006678static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6679 struct act_rule *rule, char **err)
6680{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006681 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006682
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006683 /* HTTP applets are forbidden in tcp-request rules.
6684 * HTTP applet request requires everything initilized by
6685 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6686 * The applet will be immediately initilized, but its before
6687 * the call of this analyzer.
6688 */
6689 if (rule->from != ACT_F_HTTP_REQ) {
6690 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6691 return ACT_RET_PRS_ERR;
6692 }
6693
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006694 /* Memory for the rule. */
6695 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6696 if (!rule->arg.hlua_rule) {
6697 memprintf(err, "out of memory error");
6698 return ACT_RET_PRS_ERR;
6699 }
6700
6701 /* Reference the Lua function and store the reference. */
6702 rule->arg.hlua_rule->fcn = *fcn;
6703
6704 /* TODO: later accept arguments. */
6705 rule->arg.hlua_rule->args = NULL;
6706
6707 /* Add applet pointer in the rule. */
6708 rule->applet.obj_type = OBJ_TYPE_APPLET;
6709 rule->applet.name = fcn->name;
6710 rule->applet.init = hlua_applet_http_init;
6711 rule->applet.fct = hlua_applet_http_fct;
6712 rule->applet.release = hlua_applet_http_release;
6713 rule->applet.timeout = hlua_timeout_applet;
6714
6715 return ACT_RET_PRS_OK;
6716}
6717
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006718/* This function is an LUA binding used for registering
6719 * "sample-conv" functions. It expects a converter name used
6720 * in the haproxy configuration file, and an LUA function.
6721 */
6722__LJMP static int hlua_register_action(lua_State *L)
6723{
6724 struct action_kw_list *akl;
6725 const char *name;
6726 int ref;
6727 int len;
6728 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006729 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006730
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006731 /* Initialise the number of expected arguments at 0. */
6732 nargs = 0;
6733
6734 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6735 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006736
6737 /* First argument : converter name. */
6738 name = MAY_LJMP(luaL_checkstring(L, 1));
6739
6740 /* Second argument : environment. */
6741 if (lua_type(L, 2) != LUA_TTABLE)
6742 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6743
6744 /* Third argument : lua function. */
6745 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6746
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006747 /* Fouth argument : number of mandatories arguments expected on the configuration line. */
6748 if (lua_gettop(L) >= 4)
6749 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
6750
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006751 /* browse the second argulent as an array. */
6752 lua_pushnil(L);
6753 while (lua_next(L, 2) != 0) {
6754 if (lua_type(L, -1) != LUA_TSTRING)
6755 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6756
6757 /* Check required environment. Only accepted "http" or "tcp". */
6758 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006759 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006760 if (!akl)
6761 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006762 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006763 if (!fcn)
6764 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6765
6766 /* Fill fcn. */
6767 fcn->name = strdup(name);
6768 if (!fcn->name)
6769 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6770 fcn->function_ref = ref;
6771
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006772 /* Set the expected number od arguments. */
6773 fcn->nargs = nargs;
6774
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006775 /* List head */
6776 akl->list.n = akl->list.p = NULL;
6777
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006778 /* action keyword. */
6779 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006780 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006781 if (!akl->kw[0].kw)
6782 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6783
6784 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6785
6786 akl->kw[0].match_pfx = 0;
6787 akl->kw[0].private = fcn;
6788 akl->kw[0].parse = action_register_lua;
6789
6790 /* select the action registering point. */
6791 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6792 tcp_req_cont_keywords_register(akl);
6793 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6794 tcp_res_cont_keywords_register(akl);
6795 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6796 http_req_keywords_register(akl);
6797 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6798 http_res_keywords_register(akl);
6799 else
6800 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
6801 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6802 "are expected.", lua_tostring(L, -1)));
6803
6804 /* pop the environment string. */
6805 lua_pop(L, 1);
6806 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006807 return ACT_RET_PRS_OK;
6808}
6809
6810static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6811 struct act_rule *rule, char **err)
6812{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006813 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006814
6815 /* Memory for the rule. */
6816 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6817 if (!rule->arg.hlua_rule) {
6818 memprintf(err, "out of memory error");
6819 return ACT_RET_PRS_ERR;
6820 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006821
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006822 /* Reference the Lua function and store the reference. */
6823 rule->arg.hlua_rule->fcn = *fcn;
6824
6825 /* TODO: later accept arguments. */
6826 rule->arg.hlua_rule->args = NULL;
6827
6828 /* Add applet pointer in the rule. */
6829 rule->applet.obj_type = OBJ_TYPE_APPLET;
6830 rule->applet.name = fcn->name;
6831 rule->applet.init = hlua_applet_tcp_init;
6832 rule->applet.fct = hlua_applet_tcp_fct;
6833 rule->applet.release = hlua_applet_tcp_release;
6834 rule->applet.timeout = hlua_timeout_applet;
6835
6836 return 0;
6837}
6838
6839/* This function is an LUA binding used for registering
6840 * "sample-conv" functions. It expects a converter name used
6841 * in the haproxy configuration file, and an LUA function.
6842 */
6843__LJMP static int hlua_register_service(lua_State *L)
6844{
6845 struct action_kw_list *akl;
6846 const char *name;
6847 const char *env;
6848 int ref;
6849 int len;
6850 struct hlua_function *fcn;
6851
6852 MAY_LJMP(check_args(L, 3, "register_service"));
6853
6854 /* First argument : converter name. */
6855 name = MAY_LJMP(luaL_checkstring(L, 1));
6856
6857 /* Second argument : environment. */
6858 env = MAY_LJMP(luaL_checkstring(L, 2));
6859
6860 /* Third argument : lua function. */
6861 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6862
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006863 /* Allocate and fill the sample fetch keyword struct. */
6864 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6865 if (!akl)
6866 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6867 fcn = calloc(1, sizeof(*fcn));
6868 if (!fcn)
6869 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6870
6871 /* Fill fcn. */
6872 len = strlen("<lua.>") + strlen(name) + 1;
6873 fcn->name = calloc(1, len);
6874 if (!fcn->name)
6875 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6876 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6877 fcn->function_ref = ref;
6878
6879 /* List head */
6880 akl->list.n = akl->list.p = NULL;
6881
6882 /* converter keyword. */
6883 len = strlen("lua.") + strlen(name) + 1;
6884 akl->kw[0].kw = calloc(1, len);
6885 if (!akl->kw[0].kw)
6886 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6887
6888 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6889
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01006890 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006891 if (strcmp(env, "tcp") == 0)
6892 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006893 else if (strcmp(env, "http") == 0)
6894 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006895 else
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006896 WILL_LJMP(luaL_error(L, "lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01006897 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006898
6899 akl->kw[0].match_pfx = 0;
6900 akl->kw[0].private = fcn;
6901
6902 /* End of array. */
6903 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6904
6905 /* Register this new converter */
6906 service_keywords_register(akl);
6907
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006908 return 0;
6909}
6910
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006911/* This function initialises Lua cli handler. It copies the
6912 * arguments in the Lua stack and create channel IO objects.
6913 */
6914static int hlua_cli_parse_fct(char **args, struct appctx *appctx, void *private)
6915{
6916 struct hlua *hlua;
6917 struct hlua_function *fcn;
6918 int i;
6919 const char *error;
6920
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006921 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006922 appctx->ctx.hlua_cli.fcn = private;
6923
Willy Tarreaubafbe012017-11-24 17:34:44 +01006924 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006925 if (!hlua) {
6926 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006927 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006928 }
6929 HLUA_INIT(hlua);
6930 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006931
6932 /* Create task used by signal to wakeup applets.
6933 * We use the same wakeup fonction than the Lua applet_tcp and
6934 * applet_http. It is absolutely compatible.
6935 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006936 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006937 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01006938 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006939 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006940 }
6941 appctx->ctx.hlua_cli.task->nice = 0;
6942 appctx->ctx.hlua_cli.task->context = appctx;
6943 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
6944
6945 /* Initialises the Lua context */
6946 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
6947 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006948 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006949 }
6950
6951 /* The following Lua calls can fail. */
6952 if (!SET_SAFE_LJMP(hlua->T)) {
6953 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6954 error = lua_tostring(hlua->T, -1);
6955 else
6956 error = "critical error";
6957 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
6958 goto error;
6959 }
6960
6961 /* Check stack available size. */
6962 if (!lua_checkstack(hlua->T, 2)) {
6963 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6964 goto error;
6965 }
6966
6967 /* Restore the function in the stack. */
6968 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
6969
6970 /* Once the arguments parsed, the CLI is like an AppletTCP,
6971 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006972 */
6973 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
6974 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6975 goto error;
6976 }
6977 hlua->nargs = 1;
6978
6979 /* push keywords in the stack. */
6980 for (i = 0; *args[i]; i++) {
6981 /* Check stack available size. */
6982 if (!lua_checkstack(hlua->T, 1)) {
6983 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6984 goto error;
6985 }
6986 lua_pushstring(hlua->T, args[i]);
6987 hlua->nargs++;
6988 }
6989
6990 /* We must initialize the execution timeouts. */
6991 hlua->max_time = hlua_timeout_session;
6992
6993 /* At this point the execution is safe. */
6994 RESET_SAFE_LJMP(hlua->T);
6995
6996 /* It's ok */
6997 return 0;
6998
6999 /* It's not ok. */
7000error:
7001 RESET_SAFE_LJMP(hlua->T);
7002 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007003 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007004 return 1;
7005}
7006
7007static int hlua_cli_io_handler_fct(struct appctx *appctx)
7008{
7009 struct hlua *hlua;
7010 struct stream_interface *si;
7011 struct hlua_function *fcn;
7012
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007013 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007014 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01007015 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007016
7017 /* If the stream is disconnect or closed, ldo nothing. */
7018 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7019 return 1;
7020
7021 /* Execute the function. */
7022 switch (hlua_ctx_resume(hlua, 1)) {
7023
7024 /* finished. */
7025 case HLUA_E_OK:
7026 return 1;
7027
7028 /* yield. */
7029 case HLUA_E_AGAIN:
7030 /* We want write. */
7031 if (HLUA_IS_WAKERESWR(hlua))
7032 si_applet_cant_put(si);
7033 /* Set the timeout. */
7034 if (hlua->wake_time != TICK_ETERNITY)
7035 task_schedule(hlua->task, hlua->wake_time);
7036 return 0;
7037
7038 /* finished with error. */
7039 case HLUA_E_ERRMSG:
7040 /* Display log. */
7041 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
7042 fcn->name, lua_tostring(hlua->T, -1));
7043 lua_pop(hlua->T, 1);
7044 return 1;
7045
7046 case HLUA_E_ERR:
7047 /* Display log. */
7048 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
7049 fcn->name);
7050 return 1;
7051
7052 default:
7053 return 1;
7054 }
7055
7056 return 1;
7057}
7058
7059static void hlua_cli_io_release_fct(struct appctx *appctx)
7060{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007061 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007062 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007063}
7064
7065/* This function is an LUA binding used for registering
7066 * new keywords in the cli. It expects a list of keywords
7067 * which are the "path". It is limited to 5 keywords. A
7068 * description of the command, a function to be executed
7069 * for the parsing and a function for io handlers.
7070 */
7071__LJMP static int hlua_register_cli(lua_State *L)
7072{
7073 struct cli_kw_list *cli_kws;
7074 const char *message;
7075 int ref_io;
7076 int len;
7077 struct hlua_function *fcn;
7078 int index;
7079 int i;
7080
7081 MAY_LJMP(check_args(L, 3, "register_cli"));
7082
7083 /* First argument : an array of maximum 5 keywords. */
7084 if (!lua_istable(L, 1))
7085 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
7086
7087 /* Second argument : string with contextual message. */
7088 message = MAY_LJMP(luaL_checkstring(L, 2));
7089
7090 /* Third and fourth argument : lua function. */
7091 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
7092
7093 /* Allocate and fill the sample fetch keyword struct. */
7094 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
7095 if (!cli_kws)
7096 WILL_LJMP(luaL_error(L, "lua out of memory error."));
7097 fcn = calloc(1, sizeof(*fcn));
7098 if (!fcn)
7099 WILL_LJMP(luaL_error(L, "lua out of memory error."));
7100
7101 /* Fill path. */
7102 index = 0;
7103 lua_pushnil(L);
7104 while(lua_next(L, 1) != 0) {
7105 if (index >= 5)
7106 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
7107 if (lua_type(L, -1) != LUA_TSTRING)
7108 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
7109 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
7110 if (!cli_kws->kw[0].str_kw[index])
7111 WILL_LJMP(luaL_error(L, "lua out of memory error."));
7112 index++;
7113 lua_pop(L, 1);
7114 }
7115
7116 /* Copy help message. */
7117 cli_kws->kw[0].usage = strdup(message);
7118 if (!cli_kws->kw[0].usage)
7119 WILL_LJMP(luaL_error(L, "lua out of memory error."));
7120
7121 /* Fill fcn io handler. */
7122 len = strlen("<lua.cli>") + 1;
7123 for (i = 0; i < index; i++)
7124 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
7125 fcn->name = calloc(1, len);
7126 if (!fcn->name)
7127 WILL_LJMP(luaL_error(L, "lua out of memory error."));
7128 strncat((char *)fcn->name, "<lua.cli", len);
7129 for (i = 0; i < index; i++) {
7130 strncat((char *)fcn->name, ".", len);
7131 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
7132 }
7133 strncat((char *)fcn->name, ">", len);
7134 fcn->function_ref = ref_io;
7135
7136 /* Fill last entries. */
7137 cli_kws->kw[0].private = fcn;
7138 cli_kws->kw[0].parse = hlua_cli_parse_fct;
7139 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
7140 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
7141
7142 /* Register this new converter */
7143 cli_register_kw(cli_kws);
7144
7145 return 0;
7146}
7147
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007148static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
7149 struct proxy *defpx, const char *file, int line,
7150 char **err, unsigned int *timeout)
7151{
7152 const char *error;
7153
7154 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
7155 if (error && *error != '\0') {
7156 memprintf(err, "%s: invalid timeout", args[0]);
7157 return -1;
7158 }
7159 return 0;
7160}
7161
7162static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
7163 struct proxy *defpx, const char *file, int line,
7164 char **err)
7165{
7166 return hlua_read_timeout(args, section_type, curpx, defpx,
7167 file, line, err, &hlua_timeout_session);
7168}
7169
7170static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
7171 struct proxy *defpx, const char *file, int line,
7172 char **err)
7173{
7174 return hlua_read_timeout(args, section_type, curpx, defpx,
7175 file, line, err, &hlua_timeout_task);
7176}
7177
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007178static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
7179 struct proxy *defpx, const char *file, int line,
7180 char **err)
7181{
7182 return hlua_read_timeout(args, section_type, curpx, defpx,
7183 file, line, err, &hlua_timeout_applet);
7184}
7185
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007186static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
7187 struct proxy *defpx, const char *file, int line,
7188 char **err)
7189{
7190 char *error;
7191
7192 hlua_nb_instruction = strtoll(args[1], &error, 10);
7193 if (*error != '\0') {
7194 memprintf(err, "%s: invalid number", args[0]);
7195 return -1;
7196 }
7197 return 0;
7198}
7199
Willy Tarreau32f61e22015-03-18 17:54:59 +01007200static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
7201 struct proxy *defpx, const char *file, int line,
7202 char **err)
7203{
7204 char *error;
7205
7206 if (*(args[1]) == 0) {
7207 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
7208 return -1;
7209 }
7210 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
7211 if (*error != '\0') {
7212 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
7213 return -1;
7214 }
7215 return 0;
7216}
7217
7218
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007219/* This function is called by the main configuration key "lua-load". It loads and
7220 * execute an lua file during the parsing of the HAProxy configuration file. It is
7221 * the main lua entry point.
7222 *
7223 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
7224 * occured, otherwise it returns 0.
7225 *
7226 * In some error case, LUA set an error message in top of the stack. This function
7227 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007228 *
7229 * This function can fail with an abort() due to an Lua critical error.
7230 * We are in the configuration parsing process of HAProxy, this abort() is
7231 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007232 */
7233static int hlua_load(char **args, int section_type, struct proxy *curpx,
7234 struct proxy *defpx, const char *file, int line,
7235 char **err)
7236{
7237 int error;
7238
7239 /* Just load and compile the file. */
7240 error = luaL_loadfile(gL.T, args[1]);
7241 if (error) {
7242 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
7243 lua_pop(gL.T, 1);
7244 return -1;
7245 }
7246
7247 /* If no syntax error where detected, execute the code. */
7248 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
7249 switch (error) {
7250 case LUA_OK:
7251 break;
7252 case LUA_ERRRUN:
7253 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
7254 lua_pop(gL.T, 1);
7255 return -1;
7256 case LUA_ERRMEM:
7257 memprintf(err, "lua out of memory error\n");
7258 return -1;
7259 case LUA_ERRERR:
7260 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
7261 lua_pop(gL.T, 1);
7262 return -1;
7263 case LUA_ERRGCMM:
7264 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
7265 lua_pop(gL.T, 1);
7266 return -1;
7267 default:
7268 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
7269 lua_pop(gL.T, 1);
7270 return -1;
7271 }
7272
7273 return 0;
7274}
7275
7276/* configuration keywords declaration */
7277static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007278 { CFG_GLOBAL, "lua-load", hlua_load },
7279 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
7280 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02007281 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007282 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01007283 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007284 { 0, NULL, NULL },
7285}};
7286
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007287/* This function can fail with an abort() due to an Lua critical error.
7288 * We are in the initialisation process of HAProxy, this abort() is
7289 * tolerated.
7290 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007291int hlua_post_init()
7292{
7293 struct hlua_init_function *init;
7294 const char *msg;
7295 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007296 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007297
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007298 /* Call post initialisation function in safe environement. */
7299 if (!SET_SAFE_LJMP(gL.T)) {
7300 if (lua_type(gL.T, -1) == LUA_TSTRING)
7301 error = lua_tostring(gL.T, -1);
7302 else
7303 error = "critical error";
7304 fprintf(stderr, "Lua post-init: %s.\n", error);
7305 exit(1);
7306 }
7307 hlua_fcn_post_init(gL.T);
7308 RESET_SAFE_LJMP(gL.T);
7309
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007310 list_for_each_entry(init, &hlua_init_functions, l) {
7311 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7312 ret = hlua_ctx_resume(&gL, 0);
7313 switch (ret) {
7314 case HLUA_E_OK:
7315 lua_pop(gL.T, -1);
7316 return 1;
7317 case HLUA_E_AGAIN:
Christopher Faulet767a84b2017-11-24 16:50:31 +01007318 ha_alert("lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007319 return 0;
7320 case HLUA_E_ERRMSG:
7321 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01007322 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007323 return 0;
7324 case HLUA_E_ERR:
7325 default:
Christopher Faulet767a84b2017-11-24 16:50:31 +01007326 ha_alert("lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007327 return 0;
7328 }
7329 }
7330 return 1;
7331}
7332
Willy Tarreau32f61e22015-03-18 17:54:59 +01007333/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7334 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7335 * is the previously allocated size or the kind of object in case of a new
7336 * allocation. <nsize> is the requested new size.
7337 */
7338static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7339{
7340 struct hlua_mem_allocator *zone = ud;
7341
7342 if (nsize == 0) {
7343 /* it's a free */
7344 if (ptr)
7345 zone->allocated -= osize;
7346 free(ptr);
7347 return NULL;
7348 }
7349
7350 if (!ptr) {
7351 /* it's a new allocation */
7352 if (zone->limit && zone->allocated + nsize > zone->limit)
7353 return NULL;
7354
7355 ptr = malloc(nsize);
7356 if (ptr)
7357 zone->allocated += nsize;
7358 return ptr;
7359 }
7360
7361 /* it's a realloc */
7362 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7363 return NULL;
7364
7365 ptr = realloc(ptr, nsize);
7366 if (ptr)
7367 zone->allocated += nsize - osize;
7368 return ptr;
7369}
7370
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007371/* Ithis function can fail with an abort() due to an Lua critical error.
7372 * We are in the initialisation process of HAProxy, this abort() is
7373 * tolerated.
7374 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007375void hlua_init(void)
7376{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007377 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007378 int idx;
7379 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007380 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007381 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007382 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007383#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007384 struct srv_kw *kw;
7385 int tmp_error;
7386 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007387 char *args[] = { /* SSL client configuration. */
7388 "ssl",
7389 "verify",
7390 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007391 NULL
7392 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007393#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007394
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007395 HA_SPIN_INIT(&hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02007396
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007397 /* Initialise struct hlua and com signals pool */
Willy Tarreaubafbe012017-11-24 17:34:44 +01007398 pool_head_hlua = create_pool("hlua", sizeof(struct hlua), MEM_F_SHARED);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007399
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007400 /* Register configuration keywords. */
7401 cfg_register_keywords(&cfg_kws);
7402
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007403 /* Init main lua stack. */
7404 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01007405 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007406 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02007407 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007408 hlua_sethlua(&gL);
7409 gL.Tref = LUA_REFNIL;
7410 gL.task = NULL;
7411
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007412 /* From this point, until the end of the initialisation fucntion,
7413 * the Lua function can fail with an abort. We are in the initialisation
7414 * process of HAProxy, this abort() is tolerated.
7415 */
7416
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007417 /* Initialise lua. */
7418 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007419
Thierry Fournier75933d42016-01-21 09:30:18 +01007420 /* Set safe environment for the initialisation. */
7421 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007422 if (lua_type(gL.T, -1) == LUA_TSTRING)
7423 error_msg = lua_tostring(gL.T, -1);
7424 else
7425 error_msg = "critical error";
7426 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01007427 exit(1);
7428 }
7429
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007430 /*
7431 *
7432 * Create "core" object.
7433 *
7434 */
7435
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01007436 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007437 lua_newtable(gL.T);
7438
7439 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007440 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007441 hlua_class_const_int(gL.T, log_levels[i], i);
7442
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007443 /* Register special functions. */
7444 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007445 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007446 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007447 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007448 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007449 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007450 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007451 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01007452 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007453 hlua_class_function(gL.T, "sleep", hlua_sleep);
7454 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01007455 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
7456 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
7457 hlua_class_function(gL.T, "set_map", hlua_set_map);
7458 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007459 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007460 hlua_class_function(gL.T, "log", hlua_log);
7461 hlua_class_function(gL.T, "Debug", hlua_log_debug);
7462 hlua_class_function(gL.T, "Info", hlua_log_info);
7463 hlua_class_function(gL.T, "Warning", hlua_log_warning);
7464 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02007465 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01007466 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007467
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007468 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007469
7470 /*
7471 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007472 * Register class Map
7473 *
7474 */
7475
7476 /* This table entry is the object "Map" base. */
7477 lua_newtable(gL.T);
7478
7479 /* register pattern types. */
7480 for (i=0; i<PAT_MATCH_NUM; i++)
7481 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007482 for (i=0; i<PAT_MATCH_NUM; i++) {
7483 snprintf(trash.str, trash.size, "_%s", pat_match_names[i]);
7484 hlua_class_const_int(gL.T, trash.str, i);
7485 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007486
7487 /* register constructor. */
7488 hlua_class_function(gL.T, "new", hlua_map_new);
7489
7490 /* Create and fill the metatable. */
7491 lua_newtable(gL.T);
7492
7493 /* Create and fille the __index entry. */
7494 lua_pushstring(gL.T, "__index");
7495 lua_newtable(gL.T);
7496
7497 /* Register . */
7498 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
7499 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
7500
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007501 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007502
Thierry Fournier45e78d72016-02-19 18:34:46 +01007503 /* Register previous table in the registry with reference and named entry.
7504 * The function hlua_register_metatable() pops the stack, so we
7505 * previously create a copy of the table.
7506 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007507 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007508 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007509
7510 /* Assign the metatable to the mai Map object. */
7511 lua_setmetatable(gL.T, -2);
7512
7513 /* Set a name to the table. */
7514 lua_setglobal(gL.T, "Map");
7515
7516 /*
7517 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007518 * Register class Channel
7519 *
7520 */
7521
7522 /* Create and fill the metatable. */
7523 lua_newtable(gL.T);
7524
7525 /* Create and fille the __index entry. */
7526 lua_pushstring(gL.T, "__index");
7527 lua_newtable(gL.T);
7528
7529 /* Register . */
7530 hlua_class_function(gL.T, "get", hlua_channel_get);
7531 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7532 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7533 hlua_class_function(gL.T, "set", hlua_channel_set);
7534 hlua_class_function(gL.T, "append", hlua_channel_append);
7535 hlua_class_function(gL.T, "send", hlua_channel_send);
7536 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7537 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7538 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007539 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007540
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007541 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007542
7543 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007544 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007545
7546 /*
7547 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007548 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007549 *
7550 */
7551
7552 /* Create and fill the metatable. */
7553 lua_newtable(gL.T);
7554
7555 /* Create and fille the __index entry. */
7556 lua_pushstring(gL.T, "__index");
7557 lua_newtable(gL.T);
7558
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007559 /* Browse existing fetches and create the associated
7560 * object method.
7561 */
7562 sf = NULL;
7563 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7564
7565 /* Dont register the keywork if the arguments check function are
7566 * not safe during the runtime.
7567 */
7568 if ((sf->val_args != NULL) &&
7569 (sf->val_args != val_payload_lv) &&
7570 (sf->val_args != val_hdr))
7571 continue;
7572
7573 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7574 * by an underscore.
7575 */
7576 strncpy(trash.str, sf->kw, trash.size);
7577 trash.str[trash.size - 1] = '\0';
7578 for (p = trash.str; *p; p++)
7579 if (*p == '.' || *p == '-' || *p == '+')
7580 *p = '_';
7581
7582 /* Register the function. */
7583 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007584 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007585 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007586 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007587 }
7588
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007589 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007590
7591 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007592 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007593
7594 /*
7595 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007596 * Register class Converters
7597 *
7598 */
7599
7600 /* Create and fill the metatable. */
7601 lua_newtable(gL.T);
7602
7603 /* Create and fill the __index entry. */
7604 lua_pushstring(gL.T, "__index");
7605 lua_newtable(gL.T);
7606
7607 /* Browse existing converters and create the associated
7608 * object method.
7609 */
7610 sc = NULL;
7611 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7612 /* Dont register the keywork if the arguments check function are
7613 * not safe during the runtime.
7614 */
7615 if (sc->val_args != NULL)
7616 continue;
7617
7618 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7619 * by an underscore.
7620 */
7621 strncpy(trash.str, sc->kw, trash.size);
7622 trash.str[trash.size - 1] = '\0';
7623 for (p = trash.str; *p; p++)
7624 if (*p == '.' || *p == '-' || *p == '+')
7625 *p = '_';
7626
7627 /* Register the function. */
7628 lua_pushstring(gL.T, trash.str);
7629 lua_pushlightuserdata(gL.T, sc);
7630 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007631 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007632 }
7633
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007634 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007635
7636 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007637 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007638
7639 /*
7640 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007641 * Register class HTTP
7642 *
7643 */
7644
7645 /* Create and fill the metatable. */
7646 lua_newtable(gL.T);
7647
7648 /* Create and fille the __index entry. */
7649 lua_pushstring(gL.T, "__index");
7650 lua_newtable(gL.T);
7651
7652 /* Register Lua functions. */
7653 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7654 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7655 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7656 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7657 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7658 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7659 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7660 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7661 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7662 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7663
7664 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7665 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7666 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7667 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7668 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7669 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007670 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007671
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007672 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007673
7674 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007675 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007676
7677 /*
7678 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007679 * Register class AppletTCP
7680 *
7681 */
7682
7683 /* Create and fill the metatable. */
7684 lua_newtable(gL.T);
7685
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007686 /* Create and fille the __index entry. */
7687 lua_pushstring(gL.T, "__index");
7688 lua_newtable(gL.T);
7689
7690 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01007691 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7692 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7693 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7694 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7695 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007696 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
7697 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
7698 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007699
7700 lua_settable(gL.T, -3);
7701
7702 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007703 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007704
7705 /*
7706 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007707 * Register class AppletHTTP
7708 *
7709 */
7710
7711 /* Create and fill the metatable. */
7712 lua_newtable(gL.T);
7713
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007714 /* Create and fille the __index entry. */
7715 lua_pushstring(gL.T, "__index");
7716 lua_newtable(gL.T);
7717
7718 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007719 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7720 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007721 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
7722 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
7723 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007724 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7725 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7726 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7727 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7728 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7729 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7730
7731 lua_settable(gL.T, -3);
7732
7733 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007734 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007735
7736 /*
7737 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007738 * Register class TXN
7739 *
7740 */
7741
7742 /* Create and fill the metatable. */
7743 lua_newtable(gL.T);
7744
7745 /* Create and fille the __index entry. */
7746 lua_pushstring(gL.T, "__index");
7747 lua_newtable(gL.T);
7748
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007749 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01007750 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7751 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007752 hlua_class_function(gL.T, "set_var", hlua_set_var);
Christopher Faulet85d79c92016-11-09 16:54:56 +01007753 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007754 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007755 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007756 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
7757 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7758 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007759 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7760 hlua_class_function(gL.T, "log", hlua_txn_log);
7761 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7762 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7763 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7764 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007765
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007766 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007767
7768 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007769 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007770
7771 /*
7772 *
7773 * Register class Socket
7774 *
7775 */
7776
7777 /* Create and fill the metatable. */
7778 lua_newtable(gL.T);
7779
7780 /* Create and fille the __index entry. */
7781 lua_pushstring(gL.T, "__index");
7782 lua_newtable(gL.T);
7783
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007784#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007785 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007786#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007787 hlua_class_function(gL.T, "connect", hlua_socket_connect);
7788 hlua_class_function(gL.T, "send", hlua_socket_send);
7789 hlua_class_function(gL.T, "receive", hlua_socket_receive);
7790 hlua_class_function(gL.T, "close", hlua_socket_close);
7791 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
7792 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
7793 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
7794 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
7795
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007796 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007797
7798 /* Register the garbage collector entry. */
7799 lua_pushstring(gL.T, "__gc");
7800 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
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 previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007804 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007805
7806 /* Proxy and server configuration initialisation. */
7807 memset(&socket_proxy, 0, sizeof(socket_proxy));
7808 init_new_proxy(&socket_proxy);
7809 socket_proxy.parent = NULL;
7810 socket_proxy.last_change = now.tv_sec;
7811 socket_proxy.id = "LUA-SOCKET";
7812 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
7813 socket_proxy.maxconn = 0;
7814 socket_proxy.accept = NULL;
7815 socket_proxy.options2 |= PR_O2_INDEPSTR;
7816 socket_proxy.srv = NULL;
7817 socket_proxy.conn_retries = 0;
7818 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
7819
7820 /* Init TCP server: unchanged parameters */
7821 memset(&socket_tcp, 0, sizeof(socket_tcp));
7822 socket_tcp.next = NULL;
7823 socket_tcp.proxy = &socket_proxy;
7824 socket_tcp.obj_type = OBJ_TYPE_SERVER;
7825 LIST_INIT(&socket_tcp.actconns);
7826 LIST_INIT(&socket_tcp.pendconns);
Christopher Faulet40a007c2017-07-03 15:41:01 +02007827 socket_tcp.priv_conns = NULL;
7828 socket_tcp.idle_conns = NULL;
7829 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02007830 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007831 socket_tcp.last_change = 0;
7832 socket_tcp.id = "LUA-TCP-CONN";
7833 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7834 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7835 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
7836
7837 /* XXX: Copy default parameter from default server,
7838 * but the default server is not initialized.
7839 */
7840 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
7841 socket_tcp.minconn = socket_proxy.defsrv.minconn;
7842 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
7843 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
7844 socket_tcp.onerror = socket_proxy.defsrv.onerror;
7845 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7846 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
7847 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7848 socket_tcp.uweight = socket_proxy.defsrv.iweight;
7849 socket_tcp.iweight = socket_proxy.defsrv.iweight;
7850
7851 socket_tcp.check.status = HCHK_STATUS_INI;
7852 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
7853 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
7854 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
7855 socket_tcp.check.server = &socket_tcp;
7856
7857 socket_tcp.agent.status = HCHK_STATUS_INI;
7858 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
7859 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
7860 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
7861 socket_tcp.agent.server = &socket_tcp;
7862
Willy Tarreaua261e9b2016-12-22 20:44:00 +01007863 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007864
7865#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007866 /* Init TCP server: unchanged parameters */
7867 memset(&socket_ssl, 0, sizeof(socket_ssl));
7868 socket_ssl.next = NULL;
7869 socket_ssl.proxy = &socket_proxy;
7870 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7871 LIST_INIT(&socket_ssl.actconns);
7872 LIST_INIT(&socket_ssl.pendconns);
Christopher Faulet40a007c2017-07-03 15:41:01 +02007873 socket_tcp.priv_conns = NULL;
7874 socket_tcp.idle_conns = NULL;
7875 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02007876 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007877 socket_ssl.last_change = 0;
7878 socket_ssl.id = "LUA-SSL-CONN";
7879 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7880 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7881 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7882
7883 /* XXX: Copy default parameter from default server,
7884 * but the default server is not initialized.
7885 */
7886 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7887 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7888 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7889 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7890 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7891 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7892 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7893 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7894 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7895 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7896
7897 socket_ssl.check.status = HCHK_STATUS_INI;
7898 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7899 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7900 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7901 socket_ssl.check.server = &socket_ssl;
7902
7903 socket_ssl.agent.status = HCHK_STATUS_INI;
7904 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7905 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7906 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7907 socket_ssl.agent.server = &socket_ssl;
7908
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007909 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01007910 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007911
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007912 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007913 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7914 /*
7915 *
7916 * If the keyword is not known, we can search in the registered
7917 * server keywords. This is usefull to configure special SSL
7918 * features like client certificates and ssl_verify.
7919 *
7920 */
7921 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7922 if (tmp_error != 0) {
7923 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7924 abort(); /* This must be never arrives because the command line
7925 not editable by the user. */
7926 }
7927 idx += kw->skip;
7928 }
7929 }
7930
7931 /* Initialize SSL server. */
Willy Tarreau17d45382016-12-22 21:16:08 +01007932 if (socket_ssl.xprt->prepare_srv)
7933 socket_ssl.xprt->prepare_srv(&socket_ssl);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007934#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01007935
7936 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007937}
Willy Tarreaubb57d942016-12-21 19:04:56 +01007938
7939__attribute__((constructor))
7940static void __hlua_init(void)
7941{
7942 char *ptr = NULL;
7943 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
7944 hap_register_build_opts(ptr, 1);
7945}