blob: fa629ba943356dc58a3a38056c63466b26537366 [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:
707 case ARGT_MAP:
708 case ARGT_REG:
709 case ARGT_USR:
710 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100711 break;
712 }
713
714 /* Check for type of argument. */
715 if ((mask & ARGT_MASK) != argp[idx].type) {
716 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
717 arg_type_names[(mask & ARGT_MASK)],
718 arg_type_names[argp[idx].type & ARGT_MASK]);
719 WILL_LJMP(luaL_argerror(L, first + idx, msg));
720 }
721
722 /* Next argument. */
723 mask >>= ARGT_BITS;
724 idx++;
725 }
726}
727
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100728/*
729 * The following functions are used to make correspondance between the the
730 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100731 *
732 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100733 * - hlua_sethlua : create the association between hlua context and lua_state.
734 */
735static inline struct hlua *hlua_gethlua(lua_State *L)
736{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100737 struct hlua **hlua = lua_getextraspace(L);
738 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100739}
740static inline void hlua_sethlua(struct hlua *hlua)
741{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100742 struct hlua **hlua_store = lua_getextraspace(hlua->T);
743 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100744}
745
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100746/* This function is used to send logs. It try to send on screen (stderr)
747 * and on the default syslog server.
748 */
749static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
750{
751 struct tm tm;
752 char *p;
753
754 /* Cleanup the log message. */
755 p = trash.str;
756 for (; *msg != '\0'; msg++, p++) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200757 if (p >= trash.str + trash.size - 1) {
758 /* Break the message if exceed the buffer size. */
759 *(p-4) = ' ';
760 *(p-3) = '.';
761 *(p-2) = '.';
762 *(p-1) = '.';
763 break;
764 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100765 if (isprint(*msg))
766 *p = *msg;
767 else
768 *p = '.';
769 }
770 *p = '\0';
771
Thierry FOURNIER5554e292015-09-09 11:21:37 +0200772 send_log(px, level, "%s\n", trash.str);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100773 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200774 get_localtime(date.tv_sec, &tm);
775 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100776 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
777 (int)getpid(), trash.str);
778 fflush(stderr);
779 }
780}
781
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100782/* This function just ensure that the yield will be always
783 * returned with a timeout and permit to set some flags
784 */
785__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100786 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100787{
788 struct hlua *hlua = hlua_gethlua(L);
789
790 /* Set the wake timeout. If timeout is required, we set
791 * the expiration time.
792 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200793 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100794
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100795 hlua->flags |= flags;
796
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100797 /* Process the yield. */
798 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
799}
800
Willy Tarreau87b09662015-04-03 00:22:06 +0200801/* This function initialises the Lua environment stored in the stream.
802 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100803 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200804 *
805 * This function is particular. it initialises a new Lua thread. If the
806 * initialisation fails (example: out of memory error), the lua function
807 * throws an error (longjmp).
808 *
809 * This function manipulates two Lua stack: the main and the thread. Only
810 * the main stack can fail. The thread is not manipulated. This function
811 * MUST NOT manipulate the created thread stack state, because is not
812 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100813 */
814int hlua_ctx_init(struct hlua *lua, struct task *task)
815{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200816 if (!SET_SAFE_LJMP(gL.T)) {
817 lua->Tref = LUA_REFNIL;
818 return 0;
819 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100820 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100821 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100822 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100823 lua->T = lua_newthread(gL.T);
824 if (!lua->T) {
825 lua->Tref = LUA_REFNIL;
Thierry FOURNIER0a976202017-07-12 11:18:00 +0200826 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100827 return 0;
828 }
829 hlua_sethlua(lua);
830 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
831 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200832 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100833 return 1;
834}
835
Willy Tarreau87b09662015-04-03 00:22:06 +0200836/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100837 * is destroyed. The destroy also the memory context. The struct "lua"
838 * is not freed.
839 */
840void hlua_ctx_destroy(struct hlua *lua)
841{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100842 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100843 return;
844
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100845 if (!lua->T)
846 goto end;
847
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100848 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +0200849 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100850
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200851 if (!SET_SAFE_LJMP(lua->T))
852 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100853 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200854 RESET_SAFE_LJMP(lua->T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200855
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200856 if (!SET_SAFE_LJMP(gL.T))
857 return;
858 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
859 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200860 /* Forces a garbage collecting process. If the Lua program is finished
861 * without error, we run the GC on the thread pointer. Its freed all
862 * the unused memory.
863 * If the thread is finnish with an error or is currently yielded,
864 * it seems that the GC applied on the thread doesn't clean anything,
865 * so e run the GC on the main thread.
866 * NOTE: maybe this action locks all the Lua threads untiml the en of
867 * the garbage collection.
868 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200869 if (lua->flags & HLUA_MUST_GC) {
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200870 if (!SET_SAFE_LJMP(gL.T))
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200871 return;
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200872 lua_gc(gL.T, LUA_GCCOLLECT, 0);
873 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200874 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200875
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200876 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100877
878end:
Willy Tarreaubafbe012017-11-24 17:34:44 +0100879 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100880}
881
882/* This function is used to restore the Lua context when a coroutine
883 * fails. This function copy the common memory between old coroutine
884 * and the new coroutine. The old coroutine is destroyed, and its
885 * replaced by the new coroutine.
886 * If the flag "keep_msg" is set, the last entry of the old is assumed
887 * as string error message and it is copied in the new stack.
888 */
889static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
890{
891 lua_State *T;
892 int new_ref;
893
894 /* Renew the main LUA stack doesn't have sense. */
895 if (lua == &gL)
896 return 0;
897
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100898 /* New Lua coroutine. */
899 T = lua_newthread(gL.T);
900 if (!T)
901 return 0;
902
903 /* Copy last error message. */
904 if (keep_msg)
905 lua_xmove(lua->T, T, 1);
906
907 /* Copy data between the coroutines. */
908 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
909 lua_xmove(lua->T, T, 1);
910 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
911
912 /* Destroy old data. */
913 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
914
915 /* The thread is garbage collected by Lua. */
916 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
917
918 /* Fill the struct with the new coroutine values. */
919 lua->Mref = new_ref;
920 lua->T = T;
921 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
922
923 /* Set context. */
924 hlua_sethlua(lua);
925
926 return 1;
927}
928
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100929void hlua_hook(lua_State *L, lua_Debug *ar)
930{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100931 struct hlua *hlua = hlua_gethlua(L);
932
933 /* Lua cannot yield when its returning from a function,
934 * so, we can fix the interrupt hook to 1 instruction,
935 * expecting that the function is finnished.
936 */
937 if (lua_gethookmask(L) & LUA_MASKRET) {
938 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
939 return;
940 }
941
942 /* restore the interrupt condition. */
943 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
944
945 /* If we interrupt the Lua processing in yieldable state, we yield.
946 * If the state is not yieldable, trying yield causes an error.
947 */
948 if (lua_isyieldable(L))
949 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
950
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +0100951 /* If we cannot yield, update the clock and check the timeout. */
952 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200953 hlua->run_time += now_ms - hlua->start_time;
954 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100955 lua_pushfstring(L, "execution timeout");
956 WILL_LJMP(lua_error(L));
957 }
958
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200959 /* Update the start time. */
960 hlua->start_time = now_ms;
961
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100962 /* Try to interrupt the process at the end of the current
963 * unyieldable function.
964 */
965 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100966}
967
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100968/* This function start or resumes the Lua stack execution. If the flag
969 * "yield_allowed" if no set and the LUA stack execution returns a yield
970 * The function return an error.
971 *
972 * The function can returns 4 values:
973 * - HLUA_E_OK : The execution is terminated without any errors.
974 * - HLUA_E_AGAIN : The execution must continue at the next associated
975 * task wakeup.
976 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
977 * the top of the stack.
978 * - HLUA_E_ERR : An error has occured without error message.
979 *
980 * If an error occured, the stack is renewed and it is ready to run new
981 * LUA code.
982 */
983static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
984{
985 int ret;
986 const char *msg;
987
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200988 /* Initialise run time counter. */
989 if (!HLUA_IS_RUNNING(lua))
990 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100991
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200992 /* Lock the whole Lua execution. This lock must be before the
993 * label "resume_execution".
994 */
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100995 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200996
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100997resume_execution:
998
999 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1000 * instructions. it is used for preventing infinite loops.
1001 */
1002 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1003
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001004 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001005 HLUA_SET_RUN(lua);
1006 HLUA_CLR_CTRLYIELD(lua);
1007 HLUA_CLR_WAKERESWR(lua);
1008 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001009
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001010 /* Update the start time. */
1011 lua->start_time = now_ms;
1012
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001013 /* Call the function. */
1014 ret = lua_resume(lua->T, gL.T, lua->nargs);
1015 switch (ret) {
1016
1017 case LUA_OK:
1018 ret = HLUA_E_OK;
1019 break;
1020
1021 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001022 /* Check if the execution timeout is expired. It it is the case, we
1023 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001024 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001025 tv_update_date(0, 1);
1026 lua->run_time += now_ms - lua->start_time;
1027 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001028 lua_settop(lua->T, 0); /* Empty the stack. */
1029 if (!lua_checkstack(lua->T, 1)) {
1030 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001031 break;
1032 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001033 lua_pushfstring(lua->T, "execution timeout");
1034 ret = HLUA_E_ERRMSG;
1035 break;
1036 }
1037 /* Process the forced yield. if the general yield is not allowed or
1038 * if no task were associated this the current Lua execution
1039 * coroutine, we resume the execution. Else we want to return in the
1040 * scheduler and we want to be waked up again, to continue the
1041 * current Lua execution. So we schedule our own task.
1042 */
1043 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001044 if (!yield_allowed || !lua->task)
1045 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001046 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001047 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001048 if (!yield_allowed) {
1049 lua_settop(lua->T, 0); /* Empty the stack. */
1050 if (!lua_checkstack(lua->T, 1)) {
1051 ret = HLUA_E_ERR;
1052 break;
1053 }
1054 lua_pushfstring(lua->T, "yield not allowed");
1055 ret = HLUA_E_ERRMSG;
1056 break;
1057 }
1058 ret = HLUA_E_AGAIN;
1059 break;
1060
1061 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001062
1063 /* Special exit case. The traditionnal exit is returned as an error
1064 * because the errors ares the only one mean to return immediately
1065 * from and lua execution.
1066 */
1067 if (lua->flags & HLUA_EXIT) {
1068 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001069 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001070 break;
1071 }
1072
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001073 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001074 if (!lua_checkstack(lua->T, 1)) {
1075 ret = HLUA_E_ERR;
1076 break;
1077 }
1078 msg = lua_tostring(lua->T, -1);
1079 lua_settop(lua->T, 0); /* Empty the stack. */
1080 lua_pop(lua->T, 1);
1081 if (msg)
1082 lua_pushfstring(lua->T, "runtime error: %s", msg);
1083 else
1084 lua_pushfstring(lua->T, "unknown runtime error");
1085 ret = HLUA_E_ERRMSG;
1086 break;
1087
1088 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001089 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001090 lua_settop(lua->T, 0); /* Empty the stack. */
1091 if (!lua_checkstack(lua->T, 1)) {
1092 ret = HLUA_E_ERR;
1093 break;
1094 }
1095 lua_pushfstring(lua->T, "out of memory error");
1096 ret = HLUA_E_ERRMSG;
1097 break;
1098
1099 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001100 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001101 if (!lua_checkstack(lua->T, 1)) {
1102 ret = HLUA_E_ERR;
1103 break;
1104 }
1105 msg = lua_tostring(lua->T, -1);
1106 lua_settop(lua->T, 0); /* Empty the stack. */
1107 lua_pop(lua->T, 1);
1108 if (msg)
1109 lua_pushfstring(lua->T, "message handler error: %s", msg);
1110 else
1111 lua_pushfstring(lua->T, "message handler error");
1112 ret = HLUA_E_ERRMSG;
1113 break;
1114
1115 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001116 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001117 lua_settop(lua->T, 0); /* Empty the stack. */
1118 if (!lua_checkstack(lua->T, 1)) {
1119 ret = HLUA_E_ERR;
1120 break;
1121 }
1122 lua_pushfstring(lua->T, "unknonwn error");
1123 ret = HLUA_E_ERRMSG;
1124 break;
1125 }
1126
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001127 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001128 if (lua->flags & HLUA_MUST_GC &&
1129 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001130 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1131
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001132 switch (ret) {
1133 case HLUA_E_AGAIN:
1134 break;
1135
1136 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001137 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001138 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001139 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001140 break;
1141
1142 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001143 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001144 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001145 hlua_ctx_renew(lua, 0);
1146 break;
1147
1148 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001149 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001150 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001151 break;
1152 }
1153
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001154 /* This is the main exit point, remove the Lua lock. */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001155 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001156
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001157 return ret;
1158}
1159
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001160/* This function exit the current code. */
1161__LJMP static int hlua_done(lua_State *L)
1162{
1163 struct hlua *hlua = hlua_gethlua(L);
1164
1165 hlua->flags |= HLUA_EXIT;
1166 WILL_LJMP(lua_error(L));
1167
1168 return 0;
1169}
1170
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001171/* This function is an LUA binding. It provides a function
1172 * for deleting ACL from a referenced ACL file.
1173 */
1174__LJMP static int hlua_del_acl(lua_State *L)
1175{
1176 const char *name;
1177 const char *key;
1178 struct pat_ref *ref;
1179
1180 MAY_LJMP(check_args(L, 2, "del_acl"));
1181
1182 name = MAY_LJMP(luaL_checkstring(L, 1));
1183 key = MAY_LJMP(luaL_checkstring(L, 2));
1184
1185 ref = pat_ref_lookup(name);
1186 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001187 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001188
1189 pat_ref_delete(ref, key);
1190 return 0;
1191}
1192
1193/* This function is an LUA binding. It provides a function
1194 * for deleting map entry from a referenced map file.
1195 */
1196static int hlua_del_map(lua_State *L)
1197{
1198 const char *name;
1199 const char *key;
1200 struct pat_ref *ref;
1201
1202 MAY_LJMP(check_args(L, 2, "del_map"));
1203
1204 name = MAY_LJMP(luaL_checkstring(L, 1));
1205 key = MAY_LJMP(luaL_checkstring(L, 2));
1206
1207 ref = pat_ref_lookup(name);
1208 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001209 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001210
1211 pat_ref_delete(ref, key);
1212 return 0;
1213}
1214
1215/* This function is an LUA binding. It provides a function
1216 * for adding ACL pattern from a referenced ACL file.
1217 */
1218static int hlua_add_acl(lua_State *L)
1219{
1220 const char *name;
1221 const char *key;
1222 struct pat_ref *ref;
1223
1224 MAY_LJMP(check_args(L, 2, "add_acl"));
1225
1226 name = MAY_LJMP(luaL_checkstring(L, 1));
1227 key = MAY_LJMP(luaL_checkstring(L, 2));
1228
1229 ref = pat_ref_lookup(name);
1230 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001231 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001232
1233 if (pat_ref_find_elt(ref, key) == NULL)
1234 pat_ref_add(ref, key, NULL, NULL);
1235 return 0;
1236}
1237
1238/* This function is an LUA binding. It provides a function
1239 * for setting map pattern and sample from a referenced map
1240 * file.
1241 */
1242static int hlua_set_map(lua_State *L)
1243{
1244 const char *name;
1245 const char *key;
1246 const char *value;
1247 struct pat_ref *ref;
1248
1249 MAY_LJMP(check_args(L, 3, "set_map"));
1250
1251 name = MAY_LJMP(luaL_checkstring(L, 1));
1252 key = MAY_LJMP(luaL_checkstring(L, 2));
1253 value = MAY_LJMP(luaL_checkstring(L, 3));
1254
1255 ref = pat_ref_lookup(name);
1256 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001257 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001258
1259 if (pat_ref_find_elt(ref, key) != NULL)
1260 pat_ref_set(ref, key, value, NULL);
1261 else
1262 pat_ref_add(ref, key, value, NULL);
1263 return 0;
1264}
1265
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001266/* A class is a lot of memory that contain data. This data can be a table,
1267 * an integer or user data. This data is associated with a metatable. This
1268 * metatable have an original version registred in the global context with
1269 * the name of the object (_G[<name>] = <metable> ).
1270 *
1271 * A metable is a table that modify the standard behavior of a standard
1272 * access to the associated data. The entries of this new metatable are
1273 * defined as is:
1274 *
1275 * http://lua-users.org/wiki/MetatableEvents
1276 *
1277 * __index
1278 *
1279 * we access an absent field in a table, the result is nil. This is
1280 * true, but it is not the whole truth. Actually, such access triggers
1281 * the interpreter to look for an __index metamethod: If there is no
1282 * such method, as usually happens, then the access results in nil;
1283 * otherwise, the metamethod will provide the result.
1284 *
1285 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1286 * the key does not appear in the table, but the metatable has an __index
1287 * property:
1288 *
1289 * - if the value is a function, the function is called, passing in the
1290 * table and the key; the return value of that function is returned as
1291 * the result.
1292 *
1293 * - if the value is another table, the value of the key in that table is
1294 * asked for and returned (and if it doesn't exist in that table, but that
1295 * table's metatable has an __index property, then it continues on up)
1296 *
1297 * - Use "rawget(myTable,key)" to skip this metamethod.
1298 *
1299 * http://www.lua.org/pil/13.4.1.html
1300 *
1301 * __newindex
1302 *
1303 * Like __index, but control property assignment.
1304 *
1305 * __mode - Control weak references. A string value with one or both
1306 * of the characters 'k' and 'v' which specifies that the the
1307 * keys and/or values in the table are weak references.
1308 *
1309 * __call - Treat a table like a function. When a table is followed by
1310 * parenthesis such as "myTable( 'foo' )" and the metatable has
1311 * a __call key pointing to a function, that function is invoked
1312 * (passing any specified arguments) and the return value is
1313 * returned.
1314 *
1315 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1316 * called, if the metatable for myTable has a __metatable
1317 * key, the value of that key is returned instead of the
1318 * actual metatable.
1319 *
1320 * __tostring - Control string representation. When the builtin
1321 * "tostring( myTable )" function is called, if the metatable
1322 * for myTable has a __tostring property set to a function,
1323 * that function is invoked (passing myTable to it) and the
1324 * return value is used as the string representation.
1325 *
1326 * __len - Control table length. When the table length is requested using
1327 * the length operator ( '#' ), if the metatable for myTable has
1328 * a __len key pointing to a function, that function is invoked
1329 * (passing myTable to it) and the return value used as the value
1330 * of "#myTable".
1331 *
1332 * __gc - Userdata finalizer code. When userdata is set to be garbage
1333 * collected, if the metatable has a __gc field pointing to a
1334 * function, that function is first invoked, passing the userdata
1335 * to it. The __gc metamethod is not called for tables.
1336 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1337 *
1338 * Special metamethods for redefining standard operators:
1339 * http://www.lua.org/pil/13.1.html
1340 *
1341 * __add "+"
1342 * __sub "-"
1343 * __mul "*"
1344 * __div "/"
1345 * __unm "!"
1346 * __pow "^"
1347 * __concat ".."
1348 *
1349 * Special methods for redfining standar relations
1350 * http://www.lua.org/pil/13.2.html
1351 *
1352 * __eq "=="
1353 * __lt "<"
1354 * __le "<="
1355 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001356
1357/*
1358 *
1359 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001360 * Class Map
1361 *
1362 *
1363 */
1364
1365/* Returns a struct hlua_map if the stack entry "ud" is
1366 * a class session, otherwise it throws an error.
1367 */
1368__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1369{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001370 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001371}
1372
1373/* This function is the map constructor. It don't need
1374 * the class Map object. It creates and return a new Map
1375 * object. It must be called only during "body" or "init"
1376 * context because it process some filesystem accesses.
1377 */
1378__LJMP static int hlua_map_new(struct lua_State *L)
1379{
1380 const char *fn;
1381 int match = PAT_MATCH_STR;
1382 struct sample_conv conv;
1383 const char *file = "";
1384 int line = 0;
1385 lua_Debug ar;
1386 char *err = NULL;
1387 struct arg args[2];
1388
1389 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1390 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1391
1392 fn = MAY_LJMP(luaL_checkstring(L, 1));
1393
1394 if (lua_gettop(L) >= 2) {
1395 match = MAY_LJMP(luaL_checkinteger(L, 2));
1396 if (match < 0 || match >= PAT_MATCH_NUM)
1397 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1398 }
1399
1400 /* Get Lua filename and line number. */
1401 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1402 lua_getinfo(L, "Sl", &ar); /* get info about it */
1403 if (ar.currentline > 0) { /* is there info? */
1404 file = ar.short_src;
1405 line = ar.currentline;
1406 }
1407 }
1408
1409 /* fill fake sample_conv struct. */
1410 conv.kw = ""; /* unused. */
1411 conv.process = NULL; /* unused. */
1412 conv.arg_mask = 0; /* unused. */
1413 conv.val_args = NULL; /* unused. */
1414 conv.out_type = SMP_T_STR;
1415 conv.private = (void *)(long)match;
1416 switch (match) {
1417 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1418 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1419 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1420 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1421 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1422 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1423 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001424 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001425 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1426 default:
1427 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1428 }
1429
1430 /* fill fake args. */
1431 args[0].type = ARGT_STR;
1432 args[0].data.str.str = (char *)fn;
1433 args[1].type = ARGT_STOP;
1434
1435 /* load the map. */
1436 if (!sample_load_map(args, &conv, file, line, &err)) {
1437 /* error case: we cant use luaL_error because we must
1438 * free the err variable.
1439 */
1440 luaL_where(L, 1);
1441 lua_pushfstring(L, "'new': %s.", err);
1442 lua_concat(L, 2);
1443 free(err);
1444 WILL_LJMP(lua_error(L));
1445 }
1446
1447 /* create the lua object. */
1448 lua_newtable(L);
1449 lua_pushlightuserdata(L, args[0].data.map);
1450 lua_rawseti(L, -2, 0);
1451
1452 /* Pop a class Map metatable and affect it to the userdata. */
1453 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1454 lua_setmetatable(L, -2);
1455
1456
1457 return 1;
1458}
1459
1460__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1461{
1462 struct map_descriptor *desc;
1463 struct pattern *pat;
1464 struct sample smp;
1465
1466 MAY_LJMP(check_args(L, 2, "lookup"));
1467 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001468 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001469 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001470 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001471 }
1472 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001473 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001474 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001475 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 +02001476 }
1477
1478 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001479 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001480 if (str)
1481 lua_pushstring(L, "");
1482 else
1483 lua_pushnil(L);
1484 return 1;
1485 }
1486
1487 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001488 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001489 return 1;
1490}
1491
1492__LJMP static int hlua_map_lookup(struct lua_State *L)
1493{
1494 return _hlua_map_lookup(L, 0);
1495}
1496
1497__LJMP static int hlua_map_slookup(struct lua_State *L)
1498{
1499 return _hlua_map_lookup(L, 1);
1500}
1501
1502/*
1503 *
1504 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001505 * Class Socket
1506 *
1507 *
1508 */
1509
1510__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1511{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001512 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001513}
1514
1515/* This function is the handler called for each I/O on the established
1516 * connection. It is used for notify space avalaible to send or data
1517 * received.
1518 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001519static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001520{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001521 struct stream_interface *si = appctx->owner;
Olivier Houchard9aaf7782017-09-13 18:30:23 +02001522 struct connection *c = cs_conn(objt_cs(si_opposite(si)->end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001523
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001524 if (appctx->ctx.hlua_cosocket.die) {
1525 si_shutw(si);
1526 si_shutr(si);
1527 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001528 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1529 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001530 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1531 }
1532
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001533 /* If the connection object is not avalaible, close all the
1534 * streams and wakeup everithing waiting for.
1535 */
1536 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001537 si_shutw(si);
1538 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001539 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001540 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1541 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001542 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001543 }
1544
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001545 /* If we cant write, wakeup the pending write signals. */
1546 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001547 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001548
1549 /* If we cant read, wakeup the pending read signals. */
1550 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001551 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001552
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001553 /* if the connection is not estabkished, inform the stream that we want
1554 * to be notified whenever the connection completes.
1555 */
1556 if (!(c->flags & CO_FL_CONNECTED)) {
1557 si_applet_cant_get(si);
1558 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001559 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001560 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001561
1562 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001563 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001564
1565 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001566 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001567 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001568
1569 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001570 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001571 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001572}
1573
Willy Tarreau87b09662015-04-03 00:22:06 +02001574/* This function is called when the "struct stream" is destroyed.
1575 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001576 * Wake all the pending signals.
1577 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001578static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001579{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001580 struct xref *peer;
1581
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001582 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001583 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1584 if (peer)
1585 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001586
1587 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001588 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1589 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001590}
1591
1592/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001593 * uses this object. If the stream does not exists, just quit.
1594 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001595 * pending signal can rest in the read and write lists. destroy
1596 * it.
1597 */
1598__LJMP static int hlua_socket_gc(lua_State *L)
1599{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001600 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001601 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001602 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001603
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001604 MAY_LJMP(check_args(L, 1, "__gc"));
1605
1606 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001607 peer = xref_get_peer_and_lock(&socket->xref);
1608 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001609 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001610 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001611
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001612 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001613 appctx->ctx.hlua_cosocket.die = 1;
1614 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001615
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001616 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001617 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001618 return 0;
1619}
1620
1621/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001622 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001623 */
1624__LJMP static int hlua_socket_close(lua_State *L)
1625{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001626 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001627 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001628 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001629
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001630 MAY_LJMP(check_args(L, 1, "close"));
1631
1632 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001633
1634 /* Check if we run on the same thread than the xreator thread.
1635 * We cannot access to the socket if the thread is different.
1636 */
1637 if (socket->tid != tid)
1638 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1639
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001640 peer = xref_get_peer_and_lock(&socket->xref);
1641 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001642 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001643 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001644
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001645 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001646 appctx->ctx.hlua_cosocket.die = 1;
1647 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001648
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001649 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001650 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001651 return 0;
1652}
1653
1654/* This Lua function assumes that the stack contain three parameters.
1655 * 1 - USERDATA containing a struct socket
1656 * 2 - INTEGER with values of the macro defined below
1657 * If the integer is -1, we must read at most one line.
1658 * If the integer is -2, we ust read all the data until the
1659 * end of the stream.
1660 * If the integer is positive value, we must read a number of
1661 * bytes corresponding to this value.
1662 */
1663#define HLSR_READ_LINE (-1)
1664#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001665__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001666{
1667 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1668 int wanted = lua_tointeger(L, 2);
1669 struct hlua *hlua = hlua_gethlua(L);
1670 struct appctx *appctx;
1671 int len;
1672 int nblk;
1673 char *blk1;
1674 int len1;
1675 char *blk2;
1676 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001677 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001678 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001679 struct stream_interface *si;
1680 struct stream *s;
1681 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001682
1683 /* Check if this lua stack is schedulable. */
1684 if (!hlua || !hlua->task)
1685 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1686 "'frontend', 'backend' or 'task'"));
1687
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001688 /* Check if we run on the same thread than the xreator thread.
1689 * We cannot access to the socket if the thread is different.
1690 */
1691 if (socket->tid != tid)
1692 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1693
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001694 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001695 peer = xref_get_peer_and_lock(&socket->xref);
1696 if (!peer)
1697 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001698 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1699 si = appctx->owner;
1700 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001701
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001702 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001703 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001704 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001705 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001706 if (nblk < 0) /* Connection close. */
1707 goto connection_closed;
1708 if (nblk == 0) /* No data avalaible. */
1709 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001710
1711 /* remove final \r\n. */
1712 if (nblk == 1) {
1713 if (blk1[len1-1] == '\n') {
1714 len1--;
1715 skip_at_end++;
1716 if (blk1[len1-1] == '\r') {
1717 len1--;
1718 skip_at_end++;
1719 }
1720 }
1721 }
1722 else {
1723 if (blk2[len2-1] == '\n') {
1724 len2--;
1725 skip_at_end++;
1726 if (blk2[len2-1] == '\r') {
1727 len2--;
1728 skip_at_end++;
1729 }
1730 }
1731 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001732 }
1733
1734 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001735 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001736 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001737 if (nblk < 0) /* Connection close. */
1738 goto connection_closed;
1739 if (nblk == 0) /* No data avalaible. */
1740 goto connection_empty;
1741 }
1742
1743 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001744 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001745 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001746 if (nblk < 0) /* Connection close. */
1747 goto connection_closed;
1748 if (nblk == 0) /* No data avalaible. */
1749 goto connection_empty;
1750
1751 if (len1 > wanted) {
1752 nblk = 1;
1753 len1 = wanted;
1754 } if (nblk == 2 && len1 + len2 > wanted)
1755 len2 = wanted - len1;
1756 }
1757
1758 len = len1;
1759
1760 luaL_addlstring(&socket->b, blk1, len1);
1761 if (nblk == 2) {
1762 len += len2;
1763 luaL_addlstring(&socket->b, blk2, len2);
1764 }
1765
1766 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001767 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001768
1769 /* Don't wait anything. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001770 stream_int_notify(&s->si[0]);
1771 stream_int_update_applet(&s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001772
1773 /* If the pattern reclaim to read all the data
1774 * in the connection, got out.
1775 */
1776 if (wanted == HLSR_READ_ALL)
1777 goto connection_empty;
1778 else if (wanted >= 0 && len < wanted)
1779 goto connection_empty;
1780
1781 /* Return result. */
1782 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001783 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001784 return 1;
1785
1786connection_closed:
1787
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001788 xref_unlock(&socket->xref, peer);
1789
1790no_peer:
1791
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001792 /* If the buffer containds data. */
1793 if (socket->b.n > 0) {
1794 luaL_pushresult(&socket->b);
1795 return 1;
1796 }
1797 lua_pushnil(L);
1798 lua_pushstring(L, "connection closed.");
1799 return 2;
1800
1801connection_empty:
1802
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001803 appctx = objt_appctx(s->si[0].end);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001804 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
1805 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001806 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001807 }
1808 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001809 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001810 return 0;
1811}
1812
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001813/* This Lua function gets two parameters. The first one can be string
1814 * or a number. If the string is "*l", the user requires one line. If
1815 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001816 * If the value is a number, the user require a number of bytes equal
1817 * to the value. The default value is "*l" (a line).
1818 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001819 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001820 * integer takes this values:
1821 * -1 : read a line
1822 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001823 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001824 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001825 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001826 * concatenated with the read data.
1827 */
1828__LJMP static int hlua_socket_receive(struct lua_State *L)
1829{
1830 int wanted = HLSR_READ_LINE;
1831 const char *pattern;
1832 int type;
1833 char *error;
1834 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001835 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001836
1837 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1838 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1839
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001840 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001841
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001842 /* Check if we run on the same thread than the xreator thread.
1843 * We cannot access to the socket if the thread is different.
1844 */
1845 if (socket->tid != tid)
1846 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1847
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001848 /* check for pattern. */
1849 if (lua_gettop(L) >= 2) {
1850 type = lua_type(L, 2);
1851 if (type == LUA_TSTRING) {
1852 pattern = lua_tostring(L, 2);
1853 if (strcmp(pattern, "*a") == 0)
1854 wanted = HLSR_READ_ALL;
1855 else if (strcmp(pattern, "*l") == 0)
1856 wanted = HLSR_READ_LINE;
1857 else {
1858 wanted = strtoll(pattern, &error, 10);
1859 if (*error != '\0')
1860 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1861 }
1862 }
1863 else if (type == LUA_TNUMBER) {
1864 wanted = lua_tointeger(L, 2);
1865 if (wanted < 0)
1866 WILL_LJMP(luaL_error(L, "Unsupported size."));
1867 }
1868 }
1869
1870 /* Set pattern. */
1871 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01001872
1873 /* Check if we would replace the top by itself. */
1874 if (lua_gettop(L) != 2)
1875 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001876
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001877 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001878 luaL_buffinit(L, &socket->b);
1879
1880 /* Check prefix. */
1881 if (lua_gettop(L) >= 3) {
1882 if (lua_type(L, 3) != LUA_TSTRING)
1883 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1884 pattern = lua_tolstring(L, 3, &len);
1885 luaL_addlstring(&socket->b, pattern, len);
1886 }
1887
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001888 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001889}
1890
1891/* Write the Lua input string in the output buffer.
1892 * This fucntion returns a yield if no space are available.
1893 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001894static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001895{
1896 struct hlua_socket *socket;
1897 struct hlua *hlua = hlua_gethlua(L);
1898 struct appctx *appctx;
1899 size_t buf_len;
1900 const char *buf;
1901 int len;
1902 int send_len;
1903 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001904 struct xref *peer;
1905 struct stream_interface *si;
1906 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001907
1908 /* Check if this lua stack is schedulable. */
1909 if (!hlua || !hlua->task)
1910 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1911 "'frontend', 'backend' or 'task'"));
1912
1913 /* Get object */
1914 socket = MAY_LJMP(hlua_checksocket(L, 1));
1915 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001916 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001917
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001918 /* Check if we run on the same thread than the xreator thread.
1919 * We cannot access to the socket if the thread is different.
1920 */
1921 if (socket->tid != tid)
1922 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1923
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001924 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001925 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001926 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001927 lua_pushinteger(L, -1);
1928 return 1;
1929 }
1930 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1931 si = appctx->owner;
1932 s = si_strm(si);
1933
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001934 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001935 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001936 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001937 lua_pushinteger(L, -1);
1938 return 1;
1939 }
1940
1941 /* Update the input buffer data. */
1942 buf += sent;
1943 send_len = buf_len - sent;
1944
1945 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001946 if (sent >= buf_len) {
1947 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001948 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001949 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001950
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001951 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1952 * the request buffer if its not required.
1953 */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001954 if (s->req.buf->size == 0) {
Christopher Faulet33834b12016-12-19 09:29:06 +01001955 appctx = hlua->task->context;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001956 if (!channel_alloc_buffer(&s->req, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01001957 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001958 }
1959
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001960 /* Check for avalaible space. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001961 len = buffer_total_space(s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01001962 if (len <= 0) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001963 appctx = objt_appctx(s->si[0].end);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001964 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
1965 xref_unlock(&socket->xref, peer);
Christopher Faulet33834b12016-12-19 09:29:06 +01001966 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001967 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001968 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01001969 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001970
1971 /* send data */
1972 if (len < send_len)
1973 send_len = len;
Willy Tarreau06d80a92017-10-19 14:32:15 +02001974 len = ci_putblk(&s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001975
1976 /* "Not enough space" (-1), "Buffer too little to contain
1977 * the data" (-2) are not expected because the available length
1978 * is tested.
1979 * Other unknown error are also not expected.
1980 */
1981 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001982 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001983 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001984
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001985 MAY_LJMP(hlua_socket_close(L));
1986 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001987 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001988 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001989 return 1;
1990 }
1991
1992 /* update buffers. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001993 stream_int_notify(&s->si[0]);
1994 stream_int_update_applet(&s->si[0]);
Willy Tarreaude70fa12015-09-26 11:25:05 +02001995
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001996 s->req.rex = TICK_ETERNITY;
1997 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001998
1999 /* Update length sent. */
2000 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002001 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002002
2003 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002004 if (sent + len >= buf_len) {
2005 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002006 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002007 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002008
2009hlua_socket_write_yield_return:
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002010 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002011 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002012 return 0;
2013}
2014
2015/* This function initiate the send of data. It just check the input
2016 * parameters and push an integer in the Lua stack that contain the
2017 * amount of data writed in the buffer. This is used by the function
2018 * "hlua_socket_write_yield" that can yield.
2019 *
2020 * The Lua function gets between 3 and 4 parameters. The first one is
2021 * the associated object. The second is a string buffer. The third is
2022 * a facultative integer that represents where is the buffer position
2023 * of the start of the data that can send. The first byte is the
2024 * position "1". The default value is "1". The fourth argument is a
2025 * facultative integer that represents where is the buffer position
2026 * of the end of the data that can send. The default is the last byte.
2027 */
2028static int hlua_socket_send(struct lua_State *L)
2029{
2030 int i;
2031 int j;
2032 const char *buf;
2033 size_t buf_len;
2034
2035 /* Check number of arguments. */
2036 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2037 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2038
2039 /* Get the string. */
2040 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2041
2042 /* Get and check j. */
2043 if (lua_gettop(L) == 4) {
2044 j = MAY_LJMP(luaL_checkinteger(L, 4));
2045 if (j < 0)
2046 j = buf_len + j + 1;
2047 if (j > buf_len)
2048 j = buf_len + 1;
2049 lua_pop(L, 1);
2050 }
2051 else
2052 j = buf_len;
2053
2054 /* Get and check i. */
2055 if (lua_gettop(L) == 3) {
2056 i = MAY_LJMP(luaL_checkinteger(L, 3));
2057 if (i < 0)
2058 i = buf_len + i + 1;
2059 if (i > buf_len)
2060 i = buf_len + 1;
2061 lua_pop(L, 1);
2062 } else
2063 i = 1;
2064
2065 /* Check bth i and j. */
2066 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002067 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002068 return 1;
2069 }
2070 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002071 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002072 return 1;
2073 }
2074 if (i == 0)
2075 i = 1;
2076 if (j == 0)
2077 j = 1;
2078
2079 /* Pop the string. */
2080 lua_pop(L, 1);
2081
2082 /* Update the buffer length. */
2083 buf += i - 1;
2084 buf_len = j - i + 1;
2085 lua_pushlstring(L, buf, buf_len);
2086
2087 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002088 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002089
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002090 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002091}
2092
Willy Tarreau22b0a682015-06-17 19:43:49 +02002093#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002094__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2095{
2096 static char buffer[SOCKET_INFO_MAX_LEN];
2097 int ret;
2098 int len;
2099 char *p;
2100
2101 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2102 if (ret <= 0) {
2103 lua_pushnil(L);
2104 return 1;
2105 }
2106
2107 if (ret == AF_UNIX) {
2108 lua_pushstring(L, buffer+1);
2109 return 1;
2110 }
2111 else if (ret == AF_INET6) {
2112 buffer[0] = '[';
2113 len = strlen(buffer);
2114 buffer[len] = ']';
2115 len++;
2116 buffer[len] = ':';
2117 len++;
2118 p = buffer;
2119 }
2120 else if (ret == AF_INET) {
2121 p = buffer + 1;
2122 len = strlen(p);
2123 p[len] = ':';
2124 len++;
2125 }
2126 else {
2127 lua_pushnil(L);
2128 return 1;
2129 }
2130
2131 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2132 lua_pushnil(L);
2133 return 1;
2134 }
2135
2136 lua_pushstring(L, p);
2137 return 1;
2138}
2139
2140/* Returns information about the peer of the connection. */
2141__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2142{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002143 struct hlua_socket *socket;
2144 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002145 struct xref *peer;
2146 struct appctx *appctx;
2147 struct stream_interface *si;
2148 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002149 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002150
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002151 MAY_LJMP(check_args(L, 1, "getpeername"));
2152
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002153 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002154
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002155 /* Check if we run on the same thread than the xreator thread.
2156 * We cannot access to the socket if the thread is different.
2157 */
2158 if (socket->tid != tid)
2159 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2160
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002161 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002162 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002163 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002164 lua_pushnil(L);
2165 return 1;
2166 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002167 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2168 si = appctx->owner;
2169 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002170
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002171 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002172 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002173 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002174 lua_pushnil(L);
2175 return 1;
2176 }
2177
Willy Tarreaua71f6422016-11-16 17:00:14 +01002178 conn_get_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002179 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002180 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002181 lua_pushnil(L);
2182 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002183 }
2184
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002185 ret = MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2186 xref_unlock(&socket->xref, peer);
2187 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002188}
2189
2190/* Returns information about my connection side. */
2191static int hlua_socket_getsockname(struct lua_State *L)
2192{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002193 struct hlua_socket *socket;
2194 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002195 struct appctx *appctx;
2196 struct xref *peer;
2197 struct stream_interface *si;
2198 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002199 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002200
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002201 MAY_LJMP(check_args(L, 1, "getsockname"));
2202
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002203 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002204
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002205 /* Check if we run on the same thread than the xreator thread.
2206 * We cannot access to the socket if the thread is different.
2207 */
2208 if (socket->tid != tid)
2209 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2210
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002211 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002212 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002213 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002214 lua_pushnil(L);
2215 return 1;
2216 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002217 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2218 si = appctx->owner;
2219 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002220
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002221 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002222 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002223 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002224 lua_pushnil(L);
2225 return 1;
2226 }
2227
Willy Tarreaua71f6422016-11-16 17:00:14 +01002228 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002229 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002230 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002231 lua_pushnil(L);
2232 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002233 }
2234
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002235 ret = hlua_socket_info(L, &conn->addr.from);
2236 xref_unlock(&socket->xref, peer);
2237 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002238}
2239
2240/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002241static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002242 .obj_type = OBJ_TYPE_APPLET,
2243 .name = "<LUA_TCP>",
2244 .fct = hlua_socket_handler,
2245 .release = hlua_socket_release,
2246};
2247
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002248__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002249{
2250 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2251 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002252 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002253 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002254 struct stream_interface *si;
2255 struct stream *s;
2256
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002257 /* Check if we run on the same thread than the xreator thread.
2258 * We cannot access to the socket if the thread is different.
2259 */
2260 if (socket->tid != tid)
2261 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2262
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002263 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002264 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002265 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002266 lua_pushnil(L);
2267 lua_pushstring(L, "Can't connect");
2268 return 2;
2269 }
2270 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2271 si = appctx->owner;
2272 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002273
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002274 /* Check if we run on the same thread than the xreator thread.
2275 * We cannot access to the socket if the thread is different.
2276 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002277 if (socket->tid != tid) {
2278 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002279 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002280 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002281
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002282 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002283 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002284 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002285 lua_pushnil(L);
2286 lua_pushstring(L, "Can't connect");
2287 return 2;
2288 }
2289
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002290 appctx = objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002291
2292 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002293 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002294 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002295 lua_pushinteger(L, 1);
2296 return 1;
2297 }
2298
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002299 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2300 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002301 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002302 }
2303 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002304 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002305 return 0;
2306}
2307
2308/* This function fail or initite the connection. */
2309__LJMP static int hlua_socket_connect(struct lua_State *L)
2310{
2311 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002312 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002313 const char *ip;
2314 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002315 struct hlua *hlua;
2316 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002317 int low, high;
2318 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002319 struct xref *peer;
2320 struct stream_interface *si;
2321 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002322
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002323 if (lua_gettop(L) < 2)
2324 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002325
2326 /* Get args. */
2327 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002328
2329 /* Check if we run on the same thread than the xreator thread.
2330 * We cannot access to the socket if the thread is different.
2331 */
2332 if (socket->tid != tid)
2333 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2334
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002335 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002336 if (lua_gettop(L) >= 3) {
2337 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002338 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002339
Tim Duesterhus6edab862018-01-06 19:04:45 +01002340 /* Force the ip to end with a colon, to support IPv6 addresses
2341 * that are not enclosed within square brackets.
2342 */
2343 if (port > 0) {
2344 luaL_buffinit(L, &b);
2345 luaL_addstring(&b, ip);
2346 luaL_addchar(&b, ':');
2347 luaL_pushresult(&b);
2348 ip = lua_tolstring(L, lua_gettop(L), NULL);
2349 }
2350 }
2351
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002352 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002353 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002354 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002355 lua_pushnil(L);
2356 return 1;
2357 }
2358 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2359 si = appctx->owner;
2360 s = si_strm(si);
2361
2362 /* Initialise connection. */
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002363 conn = cs_conn(si_alloc_cs(&s->si[1], NULL));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002364 if (!conn) {
2365 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002366 WILL_LJMP(luaL_error(L, "connect: internal error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002367 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002368
Willy Tarreau3adac082015-09-26 17:51:09 +02002369 /* needed for the connection not to be closed */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002370 conn->target = s->target;
Willy Tarreau3adac082015-09-26 17:51:09 +02002371
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002372 /* Parse ip address. */
Willy Tarreau48ef4c92017-01-06 18:32:38 +01002373 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, 0);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002374 if (!addr) {
2375 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002376 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002377 }
2378 if (low != high) {
2379 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002380 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002381 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002382 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002383
2384 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002385 if (low == 0) {
2386 if (conn->addr.to.ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002387 if (port == -1) {
2388 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002389 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002390 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002391 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2392 } else if (conn->addr.to.ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002393 if (port == -1) {
2394 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002395 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002396 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002397 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2398 }
2399 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002400
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002401 hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002402 appctx = objt_appctx(s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002403
2404 /* inform the stream that we want to be notified whenever the
2405 * connection completes.
2406 */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002407 si_applet_cant_get(&s->si[0]);
2408 si_applet_cant_put(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002409 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002410
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002411 hlua->flags |= HLUA_MUST_GC;
2412
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002413 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2414 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002415 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002416 }
2417 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002418 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002419
2420 return 0;
2421}
2422
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002423#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002424__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2425{
2426 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002427 struct xref *peer;
2428 struct appctx *appctx;
2429 struct stream_interface *si;
2430 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002431
2432 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2433 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002434
2435 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002436 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002437 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002438 lua_pushnil(L);
2439 return 1;
2440 }
2441 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2442 si = appctx->owner;
2443 s = si_strm(si);
2444
2445 s->target = &socket_ssl.obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002446 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002447 return MAY_LJMP(hlua_socket_connect(L));
2448}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002449#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002450
2451__LJMP static int hlua_socket_setoption(struct lua_State *L)
2452{
2453 return 0;
2454}
2455
2456__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2457{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002458 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002459 int tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002460 struct xref *peer;
2461 struct appctx *appctx;
2462 struct stream_interface *si;
2463 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002464
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002465 MAY_LJMP(check_args(L, 2, "settimeout"));
2466
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002467 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002468 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002469
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002470 /* Check if we run on the same thread than the xreator thread.
2471 * We cannot access to the socket if the thread is different.
2472 */
2473 if (socket->tid != tid)
2474 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2475
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002476 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002477 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002478 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002479 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2480 WILL_LJMP(lua_error(L));
2481 return 0;
2482 }
2483 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2484 si = appctx->owner;
2485 s = si_strm(si);
2486
2487 s->req.rto = tmout;
2488 s->req.wto = tmout;
2489 s->res.rto = tmout;
2490 s->res.wto = tmout;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002491 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002492
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002493 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002494}
2495
2496__LJMP static int hlua_socket_new(lua_State *L)
2497{
2498 struct hlua_socket *socket;
2499 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002500 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002501 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002502
2503 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002504 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002505 hlua_pusherror(L, "socket: full stack");
2506 goto out_fail_conf;
2507 }
2508
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002509 /* Create the object: obj[0] = userdata. */
2510 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002511 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002512 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002513 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002514 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002515
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002516 /* Check if the various memory pools are intialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002517 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002518 hlua_pusherror(L, "socket: uninitialized pools.");
2519 goto out_fail_conf;
2520 }
2521
Willy Tarreau87b09662015-04-03 00:22:06 +02002522 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002523 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2524 lua_setmetatable(L, -2);
2525
Willy Tarreaud420a972015-04-06 00:39:18 +02002526 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002527 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002528 if (!appctx) {
2529 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002530 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002531 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002532
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002533 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002534 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002535 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2536 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002537
Willy Tarreaud420a972015-04-06 00:39:18 +02002538 /* Now create a session, task and stream for this applet */
2539 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2540 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002541 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002542 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002543 }
2544
Willy Tarreau87787ac2017-08-28 16:22:54 +02002545 strm = stream_new(sess, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002546 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002547 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002548 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002549 }
2550
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002551 /* Initialise cross reference between stream and Lua socket object. */
2552 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002553
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002554 /* Configure "right" stream interface. this "si" is used to connect
2555 * and retrieve data from the server. The connection is initialized
2556 * with the "struct server".
2557 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002558 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002559
2560 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002561 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2562 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002563
Willy Tarreau87787ac2017-08-28 16:22:54 +02002564 task_wakeup(strm->task, TASK_WOKEN_INIT);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002565 /* Return yield waiting for connection. */
2566 return 1;
2567
Willy Tarreaud420a972015-04-06 00:39:18 +02002568 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002569 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002570 out_fail_sess:
2571 appctx_free(appctx);
2572 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002573 WILL_LJMP(lua_error(L));
2574 return 0;
2575}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002576
2577/*
2578 *
2579 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002580 * Class Channel
2581 *
2582 *
2583 */
2584
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002585/* The state between the channel data and the HTTP parser state can be
2586 * unconsistent, so reset the parser and call it again. Warning, this
2587 * action not revalidate the request and not send a 400 if the modified
2588 * resuest is not valid.
2589 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002590 * This function never fails. The direction is set using dir, which equals
2591 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002592 */
2593static void hlua_resynchonize_proto(struct stream *stream, int dir)
2594{
2595 /* Protocol HTTP. */
2596 if (stream->be->mode == PR_MODE_HTTP) {
2597
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002598 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002599 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002600 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002601 http_txn_reset_res(stream->txn);
2602
2603 if (stream->txn->hdr_idx.v)
2604 hdr_idx_init(&stream->txn->hdr_idx);
2605
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002606 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002607 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002608 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002609 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2610 }
2611}
2612
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002613/* This function is called before the Lua execution. It stores
2614 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002615 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002616static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002617{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002618 c->mode = stream->be->mode;
2619 switch (c->mode) {
2620 case PR_MODE_HTTP:
2621 c->data.http.dir = opt & SMP_OPT_DIR;
2622 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2623 c->data.http.state = stream->txn->req.msg_state;
2624 else
2625 c->data.http.state = stream->txn->rsp.msg_state;
2626 break;
2627 default:
2628 break;
2629 }
2630}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002631
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002632/* This function is called after the Lua execution. it
2633 * returns true if the parser state is consistent, otherwise,
2634 * it return false.
2635 *
2636 * In HTTP mode, the parser state must be in the same state
2637 * or greater when we exit the function. Even if we do a
2638 * control yield. This prevent to break the HTTP message
2639 * from the Lua code.
2640 */
2641static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2642{
2643 if (c->mode != stream->be->mode)
2644 return 0;
2645
2646 switch (c->mode) {
2647 case PR_MODE_HTTP:
2648 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002649 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002650 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2651 return stream->txn->req.msg_state >= c->data.http.state;
2652 else
2653 return stream->txn->rsp.msg_state >= c->data.http.state;
2654 default:
2655 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002656 }
2657 return 1;
2658}
2659
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002660/* Returns the struct hlua_channel join to the class channel in the
2661 * stack entry "ud" or throws an argument error.
2662 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002663__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002664{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002665 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002666}
2667
Willy Tarreau47860ed2015-03-10 14:07:50 +01002668/* Pushes the channel onto the top of the stack. If the stask does not have a
2669 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002670 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002671static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002672{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002673 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002674 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002675 return 0;
2676
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002677 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002678 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002679 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002680
2681 /* Pop a class sesison metatable and affect it to the userdata. */
2682 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2683 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002684 return 1;
2685}
2686
2687/* Duplicate all the data present in the input channel and put it
2688 * in a string LUA variables. Returns -1 and push a nil value in
2689 * the stack if the channel is closed and all the data are consumed,
2690 * returns 0 if no data are available, otherwise it returns the length
2691 * of the builded string.
2692 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002693static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002694{
2695 char *blk1;
2696 char *blk2;
2697 int len1;
2698 int len2;
2699 int ret;
2700 luaL_Buffer b;
2701
Willy Tarreau06d80a92017-10-19 14:32:15 +02002702 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002703 if (unlikely(ret == 0))
2704 return 0;
2705
2706 if (unlikely(ret < 0)) {
2707 lua_pushnil(L);
2708 return -1;
2709 }
2710
2711 luaL_buffinit(L, &b);
2712 luaL_addlstring(&b, blk1, len1);
2713 if (unlikely(ret == 2))
2714 luaL_addlstring(&b, blk2, len2);
2715 luaL_pushresult(&b);
2716
2717 if (unlikely(ret == 2))
2718 return len1 + len2;
2719 return len1;
2720}
2721
2722/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2723 * a yield. This function keep the data in the buffer.
2724 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002725__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002726{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002727 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002728
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002729 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2730
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002731 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002732 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002733 return 1;
2734}
2735
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002736/* Check arguments for the function "hlua_channel_dup_yield". */
2737__LJMP static int hlua_channel_dup(lua_State *L)
2738{
2739 MAY_LJMP(check_args(L, 1, "dup"));
2740 MAY_LJMP(hlua_checkchannel(L, 1));
2741 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2742}
2743
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002744/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2745 * a yield. This function consumes the data in the buffer. It returns
2746 * a string containing the data or a nil pointer if no data are available
2747 * and the channel is closed.
2748 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002749__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002750{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002751 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002752 int ret;
2753
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002754 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002755
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002756 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002757 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002758 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002759
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002760 if (unlikely(ret == -1))
2761 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002762
Willy Tarreau47860ed2015-03-10 14:07:50 +01002763 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002764 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002765 return 1;
2766}
2767
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002768/* Check arguments for the fucntion "hlua_channel_get_yield". */
2769__LJMP static int hlua_channel_get(lua_State *L)
2770{
2771 MAY_LJMP(check_args(L, 1, "get"));
2772 MAY_LJMP(hlua_checkchannel(L, 1));
2773 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2774}
2775
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002776/* This functions consumes and returns one line. If the channel is closed,
2777 * and the last data does not contains a final '\n', the data are returned
2778 * without the final '\n'. When no more data are avalaible, it returns nil
2779 * value.
2780 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002781__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002782{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002783 char *blk1;
2784 char *blk2;
2785 int len1;
2786 int len2;
2787 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002788 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002789 int ret;
2790 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002791
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002792 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2793
Willy Tarreau06d80a92017-10-19 14:32:15 +02002794 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002795 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002796 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002797
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002798 if (ret == -1) {
2799 lua_pushnil(L);
2800 return 1;
2801 }
2802
2803 luaL_buffinit(L, &b);
2804 luaL_addlstring(&b, blk1, len1);
2805 len = len1;
2806 if (unlikely(ret == 2)) {
2807 luaL_addlstring(&b, blk2, len2);
2808 len += len2;
2809 }
2810 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002811 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002812 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002813 return 1;
2814}
2815
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002816/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2817__LJMP static int hlua_channel_getline(lua_State *L)
2818{
2819 MAY_LJMP(check_args(L, 1, "getline"));
2820 MAY_LJMP(hlua_checkchannel(L, 1));
2821 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2822}
2823
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002824/* This function takes a string as input, and append it at the
2825 * input side of channel. If the data is too big, but a space
2826 * is probably available after sending some data, the function
2827 * yield. If the data is bigger than the buffer, or if the
2828 * channel is closed, it returns -1. otherwise, it returns the
2829 * amount of data writed.
2830 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002831__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002832{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002833 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002834 size_t len;
2835 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2836 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2837 int ret;
2838 int max;
2839
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002840 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2841 * the request buffer if its not required.
2842 */
2843 if (chn->buf->size == 0) {
2844 si_applet_cant_put(chn_prod(chn));
2845 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
2846 }
2847
Willy Tarreau47860ed2015-03-10 14:07:50 +01002848 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002849 if (max > len - l)
2850 max = len - l;
2851
Willy Tarreau06d80a92017-10-19 14:32:15 +02002852 ret = ci_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002853 if (ret == -2 || ret == -3) {
2854 lua_pushinteger(L, -1);
2855 return 1;
2856 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002857 if (ret == -1) {
2858 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002859 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002860 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002861 l += ret;
2862 lua_pop(L, 1);
2863 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002864 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002865
Willy Tarreau47860ed2015-03-10 14:07:50 +01002866 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2867 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002868 /* There are no space avalaible, and the output buffer is empty.
2869 * in this case, we cannot add more data, so we cannot yield,
2870 * we return the amount of copyied data.
2871 */
2872 return 1;
2873 }
2874 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002875 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002876 return 1;
2877}
2878
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002879/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002880 * of the writed string, or -1 if the channel is closed or if the
2881 * buffer size is too little for the data.
2882 */
2883__LJMP static int hlua_channel_append(lua_State *L)
2884{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002885 size_t len;
2886
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002887 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002888 MAY_LJMP(hlua_checkchannel(L, 1));
2889 MAY_LJMP(luaL_checklstring(L, 2, &len));
2890 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002891 lua_pushinteger(L, 0);
2892
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002893 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002894}
2895
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002896/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002897 * his process by cleaning the buffer. The result is a replacement
2898 * of the current data. It returns the length of the writed string,
2899 * or -1 if the channel is closed or if the buffer size is too
2900 * little for the data.
2901 */
2902__LJMP static int hlua_channel_set(lua_State *L)
2903{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002904 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002905
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002906 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002907 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002908 lua_pushinteger(L, 0);
2909
Willy Tarreau47860ed2015-03-10 14:07:50 +01002910 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002911
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002912 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002913}
2914
2915/* Append data in the output side of the buffer. This data is immediatly
2916 * sent. The fcuntion returns the ammount of data writed. If the buffer
2917 * cannot contains the data, the function yield. The function returns -1
2918 * if the channel is closed.
2919 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002920__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002921{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002922 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002923 size_t len;
2924 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2925 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2926 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002927 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002928
Willy Tarreau47860ed2015-03-10 14:07:50 +01002929 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002930 lua_pushinteger(L, -1);
2931 return 1;
2932 }
2933
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002934 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2935 * the request buffer if its not required.
2936 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002937 if (chn->buf->size == 0) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002938 si_applet_cant_put(chn_prod(chn));
2939 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002940 }
2941
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002942 /* the writed data will be immediatly sent, so we can check
2943 * the avalaible space without taking in account the reserve.
2944 * The reserve is guaranted for the processing of incoming
2945 * data, because the buffer will be flushed.
2946 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002947 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002948
2949 /* If there are no space avalaible, and the output buffer is empty.
2950 * in this case, we cannot add more data, so we cannot yield,
2951 * we return the amount of copyied data.
2952 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002953 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002954 return 1;
2955
2956 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002957 if (max > len - l)
2958 max = len - l;
2959
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002960 /* The buffer avalaible size may be not contiguous. This test
2961 * detects a non contiguous buffer and realign it.
2962 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002963 if (bi_space_for_replace(chn->buf) < max)
2964 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002965
2966 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002967 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002968
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002969 /* buffer replace considers that the input part is filled.
2970 * so, I must forward these new data in the output part.
2971 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002972 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002973
2974 l += max;
2975 lua_pop(L, 1);
2976 lua_pushinteger(L, l);
2977
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002978 /* If there are no space avalaible, and the output buffer is empty.
2979 * in this case, we cannot add more data, so we cannot yield,
2980 * we return the amount of copyied data.
2981 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002982 max = chn->buf->size - buffer_len(chn->buf);
2983 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002984 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002985
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002986 if (l < len) {
2987 /* If we are waiting for space in the response buffer, we
2988 * must set the flag WAKERESWR. This flag required the task
2989 * wake up if any activity is detected on the response buffer.
2990 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002991 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002992 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002993 else
2994 HLUA_SET_WAKEREQWR(hlua);
2995 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002996 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002997
2998 return 1;
2999}
3000
3001/* Just a wraper of "_hlua_channel_send". This wrapper permits
3002 * yield the LUA process, and resume it without checking the
3003 * input arguments.
3004 */
3005__LJMP static int hlua_channel_send(lua_State *L)
3006{
3007 MAY_LJMP(check_args(L, 2, "send"));
3008 lua_pushinteger(L, 0);
3009
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003010 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003011}
3012
3013/* This function forward and amount of butes. The data pass from
3014 * the input side of the buffer to the output side, and can be
3015 * forwarded. This function never fails.
3016 *
3017 * The Lua function takes an amount of bytes to be forwarded in
3018 * imput. It returns the number of bytes forwarded.
3019 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003020__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003021{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003022 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003023 int len;
3024 int l;
3025 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003026 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003027
3028 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3029 len = MAY_LJMP(luaL_checkinteger(L, 2));
3030 l = MAY_LJMP(luaL_checkinteger(L, -1));
3031
3032 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01003033 if (max > chn->buf->i)
3034 max = chn->buf->i;
3035 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003036 l += max;
3037
3038 lua_pop(L, 1);
3039 lua_pushinteger(L, l);
3040
3041 /* Check if it miss bytes to forward. */
3042 if (l < len) {
3043 /* The the input channel or the output channel are closed, we
3044 * must return the amount of data forwarded.
3045 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003046 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003047 return 1;
3048
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003049 /* If we are waiting for space data in the response buffer, we
3050 * must set the flag WAKERESWR. This flag required the task
3051 * wake up if any activity is detected on the response buffer.
3052 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003053 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003054 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003055 else
3056 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003057
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003058 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01003059 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003060 }
3061
3062 return 1;
3063}
3064
3065/* Just check the input and prepare the stack for the previous
3066 * function "hlua_channel_forward_yield"
3067 */
3068__LJMP static int hlua_channel_forward(lua_State *L)
3069{
3070 MAY_LJMP(check_args(L, 2, "forward"));
3071 MAY_LJMP(hlua_checkchannel(L, 1));
3072 MAY_LJMP(luaL_checkinteger(L, 2));
3073
3074 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003075 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003076}
3077
3078/* Just returns the number of bytes available in the input
3079 * side of the buffer. This function never fails.
3080 */
3081__LJMP static int hlua_channel_get_in_len(lua_State *L)
3082{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003083 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003084
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003085 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003086 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01003087 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003088 return 1;
3089}
3090
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003091/* Returns true if the channel is full. */
3092__LJMP static int hlua_channel_is_full(lua_State *L)
3093{
3094 struct channel *chn;
3095 int rem;
3096
3097 MAY_LJMP(check_args(L, 1, "is_full"));
3098 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3099
3100 rem = chn->buf->size;
3101 rem -= chn->buf->o; /* Output size */
3102 rem -= chn->buf->i; /* Input size */
3103 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
3104
3105 lua_pushboolean(L, rem <= 0);
3106 return 1;
3107}
3108
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003109/* Just returns the number of bytes available in the output
3110 * side of the buffer. This function never fails.
3111 */
3112__LJMP static int hlua_channel_get_out_len(lua_State *L)
3113{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003114 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003115
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003116 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003117 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01003118 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003119 return 1;
3120}
3121
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003122/*
3123 *
3124 *
3125 * Class Fetches
3126 *
3127 *
3128 */
3129
3130/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003131 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003132 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003133__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003134{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003135 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003136}
3137
3138/* This function creates and push in the stack a fetch object according
3139 * with a current TXN.
3140 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003141static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003142{
Willy Tarreau7073c472015-04-06 11:15:40 +02003143 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003144
3145 /* Check stack size. */
3146 if (!lua_checkstack(L, 3))
3147 return 0;
3148
3149 /* Create the object: obj[0] = userdata.
3150 * Note that the base of the Fetches object is the
3151 * transaction object.
3152 */
3153 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003154 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003155 lua_rawseti(L, -2, 0);
3156
Willy Tarreau7073c472015-04-06 11:15:40 +02003157 hsmp->s = txn->s;
3158 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003159 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003160 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003161
3162 /* Pop a class sesison metatable and affect it to the userdata. */
3163 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3164 lua_setmetatable(L, -2);
3165
3166 return 1;
3167}
3168
3169/* This function is an LUA binding. It is called with each sample-fetch.
3170 * It uses closure argument to store the associated sample-fetch. It
3171 * returns only one argument or throws an error. An error is thrown
3172 * only if an error is encountered during the argument parsing. If
3173 * the "sample-fetch" function fails, nil is returned.
3174 */
3175__LJMP static int hlua_run_sample_fetch(lua_State *L)
3176{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003177 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003178 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003179 struct arg args[ARGM_NBARGS + 1];
3180 int i;
3181 struct sample smp;
3182
3183 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003184 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003185
3186 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003187 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003188
Thierry FOURNIERca988662015-12-20 18:43:03 +01003189 /* Check execution authorization. */
3190 if (f->use & SMP_USE_HTTP_ANY &&
3191 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3192 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3193 "is not available in Lua services", f->kw);
3194 WILL_LJMP(lua_error(L));
3195 }
3196
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003197 /* Get extra arguments. */
3198 for (i = 0; i < lua_gettop(L) - 1; i++) {
3199 if (i >= ARGM_NBARGS)
3200 break;
3201 hlua_lua2arg(L, i + 2, &args[i]);
3202 }
3203 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003204 args[i].data.str.str = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003205
3206 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003207 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003208
3209 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003210 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003211 lua_pushfstring(L, "error in arguments");
3212 WILL_LJMP(lua_error(L));
3213 }
3214
3215 /* Initialise the sample. */
3216 memset(&smp, 0, sizeof(smp));
3217
3218 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003219 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003220 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003221 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003222 lua_pushstring(L, "");
3223 else
3224 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003225 return 1;
3226 }
3227
3228 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003229 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003230 hlua_smp2lua_str(L, &smp);
3231 else
3232 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003233 return 1;
3234}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003235
3236/*
3237 *
3238 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003239 * Class Converters
3240 *
3241 *
3242 */
3243
3244/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003245 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003246 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003247__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003248{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003249 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003250}
3251
3252/* This function creates and push in the stack a Converters object
3253 * according with a current TXN.
3254 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003255static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003256{
Willy Tarreau7073c472015-04-06 11:15:40 +02003257 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003258
3259 /* Check stack size. */
3260 if (!lua_checkstack(L, 3))
3261 return 0;
3262
3263 /* Create the object: obj[0] = userdata.
3264 * Note that the base of the Converters object is the
3265 * same than the TXN object.
3266 */
3267 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003268 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003269 lua_rawseti(L, -2, 0);
3270
Willy Tarreau7073c472015-04-06 11:15:40 +02003271 hsmp->s = txn->s;
3272 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003273 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003274 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003275
Willy Tarreau87b09662015-04-03 00:22:06 +02003276 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003277 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3278 lua_setmetatable(L, -2);
3279
3280 return 1;
3281}
3282
3283/* This function is an LUA binding. It is called with each converter.
3284 * It uses closure argument to store the associated converter. It
3285 * returns only one argument or throws an error. An error is thrown
3286 * only if an error is encountered during the argument parsing. If
3287 * the converter function function fails, nil is returned.
3288 */
3289__LJMP static int hlua_run_sample_conv(lua_State *L)
3290{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003291 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003292 struct sample_conv *conv;
3293 struct arg args[ARGM_NBARGS + 1];
3294 int i;
3295 struct sample smp;
3296
3297 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003298 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003299
3300 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003301 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003302
3303 /* Get extra arguments. */
3304 for (i = 0; i < lua_gettop(L) - 2; i++) {
3305 if (i >= ARGM_NBARGS)
3306 break;
3307 hlua_lua2arg(L, i + 3, &args[i]);
3308 }
3309 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003310 args[i].data.str.str = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003311
3312 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003313 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003314
3315 /* Run the special args checker. */
3316 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3317 hlua_pusherror(L, "error in arguments");
3318 WILL_LJMP(lua_error(L));
3319 }
3320
3321 /* Initialise the sample. */
3322 if (!hlua_lua2smp(L, 2, &smp)) {
3323 hlua_pusherror(L, "error in the input argument");
3324 WILL_LJMP(lua_error(L));
3325 }
3326
Willy Tarreau1777ea62016-03-10 16:15:46 +01003327 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3328
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003329 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003330 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003331 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003332 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003333 WILL_LJMP(lua_error(L));
3334 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003335 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3336 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003337 hlua_pusherror(L, "error during the input argument casting");
3338 WILL_LJMP(lua_error(L));
3339 }
3340
3341 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003342 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003343 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003344 lua_pushstring(L, "");
3345 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003346 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003347 return 1;
3348 }
3349
3350 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003351 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003352 hlua_smp2lua_str(L, &smp);
3353 else
3354 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003355 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003356}
3357
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003358/*
3359 *
3360 *
3361 * Class AppletTCP
3362 *
3363 *
3364 */
3365
3366/* Returns a struct hlua_txn if the stack entry "ud" is
3367 * a class stream, otherwise it throws an error.
3368 */
3369__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3370{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003371 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003372}
3373
3374/* This function creates and push in the stack an Applet object
3375 * according with a current TXN.
3376 */
3377static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3378{
3379 struct hlua_appctx *appctx;
3380 struct stream_interface *si = ctx->owner;
3381 struct stream *s = si_strm(si);
3382 struct proxy *p = s->be;
3383
3384 /* Check stack size. */
3385 if (!lua_checkstack(L, 3))
3386 return 0;
3387
3388 /* Create the object: obj[0] = userdata.
3389 * Note that the base of the Converters object is the
3390 * same than the TXN object.
3391 */
3392 lua_newtable(L);
3393 appctx = lua_newuserdata(L, sizeof(*appctx));
3394 lua_rawseti(L, -2, 0);
3395 appctx->appctx = ctx;
3396 appctx->htxn.s = s;
3397 appctx->htxn.p = p;
3398
3399 /* Create the "f" field that contains a list of fetches. */
3400 lua_pushstring(L, "f");
3401 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3402 return 0;
3403 lua_settable(L, -3);
3404
3405 /* Create the "sf" field that contains a list of stringsafe fetches. */
3406 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003407 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003408 return 0;
3409 lua_settable(L, -3);
3410
3411 /* Create the "c" field that contains a list of converters. */
3412 lua_pushstring(L, "c");
3413 if (!hlua_converters_new(L, &appctx->htxn, 0))
3414 return 0;
3415 lua_settable(L, -3);
3416
3417 /* Create the "sc" field that contains a list of stringsafe converters. */
3418 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003419 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003420 return 0;
3421 lua_settable(L, -3);
3422
3423 /* Pop a class stream metatable and affect it to the table. */
3424 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3425 lua_setmetatable(L, -2);
3426
3427 return 1;
3428}
3429
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003430__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3431{
3432 struct hlua_appctx *appctx;
3433 struct stream *s;
3434 const char *name;
3435 size_t len;
3436 struct sample smp;
3437
3438 MAY_LJMP(check_args(L, 3, "set_var"));
3439
3440 /* It is useles to retrieve the stream, but this function
3441 * runs only in a stream context.
3442 */
3443 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3444 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3445 s = appctx->htxn.s;
3446
3447 /* Converts the third argument in a sample. */
3448 hlua_lua2smp(L, 3, &smp);
3449
3450 /* Store the sample in a variable. */
3451 smp_set_owner(&smp, s->be, s->sess, s, 0);
3452 vars_set_by_name(name, len, &smp);
3453 return 0;
3454}
3455
3456__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3457{
3458 struct hlua_appctx *appctx;
3459 struct stream *s;
3460 const char *name;
3461 size_t len;
3462 struct sample smp;
3463
3464 MAY_LJMP(check_args(L, 2, "unset_var"));
3465
3466 /* It is useles to retrieve the stream, but this function
3467 * runs only in a stream context.
3468 */
3469 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3470 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3471 s = appctx->htxn.s;
3472
3473 /* Unset the variable. */
3474 smp_set_owner(&smp, s->be, s->sess, s, 0);
3475 vars_unset_by_name(name, len, &smp);
3476 return 0;
3477}
3478
3479__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3480{
3481 struct hlua_appctx *appctx;
3482 struct stream *s;
3483 const char *name;
3484 size_t len;
3485 struct sample smp;
3486
3487 MAY_LJMP(check_args(L, 2, "get_var"));
3488
3489 /* It is useles to retrieve the stream, but this function
3490 * runs only in a stream context.
3491 */
3492 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3493 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3494 s = appctx->htxn.s;
3495
3496 smp_set_owner(&smp, s->be, s->sess, s, 0);
3497 if (!vars_get_by_name(name, len, &smp)) {
3498 lua_pushnil(L);
3499 return 1;
3500 }
3501
3502 return hlua_smp2lua(L, &smp);
3503}
3504
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003505__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3506{
3507 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3508 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003509 struct hlua *hlua;
3510
3511 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003512 if (!s->hlua)
3513 return 0;
3514 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003515
3516 MAY_LJMP(check_args(L, 2, "set_priv"));
3517
3518 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003519 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003520
3521 /* Get and store new value. */
3522 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3523 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3524
3525 return 0;
3526}
3527
3528__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3529{
3530 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3531 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003532 struct hlua *hlua;
3533
3534 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003535 if (!s->hlua) {
3536 lua_pushnil(L);
3537 return 1;
3538 }
3539 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003540
3541 /* Push configuration index in the stack. */
3542 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3543
3544 return 1;
3545}
3546
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003547/* If expected data not yet available, it returns a yield. This function
3548 * consumes the data in the buffer. It returns a string containing the
3549 * data. This string can be empty.
3550 */
3551__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3552{
3553 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3554 struct stream_interface *si = appctx->appctx->owner;
3555 int ret;
3556 char *blk1;
3557 int len1;
3558 char *blk2;
3559 int len2;
3560
3561 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003562 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003563
3564 /* Data not yet avalaible. return yield. */
3565 if (ret == 0) {
3566 si_applet_cant_get(si);
3567 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3568 }
3569
3570 /* End of data: commit the total strings and return. */
3571 if (ret < 0) {
3572 luaL_pushresult(&appctx->b);
3573 return 1;
3574 }
3575
3576 /* Ensure that the block 2 length is usable. */
3577 if (ret == 1)
3578 len2 = 0;
3579
3580 /* dont check the max length read and dont check. */
3581 luaL_addlstring(&appctx->b, blk1, len1);
3582 luaL_addlstring(&appctx->b, blk2, len2);
3583
3584 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003585 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003586 luaL_pushresult(&appctx->b);
3587 return 1;
3588}
3589
3590/* Check arguments for the fucntion "hlua_channel_get_yield". */
3591__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3592{
3593 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3594
3595 /* Initialise the string catenation. */
3596 luaL_buffinit(L, &appctx->b);
3597
3598 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3599}
3600
3601/* If expected data not yet available, it returns a yield. This function
3602 * consumes the data in the buffer. It returns a string containing the
3603 * data. This string can be empty.
3604 */
3605__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3606{
3607 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3608 struct stream_interface *si = appctx->appctx->owner;
3609 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3610 int ret;
3611 char *blk1;
3612 int len1;
3613 char *blk2;
3614 int len2;
3615
3616 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003617 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003618
3619 /* Data not yet avalaible. return yield. */
3620 if (ret == 0) {
3621 si_applet_cant_get(si);
3622 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3623 }
3624
3625 /* End of data: commit the total strings and return. */
3626 if (ret < 0) {
3627 luaL_pushresult(&appctx->b);
3628 return 1;
3629 }
3630
3631 /* Ensure that the block 2 length is usable. */
3632 if (ret == 1)
3633 len2 = 0;
3634
3635 if (len == -1) {
3636
3637 /* If len == -1, catenate all the data avalaile and
3638 * yield because we want to get all the data until
3639 * the end of data stream.
3640 */
3641 luaL_addlstring(&appctx->b, blk1, len1);
3642 luaL_addlstring(&appctx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02003643 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003644 si_applet_cant_get(si);
3645 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3646
3647 } else {
3648
3649 /* Copy the fisrt block caping to the length required. */
3650 if (len1 > len)
3651 len1 = len;
3652 luaL_addlstring(&appctx->b, blk1, len1);
3653 len -= len1;
3654
3655 /* Copy the second block. */
3656 if (len2 > len)
3657 len2 = len;
3658 luaL_addlstring(&appctx->b, blk2, len2);
3659 len -= len2;
3660
3661 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003662 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003663
3664 /* If we are no other data avalaible, yield waiting for new data. */
3665 if (len > 0) {
3666 lua_pushinteger(L, len);
3667 lua_replace(L, 2);
3668 si_applet_cant_get(si);
3669 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3670 }
3671
3672 /* return the result. */
3673 luaL_pushresult(&appctx->b);
3674 return 1;
3675 }
3676
3677 /* we never executes this */
3678 hlua_pusherror(L, "Lua: internal error");
3679 WILL_LJMP(lua_error(L));
3680 return 0;
3681}
3682
3683/* Check arguments for the fucntion "hlua_channel_get_yield". */
3684__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3685{
3686 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3687 int len = -1;
3688
3689 if (lua_gettop(L) > 2)
3690 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3691 if (lua_gettop(L) >= 2) {
3692 len = MAY_LJMP(luaL_checkinteger(L, 2));
3693 lua_pop(L, 1);
3694 }
3695
3696 /* Confirm or set the required length */
3697 lua_pushinteger(L, len);
3698
3699 /* Initialise the string catenation. */
3700 luaL_buffinit(L, &appctx->b);
3701
3702 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3703}
3704
3705/* Append data in the output side of the buffer. This data is immediatly
3706 * sent. The fcuntion returns the ammount of data writed. If the buffer
3707 * cannot contains the data, the function yield. The function returns -1
3708 * if the channel is closed.
3709 */
3710__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3711{
3712 size_t len;
3713 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3714 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3715 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3716 struct stream_interface *si = appctx->appctx->owner;
3717 struct channel *chn = si_ic(si);
3718 int max;
3719
3720 /* Get the max amount of data which can write as input in the channel. */
3721 max = channel_recv_max(chn);
3722 if (max > (len - l))
3723 max = len - l;
3724
3725 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003726 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003727
3728 /* update counters. */
3729 l += max;
3730 lua_pop(L, 1);
3731 lua_pushinteger(L, l);
3732
3733 /* If some data is not send, declares the situation to the
3734 * applet, and returns a yield.
3735 */
3736 if (l < len) {
3737 si_applet_cant_put(si);
3738 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3739 }
3740
3741 return 1;
3742}
3743
3744/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3745 * yield the LUA process, and resume it without checking the
3746 * input arguments.
3747 */
3748__LJMP static int hlua_applet_tcp_send(lua_State *L)
3749{
3750 MAY_LJMP(check_args(L, 2, "send"));
3751 lua_pushinteger(L, 0);
3752
3753 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3754}
3755
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003756/*
3757 *
3758 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003759 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003760 *
3761 *
3762 */
3763
3764/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003765 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003766 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003767__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003768{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003769 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003770}
3771
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003772/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003773 * according with a current TXN.
3774 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003775static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003776{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003777 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003778 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003779 struct stream_interface *si = ctx->owner;
3780 struct stream *s = si_strm(si);
3781 struct proxy *px = s->be;
3782 struct http_txn *txn = s->txn;
3783 const char *path;
3784 const char *end;
3785 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003786
3787 /* Check stack size. */
3788 if (!lua_checkstack(L, 3))
3789 return 0;
3790
3791 /* Create the object: obj[0] = userdata.
3792 * Note that the base of the Converters object is the
3793 * same than the TXN object.
3794 */
3795 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003796 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003797 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003798 appctx->appctx = ctx;
3799 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003800 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003801 appctx->htxn.s = s;
3802 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003803
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003804 /* Create the "f" field that contains a list of fetches. */
3805 lua_pushstring(L, "f");
3806 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3807 return 0;
3808 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003809
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003810 /* Create the "sf" field that contains a list of stringsafe fetches. */
3811 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003812 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003813 return 0;
3814 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003815
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003816 /* Create the "c" field that contains a list of converters. */
3817 lua_pushstring(L, "c");
3818 if (!hlua_converters_new(L, &appctx->htxn, 0))
3819 return 0;
3820 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003821
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003822 /* Create the "sc" field that contains a list of stringsafe converters. */
3823 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003824 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003825 return 0;
3826 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003827
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003828 /* Stores the request method. */
3829 lua_pushstring(L, "method");
3830 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3831 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003832
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003833 /* Stores the http version. */
3834 lua_pushstring(L, "version");
3835 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3836 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003837
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003838 /* creates an array of headers. hlua_http_get_headers() crates and push
3839 * the array on the top of the stack.
3840 */
3841 lua_pushstring(L, "headers");
3842 htxn.s = s;
3843 htxn.p = px;
3844 htxn.dir = SMP_OPT_DIR_REQ;
3845 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3846 return 0;
3847 lua_settable(L, -3);
3848
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003849 /* Get path and qs */
3850 path = http_get_path(txn);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003851 if (path) {
3852 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3853 p = path;
3854 while (p < end && *p != '?')
3855 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003856
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003857 /* Stores the request path. */
3858 lua_pushstring(L, "path");
3859 lua_pushlstring(L, path, p - path);
3860 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003861
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003862 /* Stores the query string. */
3863 lua_pushstring(L, "qs");
3864 if (*p == '?')
3865 p++;
3866 lua_pushlstring(L, p, end - p);
3867 lua_settable(L, -3);
3868 }
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003869
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003870 /* Stores the request path. */
3871 lua_pushstring(L, "length");
3872 lua_pushinteger(L, txn->req.body_len);
3873 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003874
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003875 /* Create an array of HTTP request headers. */
3876 lua_pushstring(L, "headers");
3877 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3878 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003879
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003880 /* Create an empty array of HTTP request headers. */
3881 lua_pushstring(L, "response");
3882 lua_newtable(L);
3883 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003884
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003885 /* Pop a class stream metatable and affect it to the table. */
3886 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3887 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003888
3889 return 1;
3890}
3891
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003892__LJMP static int hlua_applet_http_set_var(lua_State *L)
3893{
3894 struct hlua_appctx *appctx;
3895 struct stream *s;
3896 const char *name;
3897 size_t len;
3898 struct sample smp;
3899
3900 MAY_LJMP(check_args(L, 3, "set_var"));
3901
3902 /* It is useles to retrieve the stream, but this function
3903 * runs only in a stream context.
3904 */
3905 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3906 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3907 s = appctx->htxn.s;
3908
3909 /* Converts the third argument in a sample. */
3910 hlua_lua2smp(L, 3, &smp);
3911
3912 /* Store the sample in a variable. */
3913 smp_set_owner(&smp, s->be, s->sess, s, 0);
3914 vars_set_by_name(name, len, &smp);
3915 return 0;
3916}
3917
3918__LJMP static int hlua_applet_http_unset_var(lua_State *L)
3919{
3920 struct hlua_appctx *appctx;
3921 struct stream *s;
3922 const char *name;
3923 size_t len;
3924 struct sample smp;
3925
3926 MAY_LJMP(check_args(L, 2, "unset_var"));
3927
3928 /* It is useles to retrieve the stream, but this function
3929 * runs only in a stream context.
3930 */
3931 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3932 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3933 s = appctx->htxn.s;
3934
3935 /* Unset the variable. */
3936 smp_set_owner(&smp, s->be, s->sess, s, 0);
3937 vars_unset_by_name(name, len, &smp);
3938 return 0;
3939}
3940
3941__LJMP static int hlua_applet_http_get_var(lua_State *L)
3942{
3943 struct hlua_appctx *appctx;
3944 struct stream *s;
3945 const char *name;
3946 size_t len;
3947 struct sample smp;
3948
3949 MAY_LJMP(check_args(L, 2, "get_var"));
3950
3951 /* It is useles to retrieve the stream, but this function
3952 * runs only in a stream context.
3953 */
3954 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3955 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3956 s = appctx->htxn.s;
3957
3958 smp_set_owner(&smp, s->be, s->sess, s, 0);
3959 if (!vars_get_by_name(name, len, &smp)) {
3960 lua_pushnil(L);
3961 return 1;
3962 }
3963
3964 return hlua_smp2lua(L, &smp);
3965}
3966
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003967__LJMP static int hlua_applet_http_set_priv(lua_State *L)
3968{
3969 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3970 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003971 struct hlua *hlua;
3972
3973 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003974 if (!s->hlua)
3975 return 0;
3976 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003977
3978 MAY_LJMP(check_args(L, 2, "set_priv"));
3979
3980 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003981 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003982
3983 /* Get and store new value. */
3984 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3985 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3986
3987 return 0;
3988}
3989
3990__LJMP static int hlua_applet_http_get_priv(lua_State *L)
3991{
3992 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3993 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003994 struct hlua *hlua;
3995
3996 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003997 if (!s->hlua) {
3998 lua_pushnil(L);
3999 return 1;
4000 }
4001 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004002
4003 /* Push configuration index in the stack. */
4004 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4005
4006 return 1;
4007}
4008
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004009/* If expected data not yet available, it returns a yield. This function
4010 * consumes the data in the buffer. It returns a string containing the
4011 * data. This string can be empty.
4012 */
4013__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004014{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004015 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4016 struct stream_interface *si = appctx->appctx->owner;
4017 struct channel *chn = si_ic(si);
4018 int ret;
4019 char *blk1;
4020 int len1;
4021 char *blk2;
4022 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004023
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004024 /* Maybe we cant send a 100-continue ? */
4025 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau06d80a92017-10-19 14:32:15 +02004026 ret = ci_putblk(chn, HTTP_100C, strlen(HTTP_100C));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004027 /* if ret == -2 or -3 the channel closed or the message si too
4028 * big for the buffers. We cant send anything. So, we ignoring
4029 * the error, considers that the 100-continue is sent, and try
4030 * to receive.
4031 * If ret is -1, we dont have room in the buffer, so we yield.
4032 */
4033 if (ret == -1) {
4034 si_applet_cant_put(si);
4035 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
4036 }
4037 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4038 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004039
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004040 /* Check for the end of the data. */
4041 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
4042 luaL_pushresult(&appctx->b);
4043 return 1;
4044 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004045
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004046 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004047 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004048
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004049 /* Data not yet avalaible. return yield. */
4050 if (ret == 0) {
4051 si_applet_cant_get(si);
4052 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
4053 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004054
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004055 /* End of data: commit the total strings and return. */
4056 if (ret < 0) {
4057 luaL_pushresult(&appctx->b);
4058 return 1;
4059 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004060
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004061 /* Ensure that the block 2 length is usable. */
4062 if (ret == 1)
4063 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004064
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004065 /* Copy the fisrt block caping to the length required. */
4066 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4067 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4068 luaL_addlstring(&appctx->b, blk1, len1);
4069 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004070
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004071 /* Copy the second block. */
4072 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4073 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4074 luaL_addlstring(&appctx->b, blk2, len2);
4075 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004076
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004077 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004078 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004079 luaL_pushresult(&appctx->b);
4080 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004081}
4082
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004083/* Check arguments for the fucntion "hlua_channel_get_yield". */
4084__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004085{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004086 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004087
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004088 /* Initialise the string catenation. */
4089 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004090
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004091 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004092}
4093
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004094/* If expected data not yet available, it returns a yield. This function
4095 * consumes the data in the buffer. It returns a string containing the
4096 * data. This string can be empty.
4097 */
4098__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004099{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004100 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4101 struct stream_interface *si = appctx->appctx->owner;
4102 int len = MAY_LJMP(luaL_checkinteger(L, 2));
4103 struct channel *chn = si_ic(si);
4104 int ret;
4105 char *blk1;
4106 int len1;
4107 char *blk2;
4108 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004109
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004110 /* Maybe we cant send a 100-continue ? */
4111 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau06d80a92017-10-19 14:32:15 +02004112 ret = ci_putblk(chn, HTTP_100C, strlen(HTTP_100C));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004113 /* if ret == -2 or -3 the channel closed or the message si too
4114 * big for the buffers. We cant send anything. So, we ignoring
4115 * the error, considers that the 100-continue is sent, and try
4116 * to receive.
4117 * If ret is -1, we dont have room in the buffer, so we yield.
4118 */
4119 if (ret == -1) {
4120 si_applet_cant_put(si);
4121 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4122 }
4123 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4124 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004125
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004126 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004127 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004128
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004129 /* Data not yet avalaible. return yield. */
4130 if (ret == 0) {
4131 si_applet_cant_get(si);
4132 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4133 }
4134
4135 /* End of data: commit the total strings and return. */
4136 if (ret < 0) {
4137 luaL_pushresult(&appctx->b);
4138 return 1;
4139 }
4140
4141 /* Ensure that the block 2 length is usable. */
4142 if (ret == 1)
4143 len2 = 0;
4144
4145 /* Copy the fisrt block caping to the length required. */
4146 if (len1 > len)
4147 len1 = len;
4148 luaL_addlstring(&appctx->b, blk1, len1);
4149 len -= len1;
4150
4151 /* Copy the second block. */
4152 if (len2 > len)
4153 len2 = len;
4154 luaL_addlstring(&appctx->b, blk2, len2);
4155 len -= len2;
4156
4157 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004158 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004159 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
4160 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
4161
4162 /* If we are no other data avalaible, yield waiting for new data. */
4163 if (len > 0) {
4164 lua_pushinteger(L, len);
4165 lua_replace(L, 2);
4166 si_applet_cant_get(si);
4167 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4168 }
4169
4170 /* return the result. */
4171 luaL_pushresult(&appctx->b);
4172 return 1;
4173}
4174
4175/* Check arguments for the fucntion "hlua_channel_get_yield". */
4176__LJMP static int hlua_applet_http_recv(lua_State *L)
4177{
4178 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4179 int len = -1;
4180
4181 /* Check arguments. */
4182 if (lua_gettop(L) > 2)
4183 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4184 if (lua_gettop(L) >= 2) {
4185 len = MAY_LJMP(luaL_checkinteger(L, 2));
4186 lua_pop(L, 1);
4187 }
4188
4189 /* Check the required length */
4190 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4191 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4192 lua_pushinteger(L, len);
4193
4194 /* Initialise the string catenation. */
4195 luaL_buffinit(L, &appctx->b);
4196
4197 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4198}
4199
4200/* Append data in the output side of the buffer. This data is immediatly
4201 * sent. The fcuntion returns the ammount of data writed. If the buffer
4202 * cannot contains the data, the function yield. The function returns -1
4203 * if the channel is closed.
4204 */
4205__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4206{
4207 size_t len;
4208 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4209 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4210 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4211 struct stream_interface *si = appctx->appctx->owner;
4212 struct channel *chn = si_ic(si);
4213 int max;
4214
4215 /* Get the max amount of data which can write as input in the channel. */
4216 max = channel_recv_max(chn);
4217 if (max > (len - l))
4218 max = len - l;
4219
4220 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004221 ci_putblk(chn, str + l, max);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004222
4223 /* update counters. */
4224 l += max;
4225 lua_pop(L, 1);
4226 lua_pushinteger(L, l);
4227
4228 /* If some data is not send, declares the situation to the
4229 * applet, and returns a yield.
4230 */
4231 if (l < len) {
4232 si_applet_cant_put(si);
4233 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
4234 }
4235
4236 return 1;
4237}
4238
4239/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4240 * yield the LUA process, and resume it without checking the
4241 * input arguments.
4242 */
4243__LJMP static int hlua_applet_http_send(lua_State *L)
4244{
4245 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4246 size_t len;
4247 char hex[10];
4248
4249 MAY_LJMP(luaL_checklstring(L, 2, &len));
4250
4251 /* If transfer encoding chunked is selected, we surround the data
4252 * by chunk data.
4253 */
4254 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4255 snprintf(hex, 9, "%x", (unsigned int)len);
4256 lua_pushfstring(L, "%s\r\n", hex);
4257 lua_insert(L, 2); /* swap the last 2 entries. */
4258 lua_pushstring(L, "\r\n");
4259 lua_concat(L, 3);
4260 }
4261
4262 /* This interger is used for followinf the amount of data sent. */
4263 lua_pushinteger(L, 0);
4264
4265 /* We want to send some data. Headers must be sent. */
4266 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4267 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4268 WILL_LJMP(lua_error(L));
4269 }
4270
4271 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4272}
4273
4274__LJMP static int hlua_applet_http_addheader(lua_State *L)
4275{
4276 const char *name;
4277 int ret;
4278
4279 MAY_LJMP(hlua_checkapplet_http(L, 1));
4280 name = MAY_LJMP(luaL_checkstring(L, 2));
4281 MAY_LJMP(luaL_checkstring(L, 3));
4282
4283 /* Push in the stack the "response" entry. */
4284 ret = lua_getfield(L, 1, "response");
4285 if (ret != LUA_TTABLE) {
4286 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4287 "is expected as an array. %s found", lua_typename(L, ret));
4288 WILL_LJMP(lua_error(L));
4289 }
4290
4291 /* check if the header is already registered if it is not
4292 * the case, register it.
4293 */
4294 ret = lua_getfield(L, -1, name);
4295 if (ret == LUA_TNIL) {
4296
4297 /* Entry not found. */
4298 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4299
4300 /* Insert the new header name in the array in the top of the stack.
4301 * It left the new array in the top of the stack.
4302 */
4303 lua_newtable(L);
4304 lua_pushvalue(L, 2);
4305 lua_pushvalue(L, -2);
4306 lua_settable(L, -4);
4307
4308 } else if (ret != LUA_TTABLE) {
4309
4310 /* corruption error. */
4311 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4312 "is expected as an array. %s found", name, lua_typename(L, ret));
4313 WILL_LJMP(lua_error(L));
4314 }
4315
4316 /* Now the top od thestack is an array of values. We push
4317 * the header value as new entry.
4318 */
4319 lua_pushvalue(L, 3);
4320 ret = lua_rawlen(L, -2);
4321 lua_rawseti(L, -2, ret + 1);
4322 lua_pushboolean(L, 1);
4323 return 1;
4324}
4325
4326__LJMP static int hlua_applet_http_status(lua_State *L)
4327{
4328 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4329 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004330 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004331
4332 if (status < 100 || status > 599) {
4333 lua_pushboolean(L, 0);
4334 return 1;
4335 }
4336
4337 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004338 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004339 lua_pushboolean(L, 1);
4340 return 1;
4341}
4342
4343/* We will build the status line and the headers of the HTTP response.
4344 * We will try send at once if its not possible, we give back the hand
4345 * waiting for more room.
4346 */
4347__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4348{
4349 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4350 struct stream_interface *si = appctx->appctx->owner;
4351 struct channel *chn = si_ic(si);
4352 int ret;
4353 size_t len;
4354 const char *msg;
4355
4356 /* Get the message as the first argument on the stack. */
4357 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4358
4359 /* Send the message at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004360 ret = ci_putblk(chn, msg, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004361
4362 /* if ret == -2 or -3 the channel closed or the message si too
4363 * big for the buffers.
4364 */
4365 if (ret == -2 || ret == -3) {
4366 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4367 WILL_LJMP(lua_error(L));
4368 }
4369
4370 /* If ret is -1, we dont have room in the buffer, so we yield. */
4371 if (ret == -1) {
4372 si_applet_cant_put(si);
4373 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
4374 }
4375
4376 /* Headers sent, set the flag. */
4377 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4378 return 0;
4379}
4380
4381__LJMP static int hlua_applet_http_start_response(lua_State *L)
4382{
4383 struct chunk *tmp = get_trash_chunk();
4384 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004385 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02004386 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004387 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02004388 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004389 int id;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004390 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004391 int hdr_chunked = 0;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004392 const char *reason = appctx->appctx->ctx.hlua_apphttp.reason;
4393
4394 if (reason == NULL)
4395 reason = get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004396
4397 /* Use the same http version than the request. */
4398 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004399 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004400 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004401 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004402
4403 /* Get the array associated to the field "response" in the object AppletHTTP. */
4404 lua_pushvalue(L, 0);
4405 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4406 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4407 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4408 WILL_LJMP(lua_error(L));
4409 }
4410
4411 /* Browse the list of headers. */
4412 lua_pushnil(L);
4413 while(lua_next(L, -2) != 0) {
4414
4415 /* We expect a string as -2. */
4416 if (lua_type(L, -2) != LUA_TSTRING) {
4417 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4418 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4419 lua_typename(L, lua_type(L, -2)));
4420 WILL_LJMP(lua_error(L));
4421 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004422 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004423
4424 /* We expect an array as -1. */
4425 if (lua_type(L, -1) != LUA_TTABLE) {
4426 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4427 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4428 name,
4429 lua_typename(L, lua_type(L, -1)));
4430 WILL_LJMP(lua_error(L));
4431 }
4432
4433 /* Browse the table who is on the top of the stack. */
4434 lua_pushnil(L);
4435 while(lua_next(L, -2) != 0) {
4436
4437 /* We expect a number as -2. */
4438 if (lua_type(L, -2) != LUA_TNUMBER) {
4439 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4440 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4441 name,
4442 lua_typename(L, lua_type(L, -2)));
4443 WILL_LJMP(lua_error(L));
4444 }
4445 id = lua_tointeger(L, -2);
4446
4447 /* We expect a string as -2. */
4448 if (lua_type(L, -1) != LUA_TSTRING) {
4449 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4450 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4451 name, id,
4452 lua_typename(L, lua_type(L, -1)));
4453 WILL_LJMP(lua_error(L));
4454 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004455 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004456
4457 /* Catenate a new header. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004458 if (tmp->len + name_len + 2 + value_len + 2 < tmp->size) {
4459 memcpy(tmp->str + tmp->len, name, name_len);
4460 tmp->len += name_len;
4461 tmp->str[tmp->len++] = ':';
4462 tmp->str[tmp->len++] = ' ';
4463
4464 memcpy(tmp->str + tmp->len, value, value_len);
4465 tmp->len += value_len;
4466 tmp->str[tmp->len++] = '\r';
4467 tmp->str[tmp->len++] = '\n';
4468 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004469
4470 /* Protocol checks. */
4471
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004472 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004473 * is done without control. If it contains a bad value,
4474 * the content-length remains negative so that we can
4475 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004476 */
Willy Tarreaua3294632017-08-23 11:24:47 +02004477 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004478 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004479
4480 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004481 if (name_len == 17 && value_len == 7 &&
4482 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004483 strcasecmp("chunked", value) == 0)
4484 hdr_chunked = 1;
4485
4486 /* Remove the array from the stack, and get next element with a remaining string. */
4487 lua_pop(L, 1);
4488 }
4489
4490 /* Remove the array from the stack, and get next element with a remaining string. */
4491 lua_pop(L, 1);
4492 }
4493
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004494 /* If we dont have a content-length set, and the HTTP version is 1.1
4495 * and the status code implies the presence of a message body, we must
4496 * announce a transfer encoding chunked. This is required by haproxy
4497 * for the keepalive compliance. If the applet annouces a transfer-encoding
4498 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004499 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004500 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004501 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
4502 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4503 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4504 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004505 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4506 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4507 }
4508
4509 /* Finalize headers. */
4510 chunk_appendf(tmp, "\r\n");
4511
4512 /* Remove the last entry and the array of headers */
4513 lua_pop(L, 2);
4514
4515 /* Push the headers block. */
4516 lua_pushlstring(L, tmp->str, tmp->len);
4517
4518 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4519}
4520
4521/*
4522 *
4523 *
4524 * Class HTTP
4525 *
4526 *
4527 */
4528
4529/* Returns a struct hlua_txn if the stack entry "ud" is
4530 * a class stream, otherwise it throws an error.
4531 */
4532__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4533{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004534 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004535}
4536
4537/* This function creates and push in the stack a HTTP object
4538 * according with a current TXN.
4539 */
4540static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4541{
4542 struct hlua_txn *htxn;
4543
4544 /* Check stack size. */
4545 if (!lua_checkstack(L, 3))
4546 return 0;
4547
4548 /* Create the object: obj[0] = userdata.
4549 * Note that the base of the Converters object is the
4550 * same than the TXN object.
4551 */
4552 lua_newtable(L);
4553 htxn = lua_newuserdata(L, sizeof(*htxn));
4554 lua_rawseti(L, -2, 0);
4555
4556 htxn->s = txn->s;
4557 htxn->p = txn->p;
4558
4559 /* Pop a class stream metatable and affect it to the table. */
4560 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4561 lua_setmetatable(L, -2);
4562
4563 return 1;
4564}
4565
4566/* This function creates ans returns an array of HTTP headers.
4567 * This function does not fails. It is used as wrapper with the
4568 * 2 following functions.
4569 */
4570__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4571{
4572 const char *cur_ptr, *cur_next, *p;
4573 int old_idx, cur_idx;
4574 struct hdr_idx_elem *cur_hdr;
4575 const char *hn, *hv;
4576 int hnl, hvl;
4577 int type;
4578 const char *in;
4579 char *out;
4580 int len;
4581
4582 /* Create the table. */
4583 lua_newtable(L);
4584
4585 if (!htxn->s->txn)
4586 return 1;
4587
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004588 /* Check if a valid response is parsed */
4589 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4590 return 1;
4591
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004592 /* Build array of headers. */
4593 old_idx = 0;
4594 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4595
4596 while (1) {
4597 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4598 if (!cur_idx)
4599 break;
4600 old_idx = cur_idx;
4601
4602 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4603 cur_ptr = cur_next;
4604 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4605
4606 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4607 * and the next header starts at cur_next. We'll check
4608 * this header in the list as well as against the default
4609 * rule.
4610 */
4611
4612 /* look for ': *'. */
4613 hn = cur_ptr;
4614 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4615 if (p >= cur_ptr+cur_hdr->len)
4616 continue;
4617 hnl = p - hn;
4618 p++;
4619 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4620 p++;
4621 if (p >= cur_ptr+cur_hdr->len)
4622 continue;
4623 hv = p;
4624 hvl = cur_ptr+cur_hdr->len-p;
4625
4626 /* Lowercase the key. Don't check the size of trash, it have
4627 * the size of one buffer and the input data contains in one
4628 * buffer.
4629 */
4630 out = trash.str;
4631 for (in=hn; in<hn+hnl; in++, out++)
4632 *out = tolower(*in);
4633 *out = '\0';
4634
4635 /* Check for existing entry:
4636 * assume that the table is on the top of the stack, and
4637 * push the key in the stack, the function lua_gettable()
4638 * perform the lookup.
4639 */
4640 lua_pushlstring(L, trash.str, hnl);
4641 lua_gettable(L, -2);
4642 type = lua_type(L, -1);
4643
4644 switch (type) {
4645 case LUA_TNIL:
4646 /* Table not found, create it. */
4647 lua_pop(L, 1); /* remove the nil value. */
4648 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4649 lua_newtable(L); /* create and push empty table. */
4650 lua_pushlstring(L, hv, hvl); /* push header value. */
4651 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4652 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4653 break;
4654
4655 case LUA_TTABLE:
4656 /* Entry found: push the value in the table. */
4657 len = lua_rawlen(L, -1);
4658 lua_pushlstring(L, hv, hvl); /* push header value. */
4659 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4660 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4661 break;
4662
4663 default:
4664 /* Other cases are errors. */
4665 hlua_pusherror(L, "internal error during the parsing of headers.");
4666 WILL_LJMP(lua_error(L));
4667 }
4668 }
4669
4670 return 1;
4671}
4672
4673__LJMP static int hlua_http_req_get_headers(lua_State *L)
4674{
4675 struct hlua_txn *htxn;
4676
4677 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4678 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4679
4680 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4681}
4682
4683__LJMP static int hlua_http_res_get_headers(lua_State *L)
4684{
4685 struct hlua_txn *htxn;
4686
4687 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4688 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4689
4690 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4691}
4692
4693/* This function replace full header, or just a value in
4694 * the request or in the response. It is a wrapper fir the
4695 * 4 following functions.
4696 */
4697__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4698 struct http_msg *msg, int action)
4699{
4700 size_t name_len;
4701 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4702 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4703 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4704 struct my_regex re;
4705
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004706 /* Check if a valid response is parsed */
4707 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4708 return 0;
4709
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004710 if (!regex_comp(reg, &re, 1, 1, NULL))
4711 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4712
4713 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4714 regex_free(&re);
4715 return 0;
4716}
4717
4718__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4719{
4720 struct hlua_txn *htxn;
4721
4722 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4723 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4724
4725 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4726}
4727
4728__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4729{
4730 struct hlua_txn *htxn;
4731
4732 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4733 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4734
4735 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4736}
4737
4738__LJMP static int hlua_http_req_rep_val(lua_State *L)
4739{
4740 struct hlua_txn *htxn;
4741
4742 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4743 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4744
4745 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4746}
4747
4748__LJMP static int hlua_http_res_rep_val(lua_State *L)
4749{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004750 struct hlua_txn *htxn;
4751
4752 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4753 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4754
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004755 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004756}
4757
4758/* This function deletes all the occurences of an header.
4759 * It is a wrapper for the 2 following functions.
4760 */
4761__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4762{
4763 size_t len;
4764 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4765 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004766 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004767
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004768 /* Check if a valid response is parsed */
4769 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4770 return 0;
4771
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004772 ctx.idx = 0;
4773 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4774 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4775 return 0;
4776}
4777
4778__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4779{
4780 struct hlua_txn *htxn;
4781
4782 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4783 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4784
Willy Tarreaueee5b512015-04-03 23:46:31 +02004785 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004786}
4787
4788__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4789{
4790 struct hlua_txn *htxn;
4791
4792 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4793 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4794
Willy Tarreaueee5b512015-04-03 23:46:31 +02004795 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004796}
4797
4798/* This function adds an header. It is a wrapper used by
4799 * the 2 following functions.
4800 */
4801__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4802{
4803 size_t name_len;
4804 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4805 size_t value_len;
4806 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4807 char *p;
4808
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004809 /* Check if a valid message is parsed */
4810 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4811 return 0;
4812
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004813 /* Check length. */
4814 trash.len = value_len + name_len + 2;
4815 if (trash.len > trash.size)
4816 return 0;
4817
4818 /* Creates the header string. */
4819 p = trash.str;
4820 memcpy(p, name, name_len);
4821 p += name_len;
4822 *p = ':';
4823 p++;
4824 *p = ' ';
4825 p++;
4826 memcpy(p, value, value_len);
4827
Willy Tarreaueee5b512015-04-03 23:46:31 +02004828 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004829 trash.str, trash.len) != 0);
4830
4831 return 0;
4832}
4833
4834__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4835{
4836 struct hlua_txn *htxn;
4837
4838 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4839 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4840
Willy Tarreaueee5b512015-04-03 23:46:31 +02004841 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004842}
4843
4844__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4845{
4846 struct hlua_txn *htxn;
4847
4848 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4849 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4850
Willy Tarreaueee5b512015-04-03 23:46:31 +02004851 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004852}
4853
4854static int hlua_http_req_set_hdr(lua_State *L)
4855{
4856 struct hlua_txn *htxn;
4857
4858 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4859 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4860
Willy Tarreaueee5b512015-04-03 23:46:31 +02004861 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4862 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004863}
4864
4865static int hlua_http_res_set_hdr(lua_State *L)
4866{
4867 struct hlua_txn *htxn;
4868
4869 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4870 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4871
Willy Tarreaueee5b512015-04-03 23:46:31 +02004872 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4873 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004874}
4875
4876/* This function set the method. */
4877static int hlua_http_req_set_meth(lua_State *L)
4878{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004879 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004880 size_t name_len;
4881 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004882
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004883 /* Check if a valid request is parsed */
4884 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4885 lua_pushboolean(L, 0);
4886 return 1;
4887 }
4888
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004889 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004890 return 1;
4891}
4892
4893/* This function set the method. */
4894static int hlua_http_req_set_path(lua_State *L)
4895{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004896 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004897 size_t name_len;
4898 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004899
4900 /* Check if a valid request is parsed */
4901 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4902 lua_pushboolean(L, 0);
4903 return 1;
4904 }
4905
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004906 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004907 return 1;
4908}
4909
4910/* This function set the query-string. */
4911static int hlua_http_req_set_query(lua_State *L)
4912{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004913 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004914 size_t name_len;
4915 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004916
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004917 /* Check if a valid request is parsed */
4918 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4919 lua_pushboolean(L, 0);
4920 return 1;
4921 }
4922
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004923 /* Check length. */
4924 if (name_len > trash.size - 1) {
4925 lua_pushboolean(L, 0);
4926 return 1;
4927 }
4928
4929 /* Add the mark question as prefix. */
4930 chunk_reset(&trash);
4931 trash.str[trash.len++] = '?';
4932 memcpy(trash.str + trash.len, name, name_len);
4933 trash.len += name_len;
4934
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004935 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004936 return 1;
4937}
4938
4939/* This function set the uri. */
4940static int hlua_http_req_set_uri(lua_State *L)
4941{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004942 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004943 size_t name_len;
4944 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004945
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004946 /* Check if a valid request is parsed */
4947 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4948 lua_pushboolean(L, 0);
4949 return 1;
4950 }
4951
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004952 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004953 return 1;
4954}
4955
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004956/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004957static int hlua_http_res_set_status(lua_State *L)
4958{
4959 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4960 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004961 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004962
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004963 /* Check if a valid response is parsed */
4964 if (unlikely(htxn->s->txn->rsp.msg_state < HTTP_MSG_BODY))
4965 return 0;
4966
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004967 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004968 return 0;
4969}
4970
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004971/*
4972 *
4973 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004974 * Class TXN
4975 *
4976 *
4977 */
4978
4979/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004980 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004981 */
4982__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
4983{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004984 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004985}
4986
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004987__LJMP static int hlua_set_var(lua_State *L)
4988{
4989 struct hlua_txn *htxn;
4990 const char *name;
4991 size_t len;
4992 struct sample smp;
4993
4994 MAY_LJMP(check_args(L, 3, "set_var"));
4995
4996 /* It is useles to retrieve the stream, but this function
4997 * runs only in a stream context.
4998 */
4999 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5000 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5001
5002 /* Converts the third argument in a sample. */
5003 hlua_lua2smp(L, 3, &smp);
5004
5005 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005006 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005007 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005008 return 0;
5009}
5010
Christopher Faulet85d79c92016-11-09 16:54:56 +01005011__LJMP static int hlua_unset_var(lua_State *L)
5012{
5013 struct hlua_txn *htxn;
5014 const char *name;
5015 size_t len;
5016 struct sample smp;
5017
5018 MAY_LJMP(check_args(L, 2, "unset_var"));
5019
5020 /* It is useles to retrieve the stream, but this function
5021 * runs only in a stream context.
5022 */
5023 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5024 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5025
5026 /* Unset the variable. */
5027 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
5028 vars_unset_by_name(name, len, &smp);
5029 return 0;
5030}
5031
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005032__LJMP static int hlua_get_var(lua_State *L)
5033{
5034 struct hlua_txn *htxn;
5035 const char *name;
5036 size_t len;
5037 struct sample smp;
5038
5039 MAY_LJMP(check_args(L, 2, "get_var"));
5040
5041 /* It is useles to retrieve the stream, but this function
5042 * runs only in a stream context.
5043 */
5044 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5045 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5046
Willy Tarreau7560dd42016-03-10 16:28:58 +01005047 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005048 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005049 lua_pushnil(L);
5050 return 1;
5051 }
5052
5053 return hlua_smp2lua(L, &smp);
5054}
5055
Willy Tarreau59551662015-03-10 14:23:13 +01005056__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005057{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005058 struct hlua *hlua;
5059
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005060 MAY_LJMP(check_args(L, 2, "set_priv"));
5061
Willy Tarreau87b09662015-04-03 00:22:06 +02005062 /* It is useles to retrieve the stream, but this function
5063 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005064 */
5065 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005066 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005067
5068 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005069 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005070
5071 /* Get and store new value. */
5072 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5073 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5074
5075 return 0;
5076}
5077
Willy Tarreau59551662015-03-10 14:23:13 +01005078__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005079{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005080 struct hlua *hlua;
5081
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005082 MAY_LJMP(check_args(L, 1, "get_priv"));
5083
Willy Tarreau87b09662015-04-03 00:22:06 +02005084 /* It is useles to retrieve the stream, but this function
5085 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005086 */
5087 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005088 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005089
5090 /* Push configuration index in the stack. */
5091 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5092
5093 return 1;
5094}
5095
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005096/* Create stack entry containing a class TXN. This function
5097 * return 0 if the stack does not contains free slots,
5098 * otherwise it returns 1.
5099 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005100static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005101{
Willy Tarreaude491382015-04-06 11:04:28 +02005102 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005103
5104 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005105 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005106 return 0;
5107
5108 /* NOTE: The allocation never fails. The failure
5109 * throw an error, and the function never returns.
5110 * if the throw is not avalaible, the process is aborted.
5111 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005112 /* Create the object: obj[0] = userdata. */
5113 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005114 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005115 lua_rawseti(L, -2, 0);
5116
Willy Tarreaude491382015-04-06 11:04:28 +02005117 htxn->s = s;
5118 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005119 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005120 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005121
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005122 /* Create the "f" field that contains a list of fetches. */
5123 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005124 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005125 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005126 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005127
5128 /* Create the "sf" field that contains a list of stringsafe fetches. */
5129 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005130 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005131 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005132 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005133
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005134 /* Create the "c" field that contains a list of converters. */
5135 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005136 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005137 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005138 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005139
5140 /* Create the "sc" field that contains a list of stringsafe converters. */
5141 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005142 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005143 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005144 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005145
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005146 /* Create the "req" field that contains the request channel object. */
5147 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005148 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005149 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005150 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005151
5152 /* Create the "res" field that contains the response channel object. */
5153 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005154 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005155 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005156 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005157
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005158 /* Creates the HTTP object is the current proxy allows http. */
5159 lua_pushstring(L, "http");
5160 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005161 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005162 return 0;
5163 }
5164 else
5165 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005166 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005167
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005168 /* Pop a class sesison metatable and affect it to the userdata. */
5169 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5170 lua_setmetatable(L, -2);
5171
5172 return 1;
5173}
5174
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005175__LJMP static int hlua_txn_deflog(lua_State *L)
5176{
5177 const char *msg;
5178 struct hlua_txn *htxn;
5179
5180 MAY_LJMP(check_args(L, 2, "deflog"));
5181 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5182 msg = MAY_LJMP(luaL_checkstring(L, 2));
5183
5184 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5185 return 0;
5186}
5187
5188__LJMP static int hlua_txn_log(lua_State *L)
5189{
5190 int level;
5191 const char *msg;
5192 struct hlua_txn *htxn;
5193
5194 MAY_LJMP(check_args(L, 3, "log"));
5195 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5196 level = MAY_LJMP(luaL_checkinteger(L, 2));
5197 msg = MAY_LJMP(luaL_checkstring(L, 3));
5198
5199 if (level < 0 || level >= NB_LOG_LEVELS)
5200 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5201
5202 hlua_sendlog(htxn->s->be, level, msg);
5203 return 0;
5204}
5205
5206__LJMP static int hlua_txn_log_debug(lua_State *L)
5207{
5208 const char *msg;
5209 struct hlua_txn *htxn;
5210
5211 MAY_LJMP(check_args(L, 2, "Debug"));
5212 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5213 msg = MAY_LJMP(luaL_checkstring(L, 2));
5214 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5215 return 0;
5216}
5217
5218__LJMP static int hlua_txn_log_info(lua_State *L)
5219{
5220 const char *msg;
5221 struct hlua_txn *htxn;
5222
5223 MAY_LJMP(check_args(L, 2, "Info"));
5224 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5225 msg = MAY_LJMP(luaL_checkstring(L, 2));
5226 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5227 return 0;
5228}
5229
5230__LJMP static int hlua_txn_log_warning(lua_State *L)
5231{
5232 const char *msg;
5233 struct hlua_txn *htxn;
5234
5235 MAY_LJMP(check_args(L, 2, "Warning"));
5236 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5237 msg = MAY_LJMP(luaL_checkstring(L, 2));
5238 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5239 return 0;
5240}
5241
5242__LJMP static int hlua_txn_log_alert(lua_State *L)
5243{
5244 const char *msg;
5245 struct hlua_txn *htxn;
5246
5247 MAY_LJMP(check_args(L, 2, "Alert"));
5248 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5249 msg = MAY_LJMP(luaL_checkstring(L, 2));
5250 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5251 return 0;
5252}
5253
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005254__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5255{
5256 struct hlua_txn *htxn;
5257 int ll;
5258
5259 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5260 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5261 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5262
5263 if (ll < 0 || ll > 7)
5264 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5265
5266 htxn->s->logs.level = ll;
5267 return 0;
5268}
5269
5270__LJMP static int hlua_txn_set_tos(lua_State *L)
5271{
5272 struct hlua_txn *htxn;
5273 struct connection *cli_conn;
5274 int tos;
5275
5276 MAY_LJMP(check_args(L, 2, "set_tos"));
5277 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5278 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5279
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005280 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005281 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005282
5283 return 0;
5284}
5285
5286__LJMP static int hlua_txn_set_mark(lua_State *L)
5287{
5288#ifdef SO_MARK
5289 struct hlua_txn *htxn;
5290 struct connection *cli_conn;
5291 int mark;
5292
5293 MAY_LJMP(check_args(L, 2, "set_mark"));
5294 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5295 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5296
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005297 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005298 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005299#endif
5300 return 0;
5301}
5302
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005303/* This function is an Lua binding that send pending data
5304 * to the client, and close the stream interface.
5305 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005306__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005307{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005308 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005309 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01005310 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005311
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005312 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005313 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005314 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005315
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005316 /* If the flags NOTERM is set, we cannot terminate the http
5317 * session, so we just end the execution of the current
5318 * lua code.
5319 */
5320 if (htxn->flags & HLUA_TXN_NOTERM) {
5321 WILL_LJMP(hlua_done(L));
5322 return 0;
5323 }
5324
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005325 ic = &htxn->s->req;
5326 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005327
Willy Tarreau630ef452015-08-28 10:06:15 +02005328 if (htxn->s->txn) {
5329 /* HTTP mode, let's stay in sync with the stream */
5330 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
5331 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
5332 htxn->s->txn->req.sov = 0;
5333 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
5334 oc->analysers = AN_RES_HTTP_XFER_BODY;
5335 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
5336 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
5337
Willy Tarreau630ef452015-08-28 10:06:15 +02005338 /* Note that if we want to support keep-alive, we need
5339 * to bypass the close/shutr_now calls below, but that
5340 * may only be done if the HTTP request was already
5341 * processed and the connection header is known (ie
5342 * not during TCP rules).
5343 */
5344 }
5345
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005346 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01005347 channel_abort(ic);
5348 channel_auto_close(ic);
5349 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005350
5351 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01005352 channel_auto_read(oc);
5353 channel_auto_close(oc);
5354 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005355
Willy Tarreau0458b082015-08-28 09:40:04 +02005356 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005357
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005358 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005359 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005360 return 0;
5361}
5362
5363__LJMP static int hlua_log(lua_State *L)
5364{
5365 int level;
5366 const char *msg;
5367
5368 MAY_LJMP(check_args(L, 2, "log"));
5369 level = MAY_LJMP(luaL_checkinteger(L, 1));
5370 msg = MAY_LJMP(luaL_checkstring(L, 2));
5371
5372 if (level < 0 || level >= NB_LOG_LEVELS)
5373 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5374
5375 hlua_sendlog(NULL, level, msg);
5376 return 0;
5377}
5378
5379__LJMP static int hlua_log_debug(lua_State *L)
5380{
5381 const char *msg;
5382
5383 MAY_LJMP(check_args(L, 1, "debug"));
5384 msg = MAY_LJMP(luaL_checkstring(L, 1));
5385 hlua_sendlog(NULL, LOG_DEBUG, msg);
5386 return 0;
5387}
5388
5389__LJMP static int hlua_log_info(lua_State *L)
5390{
5391 const char *msg;
5392
5393 MAY_LJMP(check_args(L, 1, "info"));
5394 msg = MAY_LJMP(luaL_checkstring(L, 1));
5395 hlua_sendlog(NULL, LOG_INFO, msg);
5396 return 0;
5397}
5398
5399__LJMP static int hlua_log_warning(lua_State *L)
5400{
5401 const char *msg;
5402
5403 MAY_LJMP(check_args(L, 1, "warning"));
5404 msg = MAY_LJMP(luaL_checkstring(L, 1));
5405 hlua_sendlog(NULL, LOG_WARNING, msg);
5406 return 0;
5407}
5408
5409__LJMP static int hlua_log_alert(lua_State *L)
5410{
5411 const char *msg;
5412
5413 MAY_LJMP(check_args(L, 1, "alert"));
5414 msg = MAY_LJMP(luaL_checkstring(L, 1));
5415 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005416 return 0;
5417}
5418
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005419__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005420{
5421 int wakeup_ms = lua_tointeger(L, -1);
5422 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005423 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005424 return 0;
5425}
5426
5427__LJMP static int hlua_sleep(lua_State *L)
5428{
5429 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005430 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005431
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005432 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005433
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005434 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005435 wakeup_ms = tick_add(now_ms, delay);
5436 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005437
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005438 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5439 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005440}
5441
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005442__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005443{
5444 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005445 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005446
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005447 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005448
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005449 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005450 wakeup_ms = tick_add(now_ms, delay);
5451 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005452
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005453 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5454 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005455}
5456
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005457/* This functionis an LUA binding. it permits to give back
5458 * the hand at the HAProxy scheduler. It is used when the
5459 * LUA processing consumes a lot of time.
5460 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005461__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005462{
5463 return 0;
5464}
5465
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005466__LJMP static int hlua_yield(lua_State *L)
5467{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005468 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
5469 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005470}
5471
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005472/* This function change the nice of the currently executed
5473 * task. It is used set low or high priority at the current
5474 * task.
5475 */
Willy Tarreau59551662015-03-10 14:23:13 +01005476__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005477{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005478 struct hlua *hlua;
5479 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005480
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005481 MAY_LJMP(check_args(L, 1, "set_nice"));
5482 hlua = hlua_gethlua(L);
5483 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005484
5485 /* If he task is not set, I'm in a start mode. */
5486 if (!hlua || !hlua->task)
5487 return 0;
5488
5489 if (nice < -1024)
5490 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005491 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005492 nice = 1024;
5493
5494 hlua->task->nice = nice;
5495 return 0;
5496}
5497
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005498/* This function is used as a calback of a task. It is called by the
5499 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5500 * return an E_AGAIN signal, the emmiter of this signal must set a
5501 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005502 *
5503 * Task wrapper are longjmp safe because the only one Lua code
5504 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005505 */
5506static struct task *hlua_process_task(struct task *task)
5507{
5508 struct hlua *hlua = task->context;
5509 enum hlua_exec status;
5510
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005511 /* If it is the first call to the task, we must initialize the
5512 * execution timeouts.
5513 */
5514 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005515 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005516
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005517 /* Execute the Lua code. */
5518 status = hlua_ctx_resume(hlua, 1);
5519
5520 switch (status) {
5521 /* finished or yield */
5522 case HLUA_E_OK:
5523 hlua_ctx_destroy(hlua);
5524 task_delete(task);
5525 task_free(task);
5526 break;
5527
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005528 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01005529 notification_gc(&hlua->com);
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005530 if (hlua->wake_time != TICK_ETERNITY)
Emeric Brun253e53e2017-10-17 18:58:40 +02005531 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005532 break;
5533
5534 /* finished with error. */
5535 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005536 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005537 hlua_ctx_destroy(hlua);
5538 task_delete(task);
5539 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02005540 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005541 break;
5542
5543 case HLUA_E_ERR:
5544 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005545 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005546 hlua_ctx_destroy(hlua);
5547 task_delete(task);
5548 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02005549 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005550 break;
5551 }
Emeric Brun253e53e2017-10-17 18:58:40 +02005552 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005553}
5554
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005555/* This function is an LUA binding that register LUA function to be
5556 * executed after the HAProxy configuration parsing and before the
5557 * HAProxy scheduler starts. This function expect only one LUA
5558 * argument that is a function. This function returns nothing, but
5559 * throws if an error is encountered.
5560 */
5561__LJMP static int hlua_register_init(lua_State *L)
5562{
5563 struct hlua_init_function *init;
5564 int ref;
5565
5566 MAY_LJMP(check_args(L, 1, "register_init"));
5567
5568 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5569
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005570 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005571 if (!init)
5572 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5573
5574 init->function_ref = ref;
5575 LIST_ADDQ(&hlua_init_functions, &init->l);
5576 return 0;
5577}
5578
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005579/* This functio is an LUA binding. It permits to register a task
5580 * executed in parallel of the main HAroxy activity. The task is
5581 * created and it is set in the HAProxy scheduler. It can be called
5582 * from the "init" section, "post init" or during the runtime.
5583 *
5584 * Lua prototype:
5585 *
5586 * <none> core.register_task(<function>)
5587 */
5588static int hlua_register_task(lua_State *L)
5589{
5590 struct hlua *hlua;
5591 struct task *task;
5592 int ref;
5593
5594 MAY_LJMP(check_args(L, 1, "register_task"));
5595
5596 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5597
Willy Tarreaubafbe012017-11-24 17:34:44 +01005598 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005599 if (!hlua)
5600 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5601
Emeric Brunc60def82017-09-27 14:59:38 +02005602 task = task_new(MAX_THREADS_MASK);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005603 task->context = hlua;
5604 task->process = hlua_process_task;
5605
5606 if (!hlua_ctx_init(hlua, task))
5607 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5608
5609 /* Restore the function in the stack. */
5610 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5611 hlua->nargs = 0;
5612
5613 /* Schedule task. */
5614 task_schedule(task, now_ms);
5615
5616 return 0;
5617}
5618
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005619/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5620 * doesn't allow "yield" functions because the HAProxy engine cannot
5621 * resume converters.
5622 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005623static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005624{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005625 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005626 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005627 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005628
Willy Tarreaube508f12016-03-10 11:47:01 +01005629 if (!stream)
5630 return 0;
5631
Willy Tarreau87b09662015-04-03 00:22:06 +02005632 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005633 * Lua context can be not initialized. This behavior
5634 * permits to save performances because a systematic
5635 * Lua initialization cause 5% performances loss.
5636 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005637 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005638 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005639 if (!stream->hlua) {
5640 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5641 return 0;
5642 }
5643 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5644 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5645 return 0;
5646 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005647 }
5648
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005649 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005650 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005651
5652 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005653 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5654 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5655 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005656 else
5657 error = "critical error";
5658 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005659 return 0;
5660 }
5661
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005662 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005663 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005664 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005665 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005666 return 0;
5667 }
5668
5669 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005670 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005671
5672 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005673 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005674 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005675 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005676 return 0;
5677 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005678 hlua_smp2lua(stream->hlua->T, smp);
5679 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005680
5681 /* push keywords in the stack. */
5682 if (arg_p) {
5683 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005684 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005685 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005686 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005687 return 0;
5688 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005689 hlua_arg2lua(stream->hlua->T, arg_p);
5690 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005691 }
5692 }
5693
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005694 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005695 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005696
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005697 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005698 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005699 }
5700
5701 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005702 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005703 /* finished. */
5704 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005705 /* If the stack is empty, the function fails. */
5706 if (lua_gettop(stream->hlua->T) <= 0)
5707 return 0;
5708
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005709 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005710 hlua_lua2smp(stream->hlua->T, -1, smp);
5711 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005712 return 1;
5713
5714 /* yield. */
5715 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005716 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005717 return 0;
5718
5719 /* finished with error. */
5720 case HLUA_E_ERRMSG:
5721 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005722 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005723 fcn->name, lua_tostring(stream->hlua->T, -1));
5724 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005725 return 0;
5726
5727 case HLUA_E_ERR:
5728 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005729 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005730
5731 default:
5732 return 0;
5733 }
5734}
5735
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005736/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5737 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005738 * resume sample-fetches. This function will be called by the sample
5739 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005740 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005741static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5742 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005743{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005744 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005745 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005746 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005747 const struct chunk msg = { .len = 0 };
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005748
Willy Tarreaube508f12016-03-10 11:47:01 +01005749 if (!stream)
5750 return 0;
5751
Willy Tarreau87b09662015-04-03 00:22:06 +02005752 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005753 * Lua context can be not initialized. This behavior
5754 * permits to save performances because a systematic
5755 * Lua initialization cause 5% performances loss.
5756 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005757 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005758 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005759 if (!stream->hlua) {
5760 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5761 return 0;
5762 }
5763 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5764 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5765 return 0;
5766 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005767 }
5768
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005769 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005770
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005771 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005772 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005773
5774 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005775 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5776 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5777 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005778 else
5779 error = "critical error";
5780 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005781 return 0;
5782 }
5783
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005784 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005785 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005786 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005787 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005788 return 0;
5789 }
5790
5791 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005792 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005793
5794 /* push arguments in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005795 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR,
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005796 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005797 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005798 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005799 return 0;
5800 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005801 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005802
5803 /* push keywords in the stack. */
5804 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5805 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005806 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005807 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005808 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005809 return 0;
5810 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005811 hlua_arg2lua(stream->hlua->T, arg_p);
5812 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005813 }
5814
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005815 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005816 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005817
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005818 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005819 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005820 }
5821
5822 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005823 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005824 /* finished. */
5825 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005826 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005827 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005828 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005829 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005830 /* If the stack is empty, the function fails. */
5831 if (lua_gettop(stream->hlua->T) <= 0)
5832 return 0;
5833
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005834 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005835 hlua_lua2smp(stream->hlua->T, -1, smp);
5836 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005837
5838 /* Set the end of execution flag. */
5839 smp->flags &= ~SMP_F_MAY_CHANGE;
5840 return 1;
5841
5842 /* yield. */
5843 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005844 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005845 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005846 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005847 return 0;
5848
5849 /* finished with error. */
5850 case HLUA_E_ERRMSG:
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 FOURNIERfa0e5dd2015-02-16 20:19:18 +01005853 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005854 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005855 fcn->name, lua_tostring(stream->hlua->T, -1));
5856 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005857 return 0;
5858
5859 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005860 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005861 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005862 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005863 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005864
5865 default:
5866 return 0;
5867 }
5868}
5869
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005870/* This function is an LUA binding used for registering
5871 * "sample-conv" functions. It expects a converter name used
5872 * in the haproxy configuration file, and an LUA function.
5873 */
5874__LJMP static int hlua_register_converters(lua_State *L)
5875{
5876 struct sample_conv_kw_list *sck;
5877 const char *name;
5878 int ref;
5879 int len;
5880 struct hlua_function *fcn;
5881
5882 MAY_LJMP(check_args(L, 2, "register_converters"));
5883
5884 /* First argument : converter name. */
5885 name = MAY_LJMP(luaL_checkstring(L, 1));
5886
5887 /* Second argument : lua function. */
5888 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5889
5890 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005891 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005892 if (!sck)
5893 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005894 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005895 if (!fcn)
5896 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5897
5898 /* Fill fcn. */
5899 fcn->name = strdup(name);
5900 if (!fcn->name)
5901 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5902 fcn->function_ref = ref;
5903
5904 /* List head */
5905 sck->list.n = sck->list.p = NULL;
5906
5907 /* converter keyword. */
5908 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005909 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005910 if (!sck->kw[0].kw)
5911 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5912
5913 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5914 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005915 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 +01005916 sck->kw[0].val_args = NULL;
5917 sck->kw[0].in_type = SMP_T_STR;
5918 sck->kw[0].out_type = SMP_T_STR;
5919 sck->kw[0].private = fcn;
5920
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005921 /* Register this new converter */
5922 sample_register_convs(sck);
5923
5924 return 0;
5925}
5926
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005927/* This fucntion is an LUA binding used for registering
5928 * "sample-fetch" functions. It expects a converter name used
5929 * in the haproxy configuration file, and an LUA function.
5930 */
5931__LJMP static int hlua_register_fetches(lua_State *L)
5932{
5933 const char *name;
5934 int ref;
5935 int len;
5936 struct sample_fetch_kw_list *sfk;
5937 struct hlua_function *fcn;
5938
5939 MAY_LJMP(check_args(L, 2, "register_fetches"));
5940
5941 /* First argument : sample-fetch name. */
5942 name = MAY_LJMP(luaL_checkstring(L, 1));
5943
5944 /* Second argument : lua function. */
5945 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5946
5947 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005948 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005949 if (!sfk)
5950 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005951 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005952 if (!fcn)
5953 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5954
5955 /* Fill fcn. */
5956 fcn->name = strdup(name);
5957 if (!fcn->name)
5958 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5959 fcn->function_ref = ref;
5960
5961 /* List head */
5962 sfk->list.n = sfk->list.p = NULL;
5963
5964 /* sample-fetch keyword. */
5965 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005966 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005967 if (!sfk->kw[0].kw)
5968 return luaL_error(L, "lua out of memory error.");
5969
5970 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
5971 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005972 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 +01005973 sfk->kw[0].val_args = NULL;
5974 sfk->kw[0].out_type = SMP_T_STR;
5975 sfk->kw[0].use = SMP_USE_HTTP_ANY;
5976 sfk->kw[0].val = 0;
5977 sfk->kw[0].private = fcn;
5978
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005979 /* Register this new fetch. */
5980 sample_register_fetches(sfk);
5981
5982 return 0;
5983}
5984
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005985/* This function is a wrapper to execute each LUA function declared
5986 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005987 * return ACT_RET_CONT if the processing is finished (with or without
5988 * error) and return ACT_RET_YIELD if the function must be called again
5989 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005990 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005991static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02005992 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005993{
5994 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005995 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005996 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005997 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005998 const struct chunk msg = { .len = 0 };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005999
6000 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01006001 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
6002 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
6003 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
6004 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006005 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006006 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006007 return ACT_RET_CONT;
6008 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006009
Willy Tarreau87b09662015-04-03 00:22:06 +02006010 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006011 * Lua context can be not initialized. This behavior
6012 * permits to save performances because a systematic
6013 * Lua initialization cause 5% performances loss.
6014 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006015 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006016 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006017 if (!s->hlua) {
6018 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6019 rule->arg.hlua_rule->fcn.name);
6020 return ACT_RET_CONT;
6021 }
6022 if (!hlua_ctx_init(s->hlua, s->task)) {
6023 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6024 rule->arg.hlua_rule->fcn.name);
6025 return ACT_RET_CONT;
6026 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006027 }
6028
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006029 consistency_set(s, dir, &s->hlua->cons);
6030
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006031 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006032 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006033
6034 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006035 if (!SET_SAFE_LJMP(s->hlua->T)) {
6036 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6037 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006038 else
6039 error = "critical error";
6040 SEND_ERR(px, "Lua function '%s': %s.\n",
6041 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006042 return ACT_RET_CONT;
6043 }
6044
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006045 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006046 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006047 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006048 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006049 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006050 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006051 }
6052
6053 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006054 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006055
Willy Tarreau87b09662015-04-03 00:22:06 +02006056 /* Create and and push object stream in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006057 if (!hlua_txn_new(s->hlua->T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006058 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006059 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006060 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006061 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006062 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006063 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006064
6065 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006066 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006067 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006068 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006069 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006070 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006071 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006072 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006073 lua_pushstring(s->hlua->T, *arg);
6074 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006075 }
6076
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006077 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006078 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006079
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006080 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006081 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006082 }
6083
6084 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006085 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006086 /* finished. */
6087 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006088 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006089 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006090 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006091 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006092 if (s->hlua->flags & HLUA_STOP)
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006093 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006094 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006095
6096 /* yield. */
6097 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006098 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006099 if (s->hlua->wake_time != TICK_ETERNITY) {
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006100 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006101 s->req.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006102 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006103 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006104 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006105 /* Some actions can be wake up when a "write" event
6106 * is detected on a response channel. This is useful
6107 * only for actions targetted on the requests.
6108 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006109 if (HLUA_IS_WAKERESWR(s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006110 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01006111 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006112 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006113 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006114 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006115 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006116 /* We can quit the fcuntion without consistency check
6117 * because HAProxy is not able to manipulate data, it
6118 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006119 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006120
6121 /* finished with error. */
6122 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006123 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006124 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006125 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006126 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006127 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006128 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006129 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6130 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006131 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006132
6133 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006134 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006135 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006136 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006137 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006138 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006139 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006140 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006141
6142 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006143 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006144 }
6145}
6146
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006147struct task *hlua_applet_wakeup(struct task *t)
6148{
6149 struct appctx *ctx = t->context;
6150 struct stream_interface *si = ctx->owner;
6151
6152 /* If the applet is wake up without any expected work, the sheduler
6153 * remove it from the run queue. This flag indicate that the applet
6154 * is waiting for write. If the buffer is full, the main processing
6155 * will send some data and after call the applet, otherwise it call
6156 * the applet ASAP.
6157 */
6158 si_applet_cant_put(si);
6159 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006160 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006161 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006162}
6163
6164static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6165{
6166 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006167 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006168 struct task *task;
6169 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006170 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006171
Willy Tarreaubafbe012017-11-24 17:34:44 +01006172 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006173 if (!hlua) {
6174 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6175 ctx->rule->arg.hlua_rule->fcn.name);
6176 return 0;
6177 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006178 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006179 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006180 ctx->ctx.hlua_apptcp.flags = 0;
6181
6182 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006183 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006184 if (!task) {
6185 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6186 ctx->rule->arg.hlua_rule->fcn.name);
6187 return 0;
6188 }
6189 task->nice = 0;
6190 task->context = ctx;
6191 task->process = hlua_applet_wakeup;
6192 ctx->ctx.hlua_apptcp.task = task;
6193
6194 /* In the execution wrappers linked with a stream, the
6195 * Lua context can be not initialized. This behavior
6196 * permits to save performances because a systematic
6197 * Lua initialization cause 5% performances loss.
6198 */
6199 if (!hlua_ctx_init(hlua, task)) {
6200 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6201 ctx->rule->arg.hlua_rule->fcn.name);
6202 return 0;
6203 }
6204
6205 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006206 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006207
6208 /* The following Lua calls can fail. */
6209 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006210 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6211 error = lua_tostring(hlua->T, -1);
6212 else
6213 error = "critical error";
6214 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6215 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006216 RESET_SAFE_LJMP(hlua->T);
6217 return 0;
6218 }
6219
6220 /* Check stack available size. */
6221 if (!lua_checkstack(hlua->T, 1)) {
6222 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6223 ctx->rule->arg.hlua_rule->fcn.name);
6224 RESET_SAFE_LJMP(hlua->T);
6225 return 0;
6226 }
6227
6228 /* Restore the function in the stack. */
6229 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6230
6231 /* Create and and push object stream in the stack. */
6232 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
6233 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6234 ctx->rule->arg.hlua_rule->fcn.name);
6235 RESET_SAFE_LJMP(hlua->T);
6236 return 0;
6237 }
6238 hlua->nargs = 1;
6239
6240 /* push keywords in the stack. */
6241 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6242 if (!lua_checkstack(hlua->T, 1)) {
6243 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6244 ctx->rule->arg.hlua_rule->fcn.name);
6245 RESET_SAFE_LJMP(hlua->T);
6246 return 0;
6247 }
6248 lua_pushstring(hlua->T, *arg);
6249 hlua->nargs++;
6250 }
6251
6252 RESET_SAFE_LJMP(hlua->T);
6253
6254 /* Wakeup the applet ASAP. */
6255 si_applet_cant_get(si);
6256 si_applet_cant_put(si);
6257
6258 return 1;
6259}
6260
6261static void hlua_applet_tcp_fct(struct appctx *ctx)
6262{
6263 struct stream_interface *si = ctx->owner;
6264 struct stream *strm = si_strm(si);
6265 struct channel *res = si_ic(si);
6266 struct act_rule *rule = ctx->rule;
6267 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006268 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006269
6270 /* The applet execution is already done. */
6271 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
6272 return;
6273
6274 /* If the stream is disconnect or closed, ldo nothing. */
6275 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6276 return;
6277
6278 /* Execute the function. */
6279 switch (hlua_ctx_resume(hlua, 1)) {
6280 /* finished. */
6281 case HLUA_E_OK:
6282 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6283
6284 /* log time */
6285 strm->logs.tv_request = now;
6286
6287 /* eat the whole request */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006288 co_skip(si_oc(si), si_ob(si)->o);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006289 res->flags |= CF_READ_NULL;
6290 si_shutr(si);
6291 return;
6292
6293 /* yield. */
6294 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006295 if (hlua->wake_time != TICK_ETERNITY)
6296 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006297 return;
6298
6299 /* finished with error. */
6300 case HLUA_E_ERRMSG:
6301 /* Display log. */
6302 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6303 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6304 lua_pop(hlua->T, 1);
6305 goto error;
6306
6307 case HLUA_E_ERR:
6308 /* Display log. */
6309 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6310 rule->arg.hlua_rule->fcn.name);
6311 goto error;
6312
6313 default:
6314 goto error;
6315 }
6316
6317error:
6318
6319 /* For all other cases, just close the stream. */
6320 si_shutw(si);
6321 si_shutr(si);
6322 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6323}
6324
6325static void hlua_applet_tcp_release(struct appctx *ctx)
6326{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006327 task_delete(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006328 task_free(ctx->ctx.hlua_apptcp.task);
6329 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006330 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006331 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006332}
6333
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006334/* The function returns 1 if the initialisation is complete, 0 if
6335 * an errors occurs and -1 if more data are required for initializing
6336 * the applet.
6337 */
6338static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6339{
6340 struct stream_interface *si = ctx->owner;
6341 struct channel *req = si_oc(si);
6342 struct http_msg *msg;
6343 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006344 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006345 char **arg;
6346 struct hdr_ctx hdr;
6347 struct task *task;
6348 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01006349 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006350
6351 /* Wait for a full HTTP request. */
6352 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
6353 if (smp.flags & SMP_F_MAY_CHANGE)
6354 return -1;
6355 return 0;
6356 }
6357 txn = strm->txn;
6358 msg = &txn->req;
6359
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006360 /* We want two things in HTTP mode :
6361 * - enforce server-close mode if we were in keep-alive, so that the
6362 * applet is released after each response ;
6363 * - enable request body transfer to the applet in order to resync
6364 * with the response body.
6365 */
6366 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
6367 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006368
Willy Tarreaubafbe012017-11-24 17:34:44 +01006369 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006370 if (!hlua) {
6371 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6372 ctx->rule->arg.hlua_rule->fcn.name);
6373 return 0;
6374 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006375 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006376 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006377 ctx->ctx.hlua_apphttp.left_bytes = -1;
6378 ctx->ctx.hlua_apphttp.flags = 0;
6379
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006380 if (txn->req.flags & HTTP_MSGF_VER_11)
6381 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6382
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006383 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006384 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006385 if (!task) {
6386 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6387 ctx->rule->arg.hlua_rule->fcn.name);
6388 return 0;
6389 }
6390 task->nice = 0;
6391 task->context = ctx;
6392 task->process = hlua_applet_wakeup;
6393 ctx->ctx.hlua_apphttp.task = task;
6394
6395 /* In the execution wrappers linked with a stream, the
6396 * Lua context can be not initialized. This behavior
6397 * permits to save performances because a systematic
6398 * Lua initialization cause 5% performances loss.
6399 */
6400 if (!hlua_ctx_init(hlua, task)) {
6401 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6402 ctx->rule->arg.hlua_rule->fcn.name);
6403 return 0;
6404 }
6405
6406 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006407 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006408
6409 /* The following Lua calls can fail. */
6410 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006411 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6412 error = lua_tostring(hlua->T, -1);
6413 else
6414 error = "critical error";
6415 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6416 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006417 return 0;
6418 }
6419
6420 /* Check stack available size. */
6421 if (!lua_checkstack(hlua->T, 1)) {
6422 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6423 ctx->rule->arg.hlua_rule->fcn.name);
6424 RESET_SAFE_LJMP(hlua->T);
6425 return 0;
6426 }
6427
6428 /* Restore the function in the stack. */
6429 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6430
6431 /* Create and and push object stream in the stack. */
6432 if (!hlua_applet_http_new(hlua->T, ctx)) {
6433 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6434 ctx->rule->arg.hlua_rule->fcn.name);
6435 RESET_SAFE_LJMP(hlua->T);
6436 return 0;
6437 }
6438 hlua->nargs = 1;
6439
6440 /* Look for a 100-continue expected. */
6441 if (msg->flags & HTTP_MSGF_VER_11) {
6442 hdr.idx = 0;
6443 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
6444 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
6445 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
6446 }
6447
6448 /* push keywords in the stack. */
6449 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6450 if (!lua_checkstack(hlua->T, 1)) {
6451 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6452 ctx->rule->arg.hlua_rule->fcn.name);
6453 RESET_SAFE_LJMP(hlua->T);
6454 return 0;
6455 }
6456 lua_pushstring(hlua->T, *arg);
6457 hlua->nargs++;
6458 }
6459
6460 RESET_SAFE_LJMP(hlua->T);
6461
6462 /* Wakeup the applet when data is ready for read. */
6463 si_applet_cant_get(si);
6464
6465 return 1;
6466}
6467
6468static void hlua_applet_http_fct(struct appctx *ctx)
6469{
6470 struct stream_interface *si = ctx->owner;
6471 struct stream *strm = si_strm(si);
6472 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006473 struct act_rule *rule = ctx->rule;
6474 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006475 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006476 char *blk1;
6477 int len1;
6478 char *blk2;
6479 int len2;
6480 int ret;
6481
6482 /* If the stream is disconnect or closed, ldo nothing. */
6483 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6484 return;
6485
6486 /* Set the currently running flag. */
6487 if (!HLUA_IS_RUNNING(hlua) &&
6488 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6489
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006490 /* Wait for full HTTP analysys. */
6491 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6492 si_applet_cant_get(si);
6493 return;
6494 }
6495
6496 /* Store the max amount of bytes that we can read. */
6497 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6498
6499 /* We need to flush the request header. This left the body
6500 * for the Lua.
6501 */
6502
6503 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006504 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006505 if (ret == -1)
6506 return;
6507
6508 /* No data available, ask for more data. */
6509 if (ret == 1)
6510 len2 = 0;
6511 if (ret == 0)
6512 len1 = 0;
6513 if (len1 + len2 < strm->txn->req.eoh + 2) {
6514 si_applet_cant_get(si);
6515 return;
6516 }
6517
6518 /* skip the requests bytes. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006519 co_skip(si_oc(si), strm->txn->req.eoh + 2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006520 }
6521
6522 /* Executes The applet if it is not done. */
6523 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6524
6525 /* Execute the function. */
6526 switch (hlua_ctx_resume(hlua, 1)) {
6527 /* finished. */
6528 case HLUA_E_OK:
6529 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6530 break;
6531
6532 /* yield. */
6533 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006534 if (hlua->wake_time != TICK_ETERNITY)
6535 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006536 return;
6537
6538 /* finished with error. */
6539 case HLUA_E_ERRMSG:
6540 /* Display log. */
6541 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6542 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6543 lua_pop(hlua->T, 1);
6544 goto error;
6545
6546 case HLUA_E_ERR:
6547 /* Display log. */
6548 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6549 rule->arg.hlua_rule->fcn.name);
6550 goto error;
6551
6552 default:
6553 goto error;
6554 }
6555 }
6556
6557 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6558
6559 /* We must send the final chunk. */
6560 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6561 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6562
6563 /* sent last chunk at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006564 ret = ci_putblk(res, "0\r\n\r\n", 5);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006565
6566 /* critical error. */
6567 if (ret == -2 || ret == -3) {
6568 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6569 rule->arg.hlua_rule->fcn.name);
6570 goto error;
6571 }
6572
6573 /* no enough space error. */
6574 if (ret == -1) {
6575 si_applet_cant_put(si);
6576 return;
6577 }
6578
6579 /* set the last chunk sent. */
6580 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6581 }
6582
6583 /* close the connection. */
6584
6585 /* status / log */
6586 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6587 strm->logs.tv_request = now;
6588
6589 /* eat the whole request */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006590 co_skip(si_oc(si), si_ob(si)->o);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006591 res->flags |= CF_READ_NULL;
6592 si_shutr(si);
6593
6594 return;
6595 }
6596
6597error:
6598
6599 /* If we are in HTTP mode, and we are not send any
6600 * data, return a 500 server error in best effort:
6601 * if there are no room avalaible in the buffer,
6602 * just close the connection.
6603 */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006604 ci_putblk(res, error_500, strlen(error_500));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006605 if (!(strm->flags & SF_ERR_MASK))
6606 strm->flags |= SF_ERR_RESOURCE;
6607 si_shutw(si);
6608 si_shutr(si);
6609 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6610}
6611
6612static void hlua_applet_http_release(struct appctx *ctx)
6613{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006614 task_delete(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006615 task_free(ctx->ctx.hlua_apphttp.task);
6616 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006617 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006618 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006619}
6620
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006621/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6622 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006623 *
6624 * This function can fail with an abort() due to an Lua critical error.
6625 * We are in the configuration parsing process of HAProxy, this abort() is
6626 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006627 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006628static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6629 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006630{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006631 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006632 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006633
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006634 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006635 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006636 if (!rule->arg.hlua_rule) {
6637 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006638 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006639 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006640
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006641 /* Memory for arguments. */
6642 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
6643 if (!rule->arg.hlua_rule->args) {
6644 memprintf(err, "out of memory error");
6645 return ACT_RET_PRS_ERR;
6646 }
6647
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006648 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006649 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006650
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006651 /* Expect some arguments */
6652 for (i = 0; i < fcn->nargs; i++) {
6653 if (*args[i+1] == '\0') {
6654 memprintf(err, "expect %d arguments", fcn->nargs);
6655 return ACT_RET_PRS_ERR;
6656 }
6657 rule->arg.hlua_rule->args[i] = strdup(args[i + 1]);
6658 if (!rule->arg.hlua_rule->args[i]) {
6659 memprintf(err, "out of memory error");
6660 return ACT_RET_PRS_ERR;
6661 }
6662 (*cur_arg)++;
6663 }
6664 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006665
Thierry FOURNIER42148732015-09-02 17:17:33 +02006666 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006667 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006668 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006669}
6670
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006671static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6672 struct act_rule *rule, char **err)
6673{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006674 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006675
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006676 /* HTTP applets are forbidden in tcp-request rules.
6677 * HTTP applet request requires everything initilized by
6678 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6679 * The applet will be immediately initilized, but its before
6680 * the call of this analyzer.
6681 */
6682 if (rule->from != ACT_F_HTTP_REQ) {
6683 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6684 return ACT_RET_PRS_ERR;
6685 }
6686
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006687 /* Memory for the rule. */
6688 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6689 if (!rule->arg.hlua_rule) {
6690 memprintf(err, "out of memory error");
6691 return ACT_RET_PRS_ERR;
6692 }
6693
6694 /* Reference the Lua function and store the reference. */
6695 rule->arg.hlua_rule->fcn = *fcn;
6696
6697 /* TODO: later accept arguments. */
6698 rule->arg.hlua_rule->args = NULL;
6699
6700 /* Add applet pointer in the rule. */
6701 rule->applet.obj_type = OBJ_TYPE_APPLET;
6702 rule->applet.name = fcn->name;
6703 rule->applet.init = hlua_applet_http_init;
6704 rule->applet.fct = hlua_applet_http_fct;
6705 rule->applet.release = hlua_applet_http_release;
6706 rule->applet.timeout = hlua_timeout_applet;
6707
6708 return ACT_RET_PRS_OK;
6709}
6710
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006711/* This function is an LUA binding used for registering
6712 * "sample-conv" functions. It expects a converter name used
6713 * in the haproxy configuration file, and an LUA function.
6714 */
6715__LJMP static int hlua_register_action(lua_State *L)
6716{
6717 struct action_kw_list *akl;
6718 const char *name;
6719 int ref;
6720 int len;
6721 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006722 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006723
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006724 /* Initialise the number of expected arguments at 0. */
6725 nargs = 0;
6726
6727 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6728 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006729
6730 /* First argument : converter name. */
6731 name = MAY_LJMP(luaL_checkstring(L, 1));
6732
6733 /* Second argument : environment. */
6734 if (lua_type(L, 2) != LUA_TTABLE)
6735 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6736
6737 /* Third argument : lua function. */
6738 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6739
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006740 /* Fouth argument : number of mandatories arguments expected on the configuration line. */
6741 if (lua_gettop(L) >= 4)
6742 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
6743
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006744 /* browse the second argulent as an array. */
6745 lua_pushnil(L);
6746 while (lua_next(L, 2) != 0) {
6747 if (lua_type(L, -1) != LUA_TSTRING)
6748 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6749
6750 /* Check required environment. Only accepted "http" or "tcp". */
6751 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006752 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006753 if (!akl)
6754 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006755 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006756 if (!fcn)
6757 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6758
6759 /* Fill fcn. */
6760 fcn->name = strdup(name);
6761 if (!fcn->name)
6762 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6763 fcn->function_ref = ref;
6764
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006765 /* Set the expected number od arguments. */
6766 fcn->nargs = nargs;
6767
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006768 /* List head */
6769 akl->list.n = akl->list.p = NULL;
6770
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006771 /* action keyword. */
6772 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006773 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006774 if (!akl->kw[0].kw)
6775 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6776
6777 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6778
6779 akl->kw[0].match_pfx = 0;
6780 akl->kw[0].private = fcn;
6781 akl->kw[0].parse = action_register_lua;
6782
6783 /* select the action registering point. */
6784 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6785 tcp_req_cont_keywords_register(akl);
6786 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6787 tcp_res_cont_keywords_register(akl);
6788 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6789 http_req_keywords_register(akl);
6790 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6791 http_res_keywords_register(akl);
6792 else
6793 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
6794 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6795 "are expected.", lua_tostring(L, -1)));
6796
6797 /* pop the environment string. */
6798 lua_pop(L, 1);
6799 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006800 return ACT_RET_PRS_OK;
6801}
6802
6803static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6804 struct act_rule *rule, char **err)
6805{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006806 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006807
6808 /* Memory for the rule. */
6809 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6810 if (!rule->arg.hlua_rule) {
6811 memprintf(err, "out of memory error");
6812 return ACT_RET_PRS_ERR;
6813 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006814
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006815 /* Reference the Lua function and store the reference. */
6816 rule->arg.hlua_rule->fcn = *fcn;
6817
6818 /* TODO: later accept arguments. */
6819 rule->arg.hlua_rule->args = NULL;
6820
6821 /* Add applet pointer in the rule. */
6822 rule->applet.obj_type = OBJ_TYPE_APPLET;
6823 rule->applet.name = fcn->name;
6824 rule->applet.init = hlua_applet_tcp_init;
6825 rule->applet.fct = hlua_applet_tcp_fct;
6826 rule->applet.release = hlua_applet_tcp_release;
6827 rule->applet.timeout = hlua_timeout_applet;
6828
6829 return 0;
6830}
6831
6832/* This function is an LUA binding used for registering
6833 * "sample-conv" functions. It expects a converter name used
6834 * in the haproxy configuration file, and an LUA function.
6835 */
6836__LJMP static int hlua_register_service(lua_State *L)
6837{
6838 struct action_kw_list *akl;
6839 const char *name;
6840 const char *env;
6841 int ref;
6842 int len;
6843 struct hlua_function *fcn;
6844
6845 MAY_LJMP(check_args(L, 3, "register_service"));
6846
6847 /* First argument : converter name. */
6848 name = MAY_LJMP(luaL_checkstring(L, 1));
6849
6850 /* Second argument : environment. */
6851 env = MAY_LJMP(luaL_checkstring(L, 2));
6852
6853 /* Third argument : lua function. */
6854 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6855
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006856 /* Allocate and fill the sample fetch keyword struct. */
6857 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6858 if (!akl)
6859 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6860 fcn = calloc(1, sizeof(*fcn));
6861 if (!fcn)
6862 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6863
6864 /* Fill fcn. */
6865 len = strlen("<lua.>") + strlen(name) + 1;
6866 fcn->name = calloc(1, len);
6867 if (!fcn->name)
6868 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6869 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6870 fcn->function_ref = ref;
6871
6872 /* List head */
6873 akl->list.n = akl->list.p = NULL;
6874
6875 /* converter keyword. */
6876 len = strlen("lua.") + strlen(name) + 1;
6877 akl->kw[0].kw = calloc(1, len);
6878 if (!akl->kw[0].kw)
6879 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6880
6881 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6882
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01006883 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006884 if (strcmp(env, "tcp") == 0)
6885 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006886 else if (strcmp(env, "http") == 0)
6887 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006888 else
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006889 WILL_LJMP(luaL_error(L, "lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01006890 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006891
6892 akl->kw[0].match_pfx = 0;
6893 akl->kw[0].private = fcn;
6894
6895 /* End of array. */
6896 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6897
6898 /* Register this new converter */
6899 service_keywords_register(akl);
6900
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006901 return 0;
6902}
6903
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006904/* This function initialises Lua cli handler. It copies the
6905 * arguments in the Lua stack and create channel IO objects.
6906 */
6907static int hlua_cli_parse_fct(char **args, struct appctx *appctx, void *private)
6908{
6909 struct hlua *hlua;
6910 struct hlua_function *fcn;
6911 int i;
6912 const char *error;
6913
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006914 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006915 appctx->ctx.hlua_cli.fcn = private;
6916
Willy Tarreaubafbe012017-11-24 17:34:44 +01006917 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006918 if (!hlua) {
6919 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006920 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006921 }
6922 HLUA_INIT(hlua);
6923 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006924
6925 /* Create task used by signal to wakeup applets.
6926 * We use the same wakeup fonction than the Lua applet_tcp and
6927 * applet_http. It is absolutely compatible.
6928 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006929 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006930 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01006931 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006932 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006933 }
6934 appctx->ctx.hlua_cli.task->nice = 0;
6935 appctx->ctx.hlua_cli.task->context = appctx;
6936 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
6937
6938 /* Initialises the Lua context */
6939 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
6940 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006941 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006942 }
6943
6944 /* The following Lua calls can fail. */
6945 if (!SET_SAFE_LJMP(hlua->T)) {
6946 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6947 error = lua_tostring(hlua->T, -1);
6948 else
6949 error = "critical error";
6950 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
6951 goto error;
6952 }
6953
6954 /* Check stack available size. */
6955 if (!lua_checkstack(hlua->T, 2)) {
6956 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6957 goto error;
6958 }
6959
6960 /* Restore the function in the stack. */
6961 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
6962
6963 /* Once the arguments parsed, the CLI is like an AppletTCP,
6964 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006965 */
6966 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
6967 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6968 goto error;
6969 }
6970 hlua->nargs = 1;
6971
6972 /* push keywords in the stack. */
6973 for (i = 0; *args[i]; i++) {
6974 /* Check stack available size. */
6975 if (!lua_checkstack(hlua->T, 1)) {
6976 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6977 goto error;
6978 }
6979 lua_pushstring(hlua->T, args[i]);
6980 hlua->nargs++;
6981 }
6982
6983 /* We must initialize the execution timeouts. */
6984 hlua->max_time = hlua_timeout_session;
6985
6986 /* At this point the execution is safe. */
6987 RESET_SAFE_LJMP(hlua->T);
6988
6989 /* It's ok */
6990 return 0;
6991
6992 /* It's not ok. */
6993error:
6994 RESET_SAFE_LJMP(hlua->T);
6995 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006996 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006997 return 1;
6998}
6999
7000static int hlua_cli_io_handler_fct(struct appctx *appctx)
7001{
7002 struct hlua *hlua;
7003 struct stream_interface *si;
7004 struct hlua_function *fcn;
7005
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007006 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007007 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01007008 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007009
7010 /* If the stream is disconnect or closed, ldo nothing. */
7011 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7012 return 1;
7013
7014 /* Execute the function. */
7015 switch (hlua_ctx_resume(hlua, 1)) {
7016
7017 /* finished. */
7018 case HLUA_E_OK:
7019 return 1;
7020
7021 /* yield. */
7022 case HLUA_E_AGAIN:
7023 /* We want write. */
7024 if (HLUA_IS_WAKERESWR(hlua))
7025 si_applet_cant_put(si);
7026 /* Set the timeout. */
7027 if (hlua->wake_time != TICK_ETERNITY)
7028 task_schedule(hlua->task, hlua->wake_time);
7029 return 0;
7030
7031 /* finished with error. */
7032 case HLUA_E_ERRMSG:
7033 /* Display log. */
7034 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
7035 fcn->name, lua_tostring(hlua->T, -1));
7036 lua_pop(hlua->T, 1);
7037 return 1;
7038
7039 case HLUA_E_ERR:
7040 /* Display log. */
7041 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
7042 fcn->name);
7043 return 1;
7044
7045 default:
7046 return 1;
7047 }
7048
7049 return 1;
7050}
7051
7052static void hlua_cli_io_release_fct(struct appctx *appctx)
7053{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007054 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007055 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007056}
7057
7058/* This function is an LUA binding used for registering
7059 * new keywords in the cli. It expects a list of keywords
7060 * which are the "path". It is limited to 5 keywords. A
7061 * description of the command, a function to be executed
7062 * for the parsing and a function for io handlers.
7063 */
7064__LJMP static int hlua_register_cli(lua_State *L)
7065{
7066 struct cli_kw_list *cli_kws;
7067 const char *message;
7068 int ref_io;
7069 int len;
7070 struct hlua_function *fcn;
7071 int index;
7072 int i;
7073
7074 MAY_LJMP(check_args(L, 3, "register_cli"));
7075
7076 /* First argument : an array of maximum 5 keywords. */
7077 if (!lua_istable(L, 1))
7078 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
7079
7080 /* Second argument : string with contextual message. */
7081 message = MAY_LJMP(luaL_checkstring(L, 2));
7082
7083 /* Third and fourth argument : lua function. */
7084 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
7085
7086 /* Allocate and fill the sample fetch keyword struct. */
7087 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
7088 if (!cli_kws)
7089 WILL_LJMP(luaL_error(L, "lua out of memory error."));
7090 fcn = calloc(1, sizeof(*fcn));
7091 if (!fcn)
7092 WILL_LJMP(luaL_error(L, "lua out of memory error."));
7093
7094 /* Fill path. */
7095 index = 0;
7096 lua_pushnil(L);
7097 while(lua_next(L, 1) != 0) {
7098 if (index >= 5)
7099 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
7100 if (lua_type(L, -1) != LUA_TSTRING)
7101 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
7102 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
7103 if (!cli_kws->kw[0].str_kw[index])
7104 WILL_LJMP(luaL_error(L, "lua out of memory error."));
7105 index++;
7106 lua_pop(L, 1);
7107 }
7108
7109 /* Copy help message. */
7110 cli_kws->kw[0].usage = strdup(message);
7111 if (!cli_kws->kw[0].usage)
7112 WILL_LJMP(luaL_error(L, "lua out of memory error."));
7113
7114 /* Fill fcn io handler. */
7115 len = strlen("<lua.cli>") + 1;
7116 for (i = 0; i < index; i++)
7117 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
7118 fcn->name = calloc(1, len);
7119 if (!fcn->name)
7120 WILL_LJMP(luaL_error(L, "lua out of memory error."));
7121 strncat((char *)fcn->name, "<lua.cli", len);
7122 for (i = 0; i < index; i++) {
7123 strncat((char *)fcn->name, ".", len);
7124 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
7125 }
7126 strncat((char *)fcn->name, ">", len);
7127 fcn->function_ref = ref_io;
7128
7129 /* Fill last entries. */
7130 cli_kws->kw[0].private = fcn;
7131 cli_kws->kw[0].parse = hlua_cli_parse_fct;
7132 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
7133 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
7134
7135 /* Register this new converter */
7136 cli_register_kw(cli_kws);
7137
7138 return 0;
7139}
7140
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007141static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
7142 struct proxy *defpx, const char *file, int line,
7143 char **err, unsigned int *timeout)
7144{
7145 const char *error;
7146
7147 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
7148 if (error && *error != '\0') {
7149 memprintf(err, "%s: invalid timeout", args[0]);
7150 return -1;
7151 }
7152 return 0;
7153}
7154
7155static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
7156 struct proxy *defpx, const char *file, int line,
7157 char **err)
7158{
7159 return hlua_read_timeout(args, section_type, curpx, defpx,
7160 file, line, err, &hlua_timeout_session);
7161}
7162
7163static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
7164 struct proxy *defpx, const char *file, int line,
7165 char **err)
7166{
7167 return hlua_read_timeout(args, section_type, curpx, defpx,
7168 file, line, err, &hlua_timeout_task);
7169}
7170
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007171static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
7172 struct proxy *defpx, const char *file, int line,
7173 char **err)
7174{
7175 return hlua_read_timeout(args, section_type, curpx, defpx,
7176 file, line, err, &hlua_timeout_applet);
7177}
7178
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007179static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
7180 struct proxy *defpx, const char *file, int line,
7181 char **err)
7182{
7183 char *error;
7184
7185 hlua_nb_instruction = strtoll(args[1], &error, 10);
7186 if (*error != '\0') {
7187 memprintf(err, "%s: invalid number", args[0]);
7188 return -1;
7189 }
7190 return 0;
7191}
7192
Willy Tarreau32f61e22015-03-18 17:54:59 +01007193static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
7194 struct proxy *defpx, const char *file, int line,
7195 char **err)
7196{
7197 char *error;
7198
7199 if (*(args[1]) == 0) {
7200 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
7201 return -1;
7202 }
7203 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
7204 if (*error != '\0') {
7205 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
7206 return -1;
7207 }
7208 return 0;
7209}
7210
7211
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007212/* This function is called by the main configuration key "lua-load". It loads and
7213 * execute an lua file during the parsing of the HAProxy configuration file. It is
7214 * the main lua entry point.
7215 *
7216 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
7217 * occured, otherwise it returns 0.
7218 *
7219 * In some error case, LUA set an error message in top of the stack. This function
7220 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007221 *
7222 * This function can fail with an abort() due to an Lua critical error.
7223 * We are in the configuration parsing process of HAProxy, this abort() is
7224 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007225 */
7226static int hlua_load(char **args, int section_type, struct proxy *curpx,
7227 struct proxy *defpx, const char *file, int line,
7228 char **err)
7229{
7230 int error;
7231
7232 /* Just load and compile the file. */
7233 error = luaL_loadfile(gL.T, args[1]);
7234 if (error) {
7235 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
7236 lua_pop(gL.T, 1);
7237 return -1;
7238 }
7239
7240 /* If no syntax error where detected, execute the code. */
7241 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
7242 switch (error) {
7243 case LUA_OK:
7244 break;
7245 case LUA_ERRRUN:
7246 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
7247 lua_pop(gL.T, 1);
7248 return -1;
7249 case LUA_ERRMEM:
7250 memprintf(err, "lua out of memory error\n");
7251 return -1;
7252 case LUA_ERRERR:
7253 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
7254 lua_pop(gL.T, 1);
7255 return -1;
7256 case LUA_ERRGCMM:
7257 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
7258 lua_pop(gL.T, 1);
7259 return -1;
7260 default:
7261 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
7262 lua_pop(gL.T, 1);
7263 return -1;
7264 }
7265
7266 return 0;
7267}
7268
7269/* configuration keywords declaration */
7270static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007271 { CFG_GLOBAL, "lua-load", hlua_load },
7272 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
7273 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02007274 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007275 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01007276 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007277 { 0, NULL, NULL },
7278}};
7279
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007280/* This function can fail with an abort() due to an Lua critical error.
7281 * We are in the initialisation process of HAProxy, this abort() is
7282 * tolerated.
7283 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007284int hlua_post_init()
7285{
7286 struct hlua_init_function *init;
7287 const char *msg;
7288 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007289 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007290
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007291 /* Call post initialisation function in safe environement. */
7292 if (!SET_SAFE_LJMP(gL.T)) {
7293 if (lua_type(gL.T, -1) == LUA_TSTRING)
7294 error = lua_tostring(gL.T, -1);
7295 else
7296 error = "critical error";
7297 fprintf(stderr, "Lua post-init: %s.\n", error);
7298 exit(1);
7299 }
7300 hlua_fcn_post_init(gL.T);
7301 RESET_SAFE_LJMP(gL.T);
7302
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007303 list_for_each_entry(init, &hlua_init_functions, l) {
7304 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7305 ret = hlua_ctx_resume(&gL, 0);
7306 switch (ret) {
7307 case HLUA_E_OK:
7308 lua_pop(gL.T, -1);
7309 return 1;
7310 case HLUA_E_AGAIN:
Christopher Faulet767a84b2017-11-24 16:50:31 +01007311 ha_alert("lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007312 return 0;
7313 case HLUA_E_ERRMSG:
7314 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01007315 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007316 return 0;
7317 case HLUA_E_ERR:
7318 default:
Christopher Faulet767a84b2017-11-24 16:50:31 +01007319 ha_alert("lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007320 return 0;
7321 }
7322 }
7323 return 1;
7324}
7325
Willy Tarreau32f61e22015-03-18 17:54:59 +01007326/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7327 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7328 * is the previously allocated size or the kind of object in case of a new
7329 * allocation. <nsize> is the requested new size.
7330 */
7331static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7332{
7333 struct hlua_mem_allocator *zone = ud;
7334
7335 if (nsize == 0) {
7336 /* it's a free */
7337 if (ptr)
7338 zone->allocated -= osize;
7339 free(ptr);
7340 return NULL;
7341 }
7342
7343 if (!ptr) {
7344 /* it's a new allocation */
7345 if (zone->limit && zone->allocated + nsize > zone->limit)
7346 return NULL;
7347
7348 ptr = malloc(nsize);
7349 if (ptr)
7350 zone->allocated += nsize;
7351 return ptr;
7352 }
7353
7354 /* it's a realloc */
7355 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7356 return NULL;
7357
7358 ptr = realloc(ptr, nsize);
7359 if (ptr)
7360 zone->allocated += nsize - osize;
7361 return ptr;
7362}
7363
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007364/* Ithis function can fail with an abort() due to an Lua critical error.
7365 * We are in the initialisation process of HAProxy, this abort() is
7366 * tolerated.
7367 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007368void hlua_init(void)
7369{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007370 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007371 int idx;
7372 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007373 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007374 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007375 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007376#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007377 struct srv_kw *kw;
7378 int tmp_error;
7379 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007380 char *args[] = { /* SSL client configuration. */
7381 "ssl",
7382 "verify",
7383 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007384 NULL
7385 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007386#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007387
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007388 HA_SPIN_INIT(&hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02007389
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007390 /* Initialise struct hlua and com signals pool */
Willy Tarreaubafbe012017-11-24 17:34:44 +01007391 pool_head_hlua = create_pool("hlua", sizeof(struct hlua), MEM_F_SHARED);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007392
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007393 /* Register configuration keywords. */
7394 cfg_register_keywords(&cfg_kws);
7395
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007396 /* Init main lua stack. */
7397 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01007398 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007399 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02007400 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007401 hlua_sethlua(&gL);
7402 gL.Tref = LUA_REFNIL;
7403 gL.task = NULL;
7404
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007405 /* From this point, until the end of the initialisation fucntion,
7406 * the Lua function can fail with an abort. We are in the initialisation
7407 * process of HAProxy, this abort() is tolerated.
7408 */
7409
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007410 /* Initialise lua. */
7411 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007412
Thierry Fournier75933d42016-01-21 09:30:18 +01007413 /* Set safe environment for the initialisation. */
7414 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007415 if (lua_type(gL.T, -1) == LUA_TSTRING)
7416 error_msg = lua_tostring(gL.T, -1);
7417 else
7418 error_msg = "critical error";
7419 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01007420 exit(1);
7421 }
7422
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007423 /*
7424 *
7425 * Create "core" object.
7426 *
7427 */
7428
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01007429 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007430 lua_newtable(gL.T);
7431
7432 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007433 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007434 hlua_class_const_int(gL.T, log_levels[i], i);
7435
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007436 /* Register special functions. */
7437 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007438 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007439 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007440 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007441 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007442 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007443 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007444 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01007445 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007446 hlua_class_function(gL.T, "sleep", hlua_sleep);
7447 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01007448 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
7449 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
7450 hlua_class_function(gL.T, "set_map", hlua_set_map);
7451 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007452 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007453 hlua_class_function(gL.T, "log", hlua_log);
7454 hlua_class_function(gL.T, "Debug", hlua_log_debug);
7455 hlua_class_function(gL.T, "Info", hlua_log_info);
7456 hlua_class_function(gL.T, "Warning", hlua_log_warning);
7457 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02007458 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01007459 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007460
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007461 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007462
7463 /*
7464 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007465 * Register class Map
7466 *
7467 */
7468
7469 /* This table entry is the object "Map" base. */
7470 lua_newtable(gL.T);
7471
7472 /* register pattern types. */
7473 for (i=0; i<PAT_MATCH_NUM; i++)
7474 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007475 for (i=0; i<PAT_MATCH_NUM; i++) {
7476 snprintf(trash.str, trash.size, "_%s", pat_match_names[i]);
7477 hlua_class_const_int(gL.T, trash.str, i);
7478 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007479
7480 /* register constructor. */
7481 hlua_class_function(gL.T, "new", hlua_map_new);
7482
7483 /* Create and fill the metatable. */
7484 lua_newtable(gL.T);
7485
7486 /* Create and fille the __index entry. */
7487 lua_pushstring(gL.T, "__index");
7488 lua_newtable(gL.T);
7489
7490 /* Register . */
7491 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
7492 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
7493
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007494 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007495
Thierry Fournier45e78d72016-02-19 18:34:46 +01007496 /* Register previous table in the registry with reference and named entry.
7497 * The function hlua_register_metatable() pops the stack, so we
7498 * previously create a copy of the table.
7499 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007500 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007501 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007502
7503 /* Assign the metatable to the mai Map object. */
7504 lua_setmetatable(gL.T, -2);
7505
7506 /* Set a name to the table. */
7507 lua_setglobal(gL.T, "Map");
7508
7509 /*
7510 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007511 * Register class Channel
7512 *
7513 */
7514
7515 /* Create and fill the metatable. */
7516 lua_newtable(gL.T);
7517
7518 /* Create and fille the __index entry. */
7519 lua_pushstring(gL.T, "__index");
7520 lua_newtable(gL.T);
7521
7522 /* Register . */
7523 hlua_class_function(gL.T, "get", hlua_channel_get);
7524 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7525 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7526 hlua_class_function(gL.T, "set", hlua_channel_set);
7527 hlua_class_function(gL.T, "append", hlua_channel_append);
7528 hlua_class_function(gL.T, "send", hlua_channel_send);
7529 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7530 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7531 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007532 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007533
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007534 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007535
7536 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007537 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007538
7539 /*
7540 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007541 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007542 *
7543 */
7544
7545 /* Create and fill the metatable. */
7546 lua_newtable(gL.T);
7547
7548 /* Create and fille the __index entry. */
7549 lua_pushstring(gL.T, "__index");
7550 lua_newtable(gL.T);
7551
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007552 /* Browse existing fetches and create the associated
7553 * object method.
7554 */
7555 sf = NULL;
7556 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7557
7558 /* Dont register the keywork if the arguments check function are
7559 * not safe during the runtime.
7560 */
7561 if ((sf->val_args != NULL) &&
7562 (sf->val_args != val_payload_lv) &&
7563 (sf->val_args != val_hdr))
7564 continue;
7565
7566 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7567 * by an underscore.
7568 */
7569 strncpy(trash.str, sf->kw, trash.size);
7570 trash.str[trash.size - 1] = '\0';
7571 for (p = trash.str; *p; p++)
7572 if (*p == '.' || *p == '-' || *p == '+')
7573 *p = '_';
7574
7575 /* Register the function. */
7576 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007577 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007578 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007579 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007580 }
7581
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007582 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007583
7584 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007585 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007586
7587 /*
7588 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007589 * Register class Converters
7590 *
7591 */
7592
7593 /* Create and fill the metatable. */
7594 lua_newtable(gL.T);
7595
7596 /* Create and fill the __index entry. */
7597 lua_pushstring(gL.T, "__index");
7598 lua_newtable(gL.T);
7599
7600 /* Browse existing converters and create the associated
7601 * object method.
7602 */
7603 sc = NULL;
7604 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7605 /* Dont register the keywork if the arguments check function are
7606 * not safe during the runtime.
7607 */
7608 if (sc->val_args != NULL)
7609 continue;
7610
7611 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7612 * by an underscore.
7613 */
7614 strncpy(trash.str, sc->kw, trash.size);
7615 trash.str[trash.size - 1] = '\0';
7616 for (p = trash.str; *p; p++)
7617 if (*p == '.' || *p == '-' || *p == '+')
7618 *p = '_';
7619
7620 /* Register the function. */
7621 lua_pushstring(gL.T, trash.str);
7622 lua_pushlightuserdata(gL.T, sc);
7623 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007624 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007625 }
7626
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007627 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007628
7629 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007630 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007631
7632 /*
7633 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007634 * Register class HTTP
7635 *
7636 */
7637
7638 /* Create and fill the metatable. */
7639 lua_newtable(gL.T);
7640
7641 /* Create and fille the __index entry. */
7642 lua_pushstring(gL.T, "__index");
7643 lua_newtable(gL.T);
7644
7645 /* Register Lua functions. */
7646 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7647 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7648 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7649 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7650 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7651 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7652 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7653 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7654 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7655 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7656
7657 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7658 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7659 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7660 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7661 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7662 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007663 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007664
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007665 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007666
7667 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007668 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007669
7670 /*
7671 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007672 * Register class AppletTCP
7673 *
7674 */
7675
7676 /* Create and fill the metatable. */
7677 lua_newtable(gL.T);
7678
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007679 /* Create and fille the __index entry. */
7680 lua_pushstring(gL.T, "__index");
7681 lua_newtable(gL.T);
7682
7683 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01007684 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7685 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7686 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7687 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7688 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007689 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
7690 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
7691 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007692
7693 lua_settable(gL.T, -3);
7694
7695 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007696 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007697
7698 /*
7699 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007700 * Register class AppletHTTP
7701 *
7702 */
7703
7704 /* Create and fill the metatable. */
7705 lua_newtable(gL.T);
7706
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007707 /* Create and fille the __index entry. */
7708 lua_pushstring(gL.T, "__index");
7709 lua_newtable(gL.T);
7710
7711 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007712 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7713 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007714 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
7715 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
7716 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007717 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7718 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7719 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7720 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7721 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7722 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7723
7724 lua_settable(gL.T, -3);
7725
7726 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007727 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007728
7729 /*
7730 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007731 * Register class TXN
7732 *
7733 */
7734
7735 /* Create and fill the metatable. */
7736 lua_newtable(gL.T);
7737
7738 /* Create and fille the __index entry. */
7739 lua_pushstring(gL.T, "__index");
7740 lua_newtable(gL.T);
7741
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007742 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01007743 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7744 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007745 hlua_class_function(gL.T, "set_var", hlua_set_var);
Christopher Faulet85d79c92016-11-09 16:54:56 +01007746 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007747 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007748 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007749 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
7750 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7751 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007752 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7753 hlua_class_function(gL.T, "log", hlua_txn_log);
7754 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7755 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7756 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7757 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007758
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007759 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007760
7761 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007762 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007763
7764 /*
7765 *
7766 * Register class Socket
7767 *
7768 */
7769
7770 /* Create and fill the metatable. */
7771 lua_newtable(gL.T);
7772
7773 /* Create and fille the __index entry. */
7774 lua_pushstring(gL.T, "__index");
7775 lua_newtable(gL.T);
7776
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007777#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007778 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007779#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007780 hlua_class_function(gL.T, "connect", hlua_socket_connect);
7781 hlua_class_function(gL.T, "send", hlua_socket_send);
7782 hlua_class_function(gL.T, "receive", hlua_socket_receive);
7783 hlua_class_function(gL.T, "close", hlua_socket_close);
7784 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
7785 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
7786 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
7787 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
7788
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007789 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007790
7791 /* Register the garbage collector entry. */
7792 lua_pushstring(gL.T, "__gc");
7793 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007794 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007795
7796 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007797 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007798
7799 /* Proxy and server configuration initialisation. */
7800 memset(&socket_proxy, 0, sizeof(socket_proxy));
7801 init_new_proxy(&socket_proxy);
7802 socket_proxy.parent = NULL;
7803 socket_proxy.last_change = now.tv_sec;
7804 socket_proxy.id = "LUA-SOCKET";
7805 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
7806 socket_proxy.maxconn = 0;
7807 socket_proxy.accept = NULL;
7808 socket_proxy.options2 |= PR_O2_INDEPSTR;
7809 socket_proxy.srv = NULL;
7810 socket_proxy.conn_retries = 0;
7811 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
7812
7813 /* Init TCP server: unchanged parameters */
7814 memset(&socket_tcp, 0, sizeof(socket_tcp));
7815 socket_tcp.next = NULL;
7816 socket_tcp.proxy = &socket_proxy;
7817 socket_tcp.obj_type = OBJ_TYPE_SERVER;
7818 LIST_INIT(&socket_tcp.actconns);
7819 LIST_INIT(&socket_tcp.pendconns);
Christopher Faulet40a007c2017-07-03 15:41:01 +02007820 socket_tcp.priv_conns = NULL;
7821 socket_tcp.idle_conns = NULL;
7822 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02007823 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007824 socket_tcp.last_change = 0;
7825 socket_tcp.id = "LUA-TCP-CONN";
7826 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7827 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7828 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
7829
7830 /* XXX: Copy default parameter from default server,
7831 * but the default server is not initialized.
7832 */
7833 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
7834 socket_tcp.minconn = socket_proxy.defsrv.minconn;
7835 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
7836 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
7837 socket_tcp.onerror = socket_proxy.defsrv.onerror;
7838 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7839 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
7840 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7841 socket_tcp.uweight = socket_proxy.defsrv.iweight;
7842 socket_tcp.iweight = socket_proxy.defsrv.iweight;
7843
7844 socket_tcp.check.status = HCHK_STATUS_INI;
7845 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
7846 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
7847 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
7848 socket_tcp.check.server = &socket_tcp;
7849
7850 socket_tcp.agent.status = HCHK_STATUS_INI;
7851 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
7852 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
7853 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
7854 socket_tcp.agent.server = &socket_tcp;
7855
Willy Tarreaua261e9b2016-12-22 20:44:00 +01007856 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007857
7858#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007859 /* Init TCP server: unchanged parameters */
7860 memset(&socket_ssl, 0, sizeof(socket_ssl));
7861 socket_ssl.next = NULL;
7862 socket_ssl.proxy = &socket_proxy;
7863 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7864 LIST_INIT(&socket_ssl.actconns);
7865 LIST_INIT(&socket_ssl.pendconns);
Christopher Faulet40a007c2017-07-03 15:41:01 +02007866 socket_tcp.priv_conns = NULL;
7867 socket_tcp.idle_conns = NULL;
7868 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02007869 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007870 socket_ssl.last_change = 0;
7871 socket_ssl.id = "LUA-SSL-CONN";
7872 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7873 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7874 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7875
7876 /* XXX: Copy default parameter from default server,
7877 * but the default server is not initialized.
7878 */
7879 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7880 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7881 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7882 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7883 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7884 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7885 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7886 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7887 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7888 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7889
7890 socket_ssl.check.status = HCHK_STATUS_INI;
7891 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7892 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7893 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7894 socket_ssl.check.server = &socket_ssl;
7895
7896 socket_ssl.agent.status = HCHK_STATUS_INI;
7897 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7898 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7899 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7900 socket_ssl.agent.server = &socket_ssl;
7901
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007902 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01007903 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007904
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007905 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007906 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7907 /*
7908 *
7909 * If the keyword is not known, we can search in the registered
7910 * server keywords. This is usefull to configure special SSL
7911 * features like client certificates and ssl_verify.
7912 *
7913 */
7914 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7915 if (tmp_error != 0) {
7916 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7917 abort(); /* This must be never arrives because the command line
7918 not editable by the user. */
7919 }
7920 idx += kw->skip;
7921 }
7922 }
7923
7924 /* Initialize SSL server. */
Willy Tarreau17d45382016-12-22 21:16:08 +01007925 if (socket_ssl.xprt->prepare_srv)
7926 socket_ssl.xprt->prepare_srv(&socket_ssl);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007927#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01007928
7929 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007930}
Willy Tarreaubb57d942016-12-21 19:04:56 +01007931
7932__attribute__((constructor))
7933static void __hlua_init(void)
7934{
7935 char *ptr = NULL;
7936 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
7937 hap_register_build_opts(ptr, 1);
7938}