blob: e1b7264979f5f1cebef90bcd6c502f983f0331ca [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 FOURNIER380d0932015-01-23 14:27:52 +010028
William Lallemand9ed62032016-11-21 17:49:11 +010029#include <types/cli.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010030#include <types/hlua.h>
31#include <types/proxy.h>
William Lallemand9ed62032016-11-21 17:49:11 +010032#include <types/stats.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010033
Thierry FOURNIER55da1652015-01-23 11:36:30 +010034#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020035#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010036#include <proto/channel.h>
William Lallemand9ed62032016-11-21 17:49:11 +010037#include <proto/cli.h>
Willy Tarreaua71f6422016-11-16 17:00:14 +010038#include <proto/connection.h>
William Lallemand9ed62032016-11-21 17:49:11 +010039#include <proto/stats.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010040#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010041#include <proto/hlua.h>
Thierry Fournierfb0b5462016-01-21 09:28:58 +010042#include <proto/hlua_fcn.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020043#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010044#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010045#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010046#include <proto/payload.h>
47#include <proto/proto_http.h>
48#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010049#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020050#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020051#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010052#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010053#include <proto/task.h>
Willy Tarreau39713102016-11-25 15:49:32 +010054#include <proto/tcp_rules.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020055#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010056
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010057/* Lua uses longjmp to perform yield or throwing errors. This
58 * macro is used only for identifying the function that can
59 * not return because a longjmp is executed.
60 * __LJMP marks a prototype of hlua file that can use longjmp.
61 * WILL_LJMP() marks an lua function that will use longjmp.
62 * MAY_LJMP() marks an lua function that may use longjmp.
63 */
64#define __LJMP
65#define WILL_LJMP(func) func
66#define MAY_LJMP(func) func
67
Thierry FOURNIERbabae282015-09-17 11:36:37 +020068/* This couple of function executes securely some Lua calls outside of
69 * the lua runtime environment. Each Lua call can return a longjmp
70 * if it encounter a memory error.
71 *
72 * Lua documentation extract:
73 *
74 * If an error happens outside any protected environment, Lua calls
75 * a panic function (see lua_atpanic) and then calls abort, thus
76 * exiting the host application. Your panic function can avoid this
77 * exit by never returning (e.g., doing a long jump to your own
78 * recovery point outside Lua).
79 *
80 * The panic function runs as if it were a message handler (see
81 * §2.3); in particular, the error message is at the top of the
82 * stack. However, there is no guarantee about stack space. To push
83 * anything on the stack, the panic function must first check the
84 * available space (see §4.2).
85 *
86 * We must check all the Lua entry point. This includes:
87 * - The include/proto/hlua.h exported functions
88 * - the task wrapper function
89 * - The action wrapper function
90 * - The converters wrapper function
91 * - The sample-fetch wrapper functions
92 *
93 * It is tolerated that the initilisation function returns an abort.
94 * Before each Lua abort, an error message is writed on stderr.
95 *
96 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
97 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
98 * because they must be exists in the program stack when the longjmp
99 * is called.
100 */
101jmp_buf safe_ljmp_env;
102static int hlua_panic_safe(lua_State *L) { return 0; }
103static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
104
105#define SET_SAFE_LJMP(__L) \
106 ({ \
107 int ret; \
108 if (setjmp(safe_ljmp_env) != 0) { \
109 lua_atpanic(__L, hlua_panic_safe); \
110 ret = 0; \
111 } else { \
112 lua_atpanic(__L, hlua_panic_ljmp); \
113 ret = 1; \
114 } \
115 ret; \
116 })
117
118/* If we are the last function catching Lua errors, we
119 * must reset the panic function.
120 */
121#define RESET_SAFE_LJMP(__L) \
122 do { \
123 lua_atpanic(__L, hlua_panic_safe); \
124 } while(0)
125
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200126/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200127#define APPLET_DONE 0x01 /* applet processing is done. */
128#define APPLET_100C 0x02 /* 100 continue expected. */
129#define APPLET_HDR_SENT 0x04 /* Response header sent. */
130#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
131#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100132#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200133
134#define HTTP_100C "HTTP/1.1 100 Continue\r\n\r\n"
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200135
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100136/* The main Lua execution context. */
137struct hlua gL;
138
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100139/* This is the memory pool containing struct lua for applets
140 * (including cli).
141 */
142struct pool_head *pool2_hlua;
143
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100144/* Used for Socket connection. */
145static struct proxy socket_proxy;
146static struct server socket_tcp;
147#ifdef USE_OPENSSL
148static struct server socket_ssl;
149#endif
150
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100151/* List head of the function called at the initialisation time. */
152struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
153
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100154/* The following variables contains the reference of the different
155 * Lua classes. These references are useful for identify metadata
156 * associated with an object.
157 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100158static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100159static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100160static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100161static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100162static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100163static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200164static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200165static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200166static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100167
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100168/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200169 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100170 * short timeout. Lua linked with tasks doesn't have a timeout
171 * because a task may remain alive during all the haproxy execution.
172 */
173static unsigned int hlua_timeout_session = 4000; /* session timeout. */
174static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200175static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100176
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100177/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
178 * it is used for preventing infinite loops.
179 *
180 * I test the scheer with an infinite loop containing one incrementation
181 * and one test. I run this loop between 10 seconds, I raise a ceil of
182 * 710M loops from one interrupt each 9000 instructions, so I fix the value
183 * to one interrupt each 10 000 instructions.
184 *
185 * configured | Number of
186 * instructions | loops executed
187 * between two | in milions
188 * forced yields |
189 * ---------------+---------------
190 * 10 | 160
191 * 500 | 670
192 * 1000 | 680
193 * 5000 | 700
194 * 7000 | 700
195 * 8000 | 700
196 * 9000 | 710 <- ceil
197 * 10000 | 710
198 * 100000 | 710
199 * 1000000 | 710
200 *
201 */
202static unsigned int hlua_nb_instruction = 10000;
203
Willy Tarreau32f61e22015-03-18 17:54:59 +0100204/* Descriptor for the memory allocation state. If limit is not null, it will
205 * be enforced on any memory allocation.
206 */
207struct hlua_mem_allocator {
208 size_t allocated;
209 size_t limit;
210};
211
212static struct hlua_mem_allocator hlua_global_allocator;
213
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200214static const char error_500[] =
Jarno Huuskonen16ad94a2017-01-09 14:17:10 +0200215 "HTTP/1.0 500 Internal Server Error\r\n"
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200216 "Cache-Control: no-cache\r\n"
217 "Connection: close\r\n"
218 "Content-Type: text/html\r\n"
219 "\r\n"
Jarno Huuskonen16ad94a2017-01-09 14:17:10 +0200220 "<html><body><h1>500 Internal Server Error</h1>\nAn internal server error occured.\n</body></html>\n";
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200221
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100222/* These functions converts types between HAProxy internal args or
223 * sample and LUA types. Another function permits to check if the
224 * LUA stack contains arguments according with an required ARG_T
225 * format.
226 */
227static int hlua_arg2lua(lua_State *L, const struct arg *arg);
228static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100229__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100230 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100231static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100232static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100233static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
234
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200235__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
236
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200237#define SEND_ERR(__be, __fmt, __args...) \
238 do { \
239 send_log(__be, LOG_ERR, __fmt, ## __args); \
240 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
241 Alert(__fmt, ## __args); \
242 } while (0)
243
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100244/* Used to check an Lua function type in the stack. It creates and
245 * returns a reference of the function. This function throws an
246 * error if the rgument is not a "function".
247 */
248__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
249{
250 if (!lua_isfunction(L, argno)) {
251 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
252 WILL_LJMP(luaL_argerror(L, argno, msg));
253 }
254 lua_pushvalue(L, argno);
255 return luaL_ref(L, LUA_REGISTRYINDEX);
256}
257
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200258/* Return the string that is of the top of the stack. */
259const char *hlua_get_top_error_string(lua_State *L)
260{
261 if (lua_gettop(L) < 1)
262 return "unknown error";
263 if (lua_type(L, -1) != LUA_TSTRING)
264 return "unknown error";
265 return lua_tostring(L, -1);
266}
267
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100268/* This function check the number of arguments available in the
269 * stack. If the number of arguments available is not the same
270 * then <nb> an error is throwed.
271 */
272__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
273{
274 if (lua_gettop(L) == nb)
275 return;
276 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
277}
278
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100279/* This fucntion push an error string prefixed by the file name
280 * and the line number where the error is encountered.
281 */
282static int hlua_pusherror(lua_State *L, const char *fmt, ...)
283{
284 va_list argp;
285 va_start(argp, fmt);
286 luaL_where(L, 1);
287 lua_pushvfstring(L, fmt, argp);
288 va_end(argp);
289 lua_concat(L, 2);
290 return 1;
291}
292
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100293/* This functions is used with sample fetch and converters. It
294 * converts the HAProxy configuration argument in a lua stack
295 * values.
296 *
297 * It takes an array of "arg", and each entry of the array is
298 * converted and pushed in the LUA stack.
299 */
300static int hlua_arg2lua(lua_State *L, const struct arg *arg)
301{
302 switch (arg->type) {
303 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100304 case ARGT_TIME:
305 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100306 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100307 break;
308
309 case ARGT_STR:
310 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
311 break;
312
313 case ARGT_IPV4:
314 case ARGT_IPV6:
315 case ARGT_MSK4:
316 case ARGT_MSK6:
317 case ARGT_FE:
318 case ARGT_BE:
319 case ARGT_TAB:
320 case ARGT_SRV:
321 case ARGT_USR:
322 case ARGT_MAP:
323 default:
324 lua_pushnil(L);
325 break;
326 }
327 return 1;
328}
329
330/* This function take one entrie in an LUA stack at the index "ud",
331 * and try to convert it in an HAProxy argument entry. This is useful
332 * with sample fetch wrappers. The input arguments are gived to the
333 * lua wrapper and converted as arg list by thi function.
334 */
335static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
336{
337 switch (lua_type(L, ud)) {
338
339 case LUA_TNUMBER:
340 case LUA_TBOOLEAN:
341 arg->type = ARGT_SINT;
342 arg->data.sint = lua_tointeger(L, ud);
343 break;
344
345 case LUA_TSTRING:
346 arg->type = ARGT_STR;
347 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
348 break;
349
350 case LUA_TUSERDATA:
351 case LUA_TNIL:
352 case LUA_TTABLE:
353 case LUA_TFUNCTION:
354 case LUA_TTHREAD:
355 case LUA_TLIGHTUSERDATA:
356 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200357 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100358 break;
359 }
360 return 1;
361}
362
363/* the following functions are used to convert a struct sample
364 * in Lua type. This useful to convert the return of the
365 * fetchs or converters.
366 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100367static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100368{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200369 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100370 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100371 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200372 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100373 break;
374
375 case SMP_T_BIN:
376 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200377 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100378 break;
379
380 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200381 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100382 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
383 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
384 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
385 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
386 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
387 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
388 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
389 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
390 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200391 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100392 break;
393 default:
394 lua_pushnil(L);
395 break;
396 }
397 break;
398
399 case SMP_T_IPV4:
400 case SMP_T_IPV6:
401 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200402 if (sample_casts[smp->data.type][SMP_T_STR] &&
403 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200404 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100405 else
406 lua_pushnil(L);
407 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100408 default:
409 lua_pushnil(L);
410 break;
411 }
412 return 1;
413}
414
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100415/* the following functions are used to convert a struct sample
416 * in Lua strings. This is useful to convert the return of the
417 * fetchs or converters.
418 */
419static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
420{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200421 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100422
423 case SMP_T_BIN:
424 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200425 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100426 break;
427
428 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200429 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100430 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
431 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
432 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
433 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
434 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
435 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
436 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
437 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
438 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200439 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100440 break;
441 default:
442 lua_pushstring(L, "");
443 break;
444 }
445 break;
446
447 case SMP_T_SINT:
448 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100449 case SMP_T_IPV4:
450 case SMP_T_IPV6:
451 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200452 if (sample_casts[smp->data.type][SMP_T_STR] &&
453 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200454 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100455 else
456 lua_pushstring(L, "");
457 break;
458 default:
459 lua_pushstring(L, "");
460 break;
461 }
462 return 1;
463}
464
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100465/* the following functions are used to convert an Lua type in a
466 * struct sample. This is useful to provide data from a converter
467 * to the LUA code.
468 */
469static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
470{
471 switch (lua_type(L, ud)) {
472
473 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200474 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200475 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100476 break;
477
478
479 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200480 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200481 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100482 break;
483
484 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200485 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100486 smp->flags |= SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200487 smp->data.u.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100488 break;
489
490 case LUA_TUSERDATA:
491 case LUA_TNIL:
492 case LUA_TTABLE:
493 case LUA_TFUNCTION:
494 case LUA_TTHREAD:
495 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200496 case LUA_TNONE:
497 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200498 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200499 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100500 break;
501 }
502 return 1;
503}
504
505/* This function check the "argp" builded by another conversion function
506 * is in accord with the expected argp defined by the "mask". The fucntion
507 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100508 *
509 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
510 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100511 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100512__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100513 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100514{
515 int min_arg;
516 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100517 struct proxy *px;
518 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100519
520 idx = 0;
521 min_arg = ARGM(mask);
522 mask >>= ARGM_BITS;
523
524 while (1) {
525
526 /* Check oversize. */
527 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100528 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100529 }
530
531 /* Check for mandatory arguments. */
532 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100533 if (idx < min_arg) {
534
535 /* If miss other argument than the first one, we return an error. */
536 if (idx > 0)
537 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
538
539 /* If first argument have a certain type, some default values
540 * may be used. See the function smp_resolve_args().
541 */
542 switch (mask & ARGT_MASK) {
543
544 case ARGT_FE:
545 if (!(p->cap & PR_CAP_FE))
546 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
547 argp[idx].data.prx = p;
548 argp[idx].type = ARGT_FE;
549 argp[idx+1].type = ARGT_STOP;
550 break;
551
552 case ARGT_BE:
553 if (!(p->cap & PR_CAP_BE))
554 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
555 argp[idx].data.prx = p;
556 argp[idx].type = ARGT_BE;
557 argp[idx+1].type = ARGT_STOP;
558 break;
559
560 case ARGT_TAB:
561 argp[idx].data.prx = p;
562 argp[idx].type = ARGT_TAB;
563 argp[idx+1].type = ARGT_STOP;
564 break;
565
566 default:
567 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
568 break;
569 }
570 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100571 return 0;
572 }
573
574 /* Check for exceed the number of requiered argument. */
575 if ((mask & ARGT_MASK) == ARGT_STOP &&
576 argp[idx].type != ARGT_STOP) {
577 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
578 }
579
580 if ((mask & ARGT_MASK) == ARGT_STOP &&
581 argp[idx].type == ARGT_STOP) {
582 return 0;
583 }
584
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100585 /* Convert some argument types. */
586 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100587 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100588 if (argp[idx].type != ARGT_SINT)
589 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
590 argp[idx].type = ARGT_SINT;
591 break;
592
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100593 case ARGT_TIME:
594 if (argp[idx].type != ARGT_SINT)
595 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200596 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100597 break;
598
599 case ARGT_SIZE:
600 if (argp[idx].type != ARGT_SINT)
601 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200602 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100603 break;
604
605 case ARGT_FE:
606 if (argp[idx].type != ARGT_STR)
607 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
608 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
609 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200610 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100611 if (!argp[idx].data.prx)
612 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
613 argp[idx].type = ARGT_FE;
614 break;
615
616 case ARGT_BE:
617 if (argp[idx].type != ARGT_STR)
618 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
619 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
620 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200621 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100622 if (!argp[idx].data.prx)
623 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
624 argp[idx].type = ARGT_BE;
625 break;
626
627 case ARGT_TAB:
628 if (argp[idx].type != ARGT_STR)
629 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
630 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
631 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200632 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100633 if (!argp[idx].data.prx)
634 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
635 argp[idx].type = ARGT_TAB;
636 break;
637
638 case ARGT_SRV:
639 if (argp[idx].type != ARGT_STR)
640 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
641 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
642 trash.str[argp[idx].data.str.len] = 0;
643 sname = strrchr(trash.str, '/');
644 if (sname) {
645 *sname++ = '\0';
646 pname = trash.str;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200647 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100648 if (!px)
649 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
650 }
651 else {
652 sname = trash.str;
653 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100654 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100655 argp[idx].data.srv = findserver(px, sname);
656 if (!argp[idx].data.srv)
657 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
658 argp[idx].type = ARGT_SRV;
659 break;
660
661 case ARGT_IPV4:
662 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
663 trash.str[argp[idx].data.str.len] = 0;
664 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
665 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
666 argp[idx].type = ARGT_IPV4;
667 break;
668
669 case ARGT_MSK4:
670 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
671 trash.str[argp[idx].data.str.len] = 0;
672 if (!str2mask(trash.str, &argp[idx].data.ipv4))
673 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
674 argp[idx].type = ARGT_MSK4;
675 break;
676
677 case ARGT_IPV6:
678 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
679 trash.str[argp[idx].data.str.len] = 0;
680 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
681 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
682 argp[idx].type = ARGT_IPV6;
683 break;
684
685 case ARGT_MSK6:
686 case ARGT_MAP:
687 case ARGT_REG:
688 case ARGT_USR:
689 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100690 break;
691 }
692
693 /* Check for type of argument. */
694 if ((mask & ARGT_MASK) != argp[idx].type) {
695 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
696 arg_type_names[(mask & ARGT_MASK)],
697 arg_type_names[argp[idx].type & ARGT_MASK]);
698 WILL_LJMP(luaL_argerror(L, first + idx, msg));
699 }
700
701 /* Next argument. */
702 mask >>= ARGT_BITS;
703 idx++;
704 }
705}
706
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100707/*
708 * The following functions are used to make correspondance between the the
709 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100710 *
711 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100712 * - hlua_sethlua : create the association between hlua context and lua_state.
713 */
714static inline struct hlua *hlua_gethlua(lua_State *L)
715{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100716 struct hlua **hlua = lua_getextraspace(L);
717 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100718}
719static inline void hlua_sethlua(struct hlua *hlua)
720{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100721 struct hlua **hlua_store = lua_getextraspace(hlua->T);
722 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100723}
724
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100725/* This function is used to send logs. It try to send on screen (stderr)
726 * and on the default syslog server.
727 */
728static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
729{
730 struct tm tm;
731 char *p;
732
733 /* Cleanup the log message. */
734 p = trash.str;
735 for (; *msg != '\0'; msg++, p++) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200736 if (p >= trash.str + trash.size - 1) {
737 /* Break the message if exceed the buffer size. */
738 *(p-4) = ' ';
739 *(p-3) = '.';
740 *(p-2) = '.';
741 *(p-1) = '.';
742 break;
743 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100744 if (isprint(*msg))
745 *p = *msg;
746 else
747 *p = '.';
748 }
749 *p = '\0';
750
Thierry FOURNIER5554e292015-09-09 11:21:37 +0200751 send_log(px, level, "%s\n", trash.str);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100752 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200753 get_localtime(date.tv_sec, &tm);
754 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100755 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
756 (int)getpid(), trash.str);
757 fflush(stderr);
758 }
759}
760
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100761/* This function just ensure that the yield will be always
762 * returned with a timeout and permit to set some flags
763 */
764__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100765 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100766{
767 struct hlua *hlua = hlua_gethlua(L);
768
769 /* Set the wake timeout. If timeout is required, we set
770 * the expiration time.
771 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200772 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100773
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100774 hlua->flags |= flags;
775
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100776 /* Process the yield. */
777 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
778}
779
Willy Tarreau87b09662015-04-03 00:22:06 +0200780/* This function initialises the Lua environment stored in the stream.
781 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100782 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200783 *
784 * This function is particular. it initialises a new Lua thread. If the
785 * initialisation fails (example: out of memory error), the lua function
786 * throws an error (longjmp).
787 *
788 * This function manipulates two Lua stack: the main and the thread. Only
789 * the main stack can fail. The thread is not manipulated. This function
790 * MUST NOT manipulate the created thread stack state, because is not
791 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100792 */
793int hlua_ctx_init(struct hlua *lua, struct task *task)
794{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200795 if (!SET_SAFE_LJMP(gL.T)) {
796 lua->Tref = LUA_REFNIL;
797 return 0;
798 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100799 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100800 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100801 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100802 lua->T = lua_newthread(gL.T);
803 if (!lua->T) {
804 lua->Tref = LUA_REFNIL;
Thierry FOURNIER0a976202017-07-12 11:18:00 +0200805 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100806 return 0;
807 }
808 hlua_sethlua(lua);
809 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
810 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200811 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100812 return 1;
813}
814
Willy Tarreau87b09662015-04-03 00:22:06 +0200815/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100816 * is destroyed. The destroy also the memory context. The struct "lua"
817 * is not freed.
818 */
819void hlua_ctx_destroy(struct hlua *lua)
820{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100821 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100822 return;
823
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100824 if (!lua->T)
825 goto end;
826
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100827 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +0200828 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100829
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200830 if (!SET_SAFE_LJMP(lua->T))
831 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100832 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200833 RESET_SAFE_LJMP(lua->T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200834
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200835 if (!SET_SAFE_LJMP(gL.T))
836 return;
837 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
838 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200839 /* Forces a garbage collecting process. If the Lua program is finished
840 * without error, we run the GC on the thread pointer. Its freed all
841 * the unused memory.
842 * If the thread is finnish with an error or is currently yielded,
843 * it seems that the GC applied on the thread doesn't clean anything,
844 * so e run the GC on the main thread.
845 * NOTE: maybe this action locks all the Lua threads untiml the en of
846 * the garbage collection.
847 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200848 if (lua->flags & HLUA_MUST_GC) {
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200849 if (!SET_SAFE_LJMP(gL.T))
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200850 return;
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200851 lua_gc(gL.T, LUA_GCCOLLECT, 0);
852 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200853 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200854
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200855 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100856
857end:
858 pool_free2(pool2_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100859}
860
861/* This function is used to restore the Lua context when a coroutine
862 * fails. This function copy the common memory between old coroutine
863 * and the new coroutine. The old coroutine is destroyed, and its
864 * replaced by the new coroutine.
865 * If the flag "keep_msg" is set, the last entry of the old is assumed
866 * as string error message and it is copied in the new stack.
867 */
868static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
869{
870 lua_State *T;
871 int new_ref;
872
873 /* Renew the main LUA stack doesn't have sense. */
874 if (lua == &gL)
875 return 0;
876
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100877 /* New Lua coroutine. */
878 T = lua_newthread(gL.T);
879 if (!T)
880 return 0;
881
882 /* Copy last error message. */
883 if (keep_msg)
884 lua_xmove(lua->T, T, 1);
885
886 /* Copy data between the coroutines. */
887 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
888 lua_xmove(lua->T, T, 1);
889 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
890
891 /* Destroy old data. */
892 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
893
894 /* The thread is garbage collected by Lua. */
895 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
896
897 /* Fill the struct with the new coroutine values. */
898 lua->Mref = new_ref;
899 lua->T = T;
900 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
901
902 /* Set context. */
903 hlua_sethlua(lua);
904
905 return 1;
906}
907
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100908void hlua_hook(lua_State *L, lua_Debug *ar)
909{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100910 struct hlua *hlua = hlua_gethlua(L);
911
912 /* Lua cannot yield when its returning from a function,
913 * so, we can fix the interrupt hook to 1 instruction,
914 * expecting that the function is finnished.
915 */
916 if (lua_gethookmask(L) & LUA_MASKRET) {
917 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
918 return;
919 }
920
921 /* restore the interrupt condition. */
922 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
923
924 /* If we interrupt the Lua processing in yieldable state, we yield.
925 * If the state is not yieldable, trying yield causes an error.
926 */
927 if (lua_isyieldable(L))
928 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
929
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +0100930 /* If we cannot yield, update the clock and check the timeout. */
931 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200932 hlua->run_time += now_ms - hlua->start_time;
933 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100934 lua_pushfstring(L, "execution timeout");
935 WILL_LJMP(lua_error(L));
936 }
937
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200938 /* Update the start time. */
939 hlua->start_time = now_ms;
940
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100941 /* Try to interrupt the process at the end of the current
942 * unyieldable function.
943 */
944 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100945}
946
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100947/* This function start or resumes the Lua stack execution. If the flag
948 * "yield_allowed" if no set and the LUA stack execution returns a yield
949 * The function return an error.
950 *
951 * The function can returns 4 values:
952 * - HLUA_E_OK : The execution is terminated without any errors.
953 * - HLUA_E_AGAIN : The execution must continue at the next associated
954 * task wakeup.
955 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
956 * the top of the stack.
957 * - HLUA_E_ERR : An error has occured without error message.
958 *
959 * If an error occured, the stack is renewed and it is ready to run new
960 * LUA code.
961 */
962static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
963{
964 int ret;
965 const char *msg;
966
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200967 /* Initialise run time counter. */
968 if (!HLUA_IS_RUNNING(lua))
969 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100970
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100971resume_execution:
972
973 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
974 * instructions. it is used for preventing infinite loops.
975 */
976 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
977
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +0100978 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +0200979 HLUA_SET_RUN(lua);
980 HLUA_CLR_CTRLYIELD(lua);
981 HLUA_CLR_WAKERESWR(lua);
982 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +0100983
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200984 /* Update the start time. */
985 lua->start_time = now_ms;
986
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100987 /* Call the function. */
988 ret = lua_resume(lua->T, gL.T, lua->nargs);
989 switch (ret) {
990
991 case LUA_OK:
992 ret = HLUA_E_OK;
993 break;
994
995 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100996 /* Check if the execution timeout is expired. It it is the case, we
997 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100998 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200999 tv_update_date(0, 1);
1000 lua->run_time += now_ms - lua->start_time;
1001 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001002 lua_settop(lua->T, 0); /* Empty the stack. */
1003 if (!lua_checkstack(lua->T, 1)) {
1004 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001005 break;
1006 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001007 lua_pushfstring(lua->T, "execution timeout");
1008 ret = HLUA_E_ERRMSG;
1009 break;
1010 }
1011 /* Process the forced yield. if the general yield is not allowed or
1012 * if no task were associated this the current Lua execution
1013 * coroutine, we resume the execution. Else we want to return in the
1014 * scheduler and we want to be waked up again, to continue the
1015 * current Lua execution. So we schedule our own task.
1016 */
1017 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001018 if (!yield_allowed || !lua->task)
1019 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001020 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001021 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001022 if (!yield_allowed) {
1023 lua_settop(lua->T, 0); /* Empty the stack. */
1024 if (!lua_checkstack(lua->T, 1)) {
1025 ret = HLUA_E_ERR;
1026 break;
1027 }
1028 lua_pushfstring(lua->T, "yield not allowed");
1029 ret = HLUA_E_ERRMSG;
1030 break;
1031 }
1032 ret = HLUA_E_AGAIN;
1033 break;
1034
1035 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001036
1037 /* Special exit case. The traditionnal exit is returned as an error
1038 * because the errors ares the only one mean to return immediately
1039 * from and lua execution.
1040 */
1041 if (lua->flags & HLUA_EXIT) {
1042 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001043 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001044 break;
1045 }
1046
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001047 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001048 if (!lua_checkstack(lua->T, 1)) {
1049 ret = HLUA_E_ERR;
1050 break;
1051 }
1052 msg = lua_tostring(lua->T, -1);
1053 lua_settop(lua->T, 0); /* Empty the stack. */
1054 lua_pop(lua->T, 1);
1055 if (msg)
1056 lua_pushfstring(lua->T, "runtime error: %s", msg);
1057 else
1058 lua_pushfstring(lua->T, "unknown runtime error");
1059 ret = HLUA_E_ERRMSG;
1060 break;
1061
1062 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001063 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001064 lua_settop(lua->T, 0); /* Empty the stack. */
1065 if (!lua_checkstack(lua->T, 1)) {
1066 ret = HLUA_E_ERR;
1067 break;
1068 }
1069 lua_pushfstring(lua->T, "out of memory error");
1070 ret = HLUA_E_ERRMSG;
1071 break;
1072
1073 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001074 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001075 if (!lua_checkstack(lua->T, 1)) {
1076 ret = HLUA_E_ERR;
1077 break;
1078 }
1079 msg = lua_tostring(lua->T, -1);
1080 lua_settop(lua->T, 0); /* Empty the stack. */
1081 lua_pop(lua->T, 1);
1082 if (msg)
1083 lua_pushfstring(lua->T, "message handler error: %s", msg);
1084 else
1085 lua_pushfstring(lua->T, "message handler error");
1086 ret = HLUA_E_ERRMSG;
1087 break;
1088
1089 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001090 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001091 lua_settop(lua->T, 0); /* Empty the stack. */
1092 if (!lua_checkstack(lua->T, 1)) {
1093 ret = HLUA_E_ERR;
1094 break;
1095 }
1096 lua_pushfstring(lua->T, "unknonwn error");
1097 ret = HLUA_E_ERRMSG;
1098 break;
1099 }
1100
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001101 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001102 if (lua->flags & HLUA_MUST_GC &&
1103 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001104 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1105
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001106 switch (ret) {
1107 case HLUA_E_AGAIN:
1108 break;
1109
1110 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001111 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001112 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001113 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001114 break;
1115
1116 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001117 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001118 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001119 hlua_ctx_renew(lua, 0);
1120 break;
1121
1122 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001123 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001124 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001125 break;
1126 }
1127
1128 return ret;
1129}
1130
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001131/* This function exit the current code. */
1132__LJMP static int hlua_done(lua_State *L)
1133{
1134 struct hlua *hlua = hlua_gethlua(L);
1135
1136 hlua->flags |= HLUA_EXIT;
1137 WILL_LJMP(lua_error(L));
1138
1139 return 0;
1140}
1141
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001142/* This function is an LUA binding. It provides a function
1143 * for deleting ACL from a referenced ACL file.
1144 */
1145__LJMP static int hlua_del_acl(lua_State *L)
1146{
1147 const char *name;
1148 const char *key;
1149 struct pat_ref *ref;
1150
1151 MAY_LJMP(check_args(L, 2, "del_acl"));
1152
1153 name = MAY_LJMP(luaL_checkstring(L, 1));
1154 key = MAY_LJMP(luaL_checkstring(L, 2));
1155
1156 ref = pat_ref_lookup(name);
1157 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001158 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001159
1160 pat_ref_delete(ref, key);
1161 return 0;
1162}
1163
1164/* This function is an LUA binding. It provides a function
1165 * for deleting map entry from a referenced map file.
1166 */
1167static int hlua_del_map(lua_State *L)
1168{
1169 const char *name;
1170 const char *key;
1171 struct pat_ref *ref;
1172
1173 MAY_LJMP(check_args(L, 2, "del_map"));
1174
1175 name = MAY_LJMP(luaL_checkstring(L, 1));
1176 key = MAY_LJMP(luaL_checkstring(L, 2));
1177
1178 ref = pat_ref_lookup(name);
1179 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001180 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001181
1182 pat_ref_delete(ref, key);
1183 return 0;
1184}
1185
1186/* This function is an LUA binding. It provides a function
1187 * for adding ACL pattern from a referenced ACL file.
1188 */
1189static int hlua_add_acl(lua_State *L)
1190{
1191 const char *name;
1192 const char *key;
1193 struct pat_ref *ref;
1194
1195 MAY_LJMP(check_args(L, 2, "add_acl"));
1196
1197 name = MAY_LJMP(luaL_checkstring(L, 1));
1198 key = MAY_LJMP(luaL_checkstring(L, 2));
1199
1200 ref = pat_ref_lookup(name);
1201 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001202 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001203
1204 if (pat_ref_find_elt(ref, key) == NULL)
1205 pat_ref_add(ref, key, NULL, NULL);
1206 return 0;
1207}
1208
1209/* This function is an LUA binding. It provides a function
1210 * for setting map pattern and sample from a referenced map
1211 * file.
1212 */
1213static int hlua_set_map(lua_State *L)
1214{
1215 const char *name;
1216 const char *key;
1217 const char *value;
1218 struct pat_ref *ref;
1219
1220 MAY_LJMP(check_args(L, 3, "set_map"));
1221
1222 name = MAY_LJMP(luaL_checkstring(L, 1));
1223 key = MAY_LJMP(luaL_checkstring(L, 2));
1224 value = MAY_LJMP(luaL_checkstring(L, 3));
1225
1226 ref = pat_ref_lookup(name);
1227 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001228 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001229
1230 if (pat_ref_find_elt(ref, key) != NULL)
1231 pat_ref_set(ref, key, value, NULL);
1232 else
1233 pat_ref_add(ref, key, value, NULL);
1234 return 0;
1235}
1236
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001237/* A class is a lot of memory that contain data. This data can be a table,
1238 * an integer or user data. This data is associated with a metatable. This
1239 * metatable have an original version registred in the global context with
1240 * the name of the object (_G[<name>] = <metable> ).
1241 *
1242 * A metable is a table that modify the standard behavior of a standard
1243 * access to the associated data. The entries of this new metatable are
1244 * defined as is:
1245 *
1246 * http://lua-users.org/wiki/MetatableEvents
1247 *
1248 * __index
1249 *
1250 * we access an absent field in a table, the result is nil. This is
1251 * true, but it is not the whole truth. Actually, such access triggers
1252 * the interpreter to look for an __index metamethod: If there is no
1253 * such method, as usually happens, then the access results in nil;
1254 * otherwise, the metamethod will provide the result.
1255 *
1256 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1257 * the key does not appear in the table, but the metatable has an __index
1258 * property:
1259 *
1260 * - if the value is a function, the function is called, passing in the
1261 * table and the key; the return value of that function is returned as
1262 * the result.
1263 *
1264 * - if the value is another table, the value of the key in that table is
1265 * asked for and returned (and if it doesn't exist in that table, but that
1266 * table's metatable has an __index property, then it continues on up)
1267 *
1268 * - Use "rawget(myTable,key)" to skip this metamethod.
1269 *
1270 * http://www.lua.org/pil/13.4.1.html
1271 *
1272 * __newindex
1273 *
1274 * Like __index, but control property assignment.
1275 *
1276 * __mode - Control weak references. A string value with one or both
1277 * of the characters 'k' and 'v' which specifies that the the
1278 * keys and/or values in the table are weak references.
1279 *
1280 * __call - Treat a table like a function. When a table is followed by
1281 * parenthesis such as "myTable( 'foo' )" and the metatable has
1282 * a __call key pointing to a function, that function is invoked
1283 * (passing any specified arguments) and the return value is
1284 * returned.
1285 *
1286 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1287 * called, if the metatable for myTable has a __metatable
1288 * key, the value of that key is returned instead of the
1289 * actual metatable.
1290 *
1291 * __tostring - Control string representation. When the builtin
1292 * "tostring( myTable )" function is called, if the metatable
1293 * for myTable has a __tostring property set to a function,
1294 * that function is invoked (passing myTable to it) and the
1295 * return value is used as the string representation.
1296 *
1297 * __len - Control table length. When the table length is requested using
1298 * the length operator ( '#' ), if the metatable for myTable has
1299 * a __len key pointing to a function, that function is invoked
1300 * (passing myTable to it) and the return value used as the value
1301 * of "#myTable".
1302 *
1303 * __gc - Userdata finalizer code. When userdata is set to be garbage
1304 * collected, if the metatable has a __gc field pointing to a
1305 * function, that function is first invoked, passing the userdata
1306 * to it. The __gc metamethod is not called for tables.
1307 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1308 *
1309 * Special metamethods for redefining standard operators:
1310 * http://www.lua.org/pil/13.1.html
1311 *
1312 * __add "+"
1313 * __sub "-"
1314 * __mul "*"
1315 * __div "/"
1316 * __unm "!"
1317 * __pow "^"
1318 * __concat ".."
1319 *
1320 * Special methods for redfining standar relations
1321 * http://www.lua.org/pil/13.2.html
1322 *
1323 * __eq "=="
1324 * __lt "<"
1325 * __le "<="
1326 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001327
1328/*
1329 *
1330 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001331 * Class Map
1332 *
1333 *
1334 */
1335
1336/* Returns a struct hlua_map if the stack entry "ud" is
1337 * a class session, otherwise it throws an error.
1338 */
1339__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1340{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001341 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001342}
1343
1344/* This function is the map constructor. It don't need
1345 * the class Map object. It creates and return a new Map
1346 * object. It must be called only during "body" or "init"
1347 * context because it process some filesystem accesses.
1348 */
1349__LJMP static int hlua_map_new(struct lua_State *L)
1350{
1351 const char *fn;
1352 int match = PAT_MATCH_STR;
1353 struct sample_conv conv;
1354 const char *file = "";
1355 int line = 0;
1356 lua_Debug ar;
1357 char *err = NULL;
1358 struct arg args[2];
1359
1360 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1361 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1362
1363 fn = MAY_LJMP(luaL_checkstring(L, 1));
1364
1365 if (lua_gettop(L) >= 2) {
1366 match = MAY_LJMP(luaL_checkinteger(L, 2));
1367 if (match < 0 || match >= PAT_MATCH_NUM)
1368 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1369 }
1370
1371 /* Get Lua filename and line number. */
1372 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1373 lua_getinfo(L, "Sl", &ar); /* get info about it */
1374 if (ar.currentline > 0) { /* is there info? */
1375 file = ar.short_src;
1376 line = ar.currentline;
1377 }
1378 }
1379
1380 /* fill fake sample_conv struct. */
1381 conv.kw = ""; /* unused. */
1382 conv.process = NULL; /* unused. */
1383 conv.arg_mask = 0; /* unused. */
1384 conv.val_args = NULL; /* unused. */
1385 conv.out_type = SMP_T_STR;
1386 conv.private = (void *)(long)match;
1387 switch (match) {
1388 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1389 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1390 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1391 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1392 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1393 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1394 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001395 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001396 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1397 default:
1398 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1399 }
1400
1401 /* fill fake args. */
1402 args[0].type = ARGT_STR;
1403 args[0].data.str.str = (char *)fn;
1404 args[1].type = ARGT_STOP;
1405
1406 /* load the map. */
1407 if (!sample_load_map(args, &conv, file, line, &err)) {
1408 /* error case: we cant use luaL_error because we must
1409 * free the err variable.
1410 */
1411 luaL_where(L, 1);
1412 lua_pushfstring(L, "'new': %s.", err);
1413 lua_concat(L, 2);
1414 free(err);
1415 WILL_LJMP(lua_error(L));
1416 }
1417
1418 /* create the lua object. */
1419 lua_newtable(L);
1420 lua_pushlightuserdata(L, args[0].data.map);
1421 lua_rawseti(L, -2, 0);
1422
1423 /* Pop a class Map metatable and affect it to the userdata. */
1424 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1425 lua_setmetatable(L, -2);
1426
1427
1428 return 1;
1429}
1430
1431__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1432{
1433 struct map_descriptor *desc;
1434 struct pattern *pat;
1435 struct sample smp;
1436
1437 MAY_LJMP(check_args(L, 2, "lookup"));
1438 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001439 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001440 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001441 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001442 }
1443 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001444 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001445 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001446 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 +02001447 }
1448
1449 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001450 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001451 if (str)
1452 lua_pushstring(L, "");
1453 else
1454 lua_pushnil(L);
1455 return 1;
1456 }
1457
1458 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001459 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001460 return 1;
1461}
1462
1463__LJMP static int hlua_map_lookup(struct lua_State *L)
1464{
1465 return _hlua_map_lookup(L, 0);
1466}
1467
1468__LJMP static int hlua_map_slookup(struct lua_State *L)
1469{
1470 return _hlua_map_lookup(L, 1);
1471}
1472
1473/*
1474 *
1475 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001476 * Class Socket
1477 *
1478 *
1479 */
1480
1481__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1482{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001483 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001484}
1485
1486/* This function is the handler called for each I/O on the established
1487 * connection. It is used for notify space avalaible to send or data
1488 * received.
1489 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001490static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001491{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001492 struct stream_interface *si = appctx->owner;
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001493 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001494
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001495 if (appctx->ctx.hlua_cosocket.die) {
1496 si_shutw(si);
1497 si_shutr(si);
1498 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001499 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1500 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001501 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1502 }
1503
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001504 /* If the connection object is not avalaible, close all the
1505 * streams and wakeup everithing waiting for.
1506 */
1507 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001508 si_shutw(si);
1509 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001510 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001511 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1512 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001513 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001514 }
1515
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001516 /* If we cant write, wakeup the pending write signals. */
1517 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001518 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001519
1520 /* If we cant read, wakeup the pending read signals. */
1521 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001522 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001523
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001524 /* if the connection is not estabkished, inform the stream that we want
1525 * to be notified whenever the connection completes.
1526 */
1527 if (!(c->flags & CO_FL_CONNECTED)) {
1528 si_applet_cant_get(si);
1529 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001530 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001531 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001532
1533 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001534 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001535
1536 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001537 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001538 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001539
1540 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001541 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001542 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001543}
1544
Willy Tarreau87b09662015-04-03 00:22:06 +02001545/* This function is called when the "struct stream" is destroyed.
1546 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001547 * Wake all the pending signals.
1548 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001549static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001550{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001551 /* Remove my link in the original object. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001552 xref_disconnect(&appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001553
1554 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001555 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1556 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001557}
1558
1559/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001560 * uses this object. If the stream does not exists, just quit.
1561 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001562 * pending signal can rest in the read and write lists. destroy
1563 * it.
1564 */
1565__LJMP static int hlua_socket_gc(lua_State *L)
1566{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001567 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001568 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001569 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001570
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001571 MAY_LJMP(check_args(L, 1, "__gc"));
1572
1573 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001574 peer = xref_get_peer(&socket->xref);
1575 if (!peer) {
1576 xref_disconnect(&socket->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001577 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001578 }
1579 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001580
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001581 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001582 appctx->ctx.hlua_cosocket.die = 1;
1583 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001584
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001585 /* Remove all reference between the Lua stack and the coroutine stream. */
1586 xref_disconnect(&socket->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001587 return 0;
1588}
1589
1590/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001591 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001592 */
1593__LJMP static int hlua_socket_close(lua_State *L)
1594{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001595 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001596 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001597 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001598
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001599 MAY_LJMP(check_args(L, 1, "close"));
1600
1601 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001602 peer = xref_get_peer(&socket->xref);
1603 if (!peer) {
1604 xref_disconnect(&socket->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001605 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001606 }
1607 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001608
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001609 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001610 appctx->ctx.hlua_cosocket.die = 1;
1611 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001612
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001613 /* Remove all reference between the Lua stack and the coroutine stream. */
1614 xref_disconnect(&socket->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001615 return 0;
1616}
1617
1618/* This Lua function assumes that the stack contain three parameters.
1619 * 1 - USERDATA containing a struct socket
1620 * 2 - INTEGER with values of the macro defined below
1621 * If the integer is -1, we must read at most one line.
1622 * If the integer is -2, we ust read all the data until the
1623 * end of the stream.
1624 * If the integer is positive value, we must read a number of
1625 * bytes corresponding to this value.
1626 */
1627#define HLSR_READ_LINE (-1)
1628#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001629__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001630{
1631 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1632 int wanted = lua_tointeger(L, 2);
1633 struct hlua *hlua = hlua_gethlua(L);
1634 struct appctx *appctx;
1635 int len;
1636 int nblk;
1637 char *blk1;
1638 int len1;
1639 char *blk2;
1640 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001641 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001642 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001643 struct stream_interface *si;
1644 struct stream *s;
1645 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001646
1647 /* Check if this lua stack is schedulable. */
1648 if (!hlua || !hlua->task)
1649 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1650 "'frontend', 'backend' or 'task'"));
1651
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001652 /* check for connection break. If some data where read, return it. */
1653 peer = xref_get_peer(&socket->xref);
1654 if (!peer) {
1655 xref_disconnect(&socket->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001656 goto connection_closed;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001657 }
1658 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1659 si = appctx->owner;
1660 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001661
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001662 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001663 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001664 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001665 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001666 if (nblk < 0) /* Connection close. */
1667 goto connection_closed;
1668 if (nblk == 0) /* No data avalaible. */
1669 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001670
1671 /* remove final \r\n. */
1672 if (nblk == 1) {
1673 if (blk1[len1-1] == '\n') {
1674 len1--;
1675 skip_at_end++;
1676 if (blk1[len1-1] == '\r') {
1677 len1--;
1678 skip_at_end++;
1679 }
1680 }
1681 }
1682 else {
1683 if (blk2[len2-1] == '\n') {
1684 len2--;
1685 skip_at_end++;
1686 if (blk2[len2-1] == '\r') {
1687 len2--;
1688 skip_at_end++;
1689 }
1690 }
1691 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001692 }
1693
1694 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001695 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001696 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001697 if (nblk < 0) /* Connection close. */
1698 goto connection_closed;
1699 if (nblk == 0) /* No data avalaible. */
1700 goto connection_empty;
1701 }
1702
1703 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001704 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001705 nblk = bo_getblk_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;
1710
1711 if (len1 > wanted) {
1712 nblk = 1;
1713 len1 = wanted;
1714 } if (nblk == 2 && len1 + len2 > wanted)
1715 len2 = wanted - len1;
1716 }
1717
1718 len = len1;
1719
1720 luaL_addlstring(&socket->b, blk1, len1);
1721 if (nblk == 2) {
1722 len += len2;
1723 luaL_addlstring(&socket->b, blk2, len2);
1724 }
1725
1726 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001727 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001728
1729 /* Don't wait anything. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001730 stream_int_notify(&s->si[0]);
1731 stream_int_update_applet(&s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001732
1733 /* If the pattern reclaim to read all the data
1734 * in the connection, got out.
1735 */
1736 if (wanted == HLSR_READ_ALL)
1737 goto connection_empty;
1738 else if (wanted >= 0 && len < wanted)
1739 goto connection_empty;
1740
1741 /* Return result. */
1742 luaL_pushresult(&socket->b);
1743 return 1;
1744
1745connection_closed:
1746
1747 /* If the buffer containds data. */
1748 if (socket->b.n > 0) {
1749 luaL_pushresult(&socket->b);
1750 return 1;
1751 }
1752 lua_pushnil(L);
1753 lua_pushstring(L, "connection closed.");
1754 return 2;
1755
1756connection_empty:
1757
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001758 appctx = objt_appctx(s->si[0].end);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001759 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001760 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001761 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001762 return 0;
1763}
1764
1765/* This Lus function gets two parameters. The first one can be string
1766 * or a number. If the string is "*l", the user require one line. If
1767 * the string is "*a", the user require all the content of the stream.
1768 * If the value is a number, the user require a number of bytes equal
1769 * to the value. The default value is "*l" (a line).
1770 *
1771 * This paraeter with a variable type is converted in integer. This
1772 * integer takes this values:
1773 * -1 : read a line
1774 * -2 : read all the stream
1775 * >0 : amount if bytes.
1776 *
1777 * The second parameter is optinal. It contains a string that must be
1778 * concatenated with the read data.
1779 */
1780__LJMP static int hlua_socket_receive(struct lua_State *L)
1781{
1782 int wanted = HLSR_READ_LINE;
1783 const char *pattern;
1784 int type;
1785 char *error;
1786 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001787 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001788
1789 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1790 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1791
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001792 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001793
1794 /* check for pattern. */
1795 if (lua_gettop(L) >= 2) {
1796 type = lua_type(L, 2);
1797 if (type == LUA_TSTRING) {
1798 pattern = lua_tostring(L, 2);
1799 if (strcmp(pattern, "*a") == 0)
1800 wanted = HLSR_READ_ALL;
1801 else if (strcmp(pattern, "*l") == 0)
1802 wanted = HLSR_READ_LINE;
1803 else {
1804 wanted = strtoll(pattern, &error, 10);
1805 if (*error != '\0')
1806 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1807 }
1808 }
1809 else if (type == LUA_TNUMBER) {
1810 wanted = lua_tointeger(L, 2);
1811 if (wanted < 0)
1812 WILL_LJMP(luaL_error(L, "Unsupported size."));
1813 }
1814 }
1815
1816 /* Set pattern. */
1817 lua_pushinteger(L, wanted);
1818 lua_replace(L, 2);
1819
1820 /* init bufffer, and fiil it wih prefix. */
1821 luaL_buffinit(L, &socket->b);
1822
1823 /* Check prefix. */
1824 if (lua_gettop(L) >= 3) {
1825 if (lua_type(L, 3) != LUA_TSTRING)
1826 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1827 pattern = lua_tolstring(L, 3, &len);
1828 luaL_addlstring(&socket->b, pattern, len);
1829 }
1830
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001831 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001832}
1833
1834/* Write the Lua input string in the output buffer.
1835 * This fucntion returns a yield if no space are available.
1836 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001837static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001838{
1839 struct hlua_socket *socket;
1840 struct hlua *hlua = hlua_gethlua(L);
1841 struct appctx *appctx;
1842 size_t buf_len;
1843 const char *buf;
1844 int len;
1845 int send_len;
1846 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001847 struct xref *peer;
1848 struct stream_interface *si;
1849 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001850
1851 /* Check if this lua stack is schedulable. */
1852 if (!hlua || !hlua->task)
1853 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1854 "'frontend', 'backend' or 'task'"));
1855
1856 /* Get object */
1857 socket = MAY_LJMP(hlua_checksocket(L, 1));
1858 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001859 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001860
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001861 /* check for connection break. If some data where read, return it. */
1862 peer = xref_get_peer(&socket->xref);
1863 if (!peer) {
1864 xref_disconnect(&socket->xref);
1865 lua_pushinteger(L, -1);
1866 return 1;
1867 }
1868 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1869 si = appctx->owner;
1870 s = si_strm(si);
1871
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001872 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001873 if (channel_output_closed(&s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001874 lua_pushinteger(L, -1);
1875 return 1;
1876 }
1877
1878 /* Update the input buffer data. */
1879 buf += sent;
1880 send_len = buf_len - sent;
1881
1882 /* All the data are sent. */
1883 if (sent >= buf_len)
1884 return 1; /* Implicitly return the length sent. */
1885
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001886 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1887 * the request buffer if its not required.
1888 */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001889 if (s->req.buf->size == 0) {
Christopher Faulet33834b12016-12-19 09:29:06 +01001890 appctx = hlua->task->context;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001891 if (!channel_alloc_buffer(&s->req, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01001892 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001893 }
1894
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001895 /* Check for avalaible space. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001896 len = buffer_total_space(s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01001897 if (len <= 0) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001898 appctx = objt_appctx(s->si[0].end);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001899 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task))
Christopher Faulet33834b12016-12-19 09:29:06 +01001900 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001901 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01001902 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001903
1904 /* send data */
1905 if (len < send_len)
1906 send_len = len;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001907 len = bi_putblk(&s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001908
1909 /* "Not enough space" (-1), "Buffer too little to contain
1910 * the data" (-2) are not expected because the available length
1911 * is tested.
1912 * Other unknown error are also not expected.
1913 */
1914 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001915 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001916 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001917
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001918 MAY_LJMP(hlua_socket_close(L));
1919 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001920 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001921 return 1;
1922 }
1923
1924 /* update buffers. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001925 stream_int_notify(&s->si[0]);
1926 stream_int_update_applet(&s->si[0]);
Willy Tarreaude70fa12015-09-26 11:25:05 +02001927
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001928 s->req.rex = TICK_ETERNITY;
1929 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001930
1931 /* Update length sent. */
1932 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001933 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001934
1935 /* All the data buffer is sent ? */
1936 if (sent + len >= buf_len)
1937 return 1;
1938
1939hlua_socket_write_yield_return:
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001940 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001941 return 0;
1942}
1943
1944/* This function initiate the send of data. It just check the input
1945 * parameters and push an integer in the Lua stack that contain the
1946 * amount of data writed in the buffer. This is used by the function
1947 * "hlua_socket_write_yield" that can yield.
1948 *
1949 * The Lua function gets between 3 and 4 parameters. The first one is
1950 * the associated object. The second is a string buffer. The third is
1951 * a facultative integer that represents where is the buffer position
1952 * of the start of the data that can send. The first byte is the
1953 * position "1". The default value is "1". The fourth argument is a
1954 * facultative integer that represents where is the buffer position
1955 * of the end of the data that can send. The default is the last byte.
1956 */
1957static int hlua_socket_send(struct lua_State *L)
1958{
1959 int i;
1960 int j;
1961 const char *buf;
1962 size_t buf_len;
1963
1964 /* Check number of arguments. */
1965 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1966 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1967
1968 /* Get the string. */
1969 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1970
1971 /* Get and check j. */
1972 if (lua_gettop(L) == 4) {
1973 j = MAY_LJMP(luaL_checkinteger(L, 4));
1974 if (j < 0)
1975 j = buf_len + j + 1;
1976 if (j > buf_len)
1977 j = buf_len + 1;
1978 lua_pop(L, 1);
1979 }
1980 else
1981 j = buf_len;
1982
1983 /* Get and check i. */
1984 if (lua_gettop(L) == 3) {
1985 i = MAY_LJMP(luaL_checkinteger(L, 3));
1986 if (i < 0)
1987 i = buf_len + i + 1;
1988 if (i > buf_len)
1989 i = buf_len + 1;
1990 lua_pop(L, 1);
1991 } else
1992 i = 1;
1993
1994 /* Check bth i and j. */
1995 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001996 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001997 return 1;
1998 }
1999 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002000 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002001 return 1;
2002 }
2003 if (i == 0)
2004 i = 1;
2005 if (j == 0)
2006 j = 1;
2007
2008 /* Pop the string. */
2009 lua_pop(L, 1);
2010
2011 /* Update the buffer length. */
2012 buf += i - 1;
2013 buf_len = j - i + 1;
2014 lua_pushlstring(L, buf, buf_len);
2015
2016 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002017 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002018
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002019 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002020}
2021
Willy Tarreau22b0a682015-06-17 19:43:49 +02002022#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002023__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2024{
2025 static char buffer[SOCKET_INFO_MAX_LEN];
2026 int ret;
2027 int len;
2028 char *p;
2029
2030 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2031 if (ret <= 0) {
2032 lua_pushnil(L);
2033 return 1;
2034 }
2035
2036 if (ret == AF_UNIX) {
2037 lua_pushstring(L, buffer+1);
2038 return 1;
2039 }
2040 else if (ret == AF_INET6) {
2041 buffer[0] = '[';
2042 len = strlen(buffer);
2043 buffer[len] = ']';
2044 len++;
2045 buffer[len] = ':';
2046 len++;
2047 p = buffer;
2048 }
2049 else if (ret == AF_INET) {
2050 p = buffer + 1;
2051 len = strlen(p);
2052 p[len] = ':';
2053 len++;
2054 }
2055 else {
2056 lua_pushnil(L);
2057 return 1;
2058 }
2059
2060 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2061 lua_pushnil(L);
2062 return 1;
2063 }
2064
2065 lua_pushstring(L, p);
2066 return 1;
2067}
2068
2069/* Returns information about the peer of the connection. */
2070__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2071{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002072 struct hlua_socket *socket;
2073 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002074 struct xref *peer;
2075 struct appctx *appctx;
2076 struct stream_interface *si;
2077 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002078
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002079 MAY_LJMP(check_args(L, 1, "getpeername"));
2080
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002081 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002082
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002083 /* check for connection break. If some data where read, return it. */
2084 peer = xref_get_peer(&socket->xref);
2085 if (!peer) {
2086 xref_disconnect(&socket->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002087 lua_pushnil(L);
2088 return 1;
2089 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002090 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2091 si = appctx->owner;
2092 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002093
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002094 conn = objt_conn(s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002095 if (!conn) {
2096 lua_pushnil(L);
2097 return 1;
2098 }
2099
Willy Tarreaua71f6422016-11-16 17:00:14 +01002100 conn_get_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002101 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
Willy Tarreaua71f6422016-11-16 17:00:14 +01002102 lua_pushnil(L);
2103 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002104 }
2105
2106 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2107}
2108
2109/* Returns information about my connection side. */
2110static int hlua_socket_getsockname(struct lua_State *L)
2111{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002112 struct hlua_socket *socket;
2113 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002114 struct appctx *appctx;
2115 struct xref *peer;
2116 struct stream_interface *si;
2117 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002118
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002119 MAY_LJMP(check_args(L, 1, "getsockname"));
2120
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002121 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002122
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002123 /* check for connection break. If some data where read, return it. */
2124 peer = xref_get_peer(&socket->xref);
2125 if (!peer) {
2126 xref_disconnect(&socket->xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002127 lua_pushnil(L);
2128 return 1;
2129 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002130 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2131 si = appctx->owner;
2132 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002133
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002134 conn = objt_conn(s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002135 if (!conn) {
2136 lua_pushnil(L);
2137 return 1;
2138 }
2139
Willy Tarreaua71f6422016-11-16 17:00:14 +01002140 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002141 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Willy Tarreaua71f6422016-11-16 17:00:14 +01002142 lua_pushnil(L);
2143 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002144 }
2145
2146 return hlua_socket_info(L, &conn->addr.from);
2147}
2148
2149/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002150static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002151 .obj_type = OBJ_TYPE_APPLET,
2152 .name = "<LUA_TCP>",
2153 .fct = hlua_socket_handler,
2154 .release = hlua_socket_release,
2155};
2156
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002157__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002158{
2159 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2160 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002161 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002162 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002163 struct stream_interface *si;
2164 struct stream *s;
2165
2166 /* check for connection break. If some data where read, return it. */
2167 peer = xref_get_peer(&socket->xref);
2168 if (!peer) {
2169 xref_disconnect(&socket->xref);
2170 lua_pushnil(L);
2171 lua_pushstring(L, "Can't connect");
2172 return 2;
2173 }
2174 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2175 si = appctx->owner;
2176 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002177
2178 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002179 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002180 lua_pushnil(L);
2181 lua_pushstring(L, "Can't connect");
2182 return 2;
2183 }
2184
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002185 appctx = objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002186
2187 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002188 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002189 lua_pushinteger(L, 1);
2190 return 1;
2191 }
2192
Thierry FOURNIERd6975962017-07-12 14:31:10 +02002193 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002194 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002195 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002196 return 0;
2197}
2198
2199/* This function fail or initite the connection. */
2200__LJMP static int hlua_socket_connect(struct lua_State *L)
2201{
2202 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002203 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002204 const char *ip;
2205 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002206 struct hlua *hlua;
2207 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002208 int low, high;
2209 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002210 struct xref *peer;
2211 struct stream_interface *si;
2212 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002213
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002214 if (lua_gettop(L) < 2)
2215 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002216
2217 /* Get args. */
2218 socket = MAY_LJMP(hlua_checksocket(L, 1));
2219 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002220 if (lua_gettop(L) >= 3)
2221 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002222
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002223 /* check for connection break. If some data where read, return it. */
2224 peer = xref_get_peer(&socket->xref);
2225 if (!peer) {
2226 xref_disconnect(&socket->xref);
2227 lua_pushnil(L);
2228 return 1;
2229 }
2230 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2231 si = appctx->owner;
2232 s = si_strm(si);
2233
2234 /* Initialise connection. */
2235 conn = si_alloc_conn(&s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002236 if (!conn)
2237 WILL_LJMP(luaL_error(L, "connect: internal error"));
2238
Willy Tarreau3adac082015-09-26 17:51:09 +02002239 /* needed for the connection not to be closed */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002240 conn->target = s->target;
Willy Tarreau3adac082015-09-26 17:51:09 +02002241
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002242 /* Parse ip address. */
Willy Tarreau48ef4c92017-01-06 18:32:38 +01002243 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, 0);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002244 if (!addr)
2245 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
2246 if (low != high)
2247 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
2248 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002249
2250 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002251 if (low == 0) {
2252 if (conn->addr.to.ss_family == AF_INET) {
2253 if (port == -1)
2254 WILL_LJMP(luaL_error(L, "connect: port missing"));
2255 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2256 } else if (conn->addr.to.ss_family == AF_INET6) {
2257 if (port == -1)
2258 WILL_LJMP(luaL_error(L, "connect: port missing"));
2259 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2260 }
2261 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002262
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002263 hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002264 appctx = objt_appctx(s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002265
2266 /* inform the stream that we want to be notified whenever the
2267 * connection completes.
2268 */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002269 si_applet_cant_get(&s->si[0]);
2270 si_applet_cant_put(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002271 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002272
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002273 hlua->flags |= HLUA_MUST_GC;
2274
Thierry FOURNIERd6975962017-07-12 14:31:10 +02002275 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task))
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002276 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002277 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002278
2279 return 0;
2280}
2281
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002282#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002283__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2284{
2285 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002286 struct xref *peer;
2287 struct appctx *appctx;
2288 struct stream_interface *si;
2289 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002290
2291 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2292 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002293
2294 /* check for connection break. If some data where read, return it. */
2295 peer = xref_get_peer(&socket->xref);
2296 if (!peer) {
2297 xref_disconnect(&socket->xref);
2298 lua_pushnil(L);
2299 return 1;
2300 }
2301 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2302 si = appctx->owner;
2303 s = si_strm(si);
2304
2305 s->target = &socket_ssl.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002306 return MAY_LJMP(hlua_socket_connect(L));
2307}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002308#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002309
2310__LJMP static int hlua_socket_setoption(struct lua_State *L)
2311{
2312 return 0;
2313}
2314
2315__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2316{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002317 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002318 int tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002319 struct xref *peer;
2320 struct appctx *appctx;
2321 struct stream_interface *si;
2322 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002323
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002324 MAY_LJMP(check_args(L, 2, "settimeout"));
2325
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002326 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002327 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002328
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002329 /* check for connection break. If some data where read, return it. */
2330 peer = xref_get_peer(&socket->xref);
2331 if (!peer) {
2332 xref_disconnect(&socket->xref);
2333 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2334 WILL_LJMP(lua_error(L));
2335 return 0;
2336 }
2337 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2338 si = appctx->owner;
2339 s = si_strm(si);
2340
2341 s->req.rto = tmout;
2342 s->req.wto = tmout;
2343 s->res.rto = tmout;
2344 s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002345
2346 return 0;
2347}
2348
2349__LJMP static int hlua_socket_new(lua_State *L)
2350{
2351 struct hlua_socket *socket;
2352 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002353 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002354 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002355
2356 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002357 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002358 hlua_pusherror(L, "socket: full stack");
2359 goto out_fail_conf;
2360 }
2361
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002362 /* Create the object: obj[0] = userdata. */
2363 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002364 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002365 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002366 memset(socket, 0, sizeof(*socket));
2367
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002368 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002369 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002370 hlua_pusherror(L, "socket: uninitialized pools.");
2371 goto out_fail_conf;
2372 }
2373
Willy Tarreau87b09662015-04-03 00:22:06 +02002374 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002375 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2376 lua_setmetatable(L, -2);
2377
Willy Tarreaud420a972015-04-06 00:39:18 +02002378 /* Create the applet context */
2379 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002380 if (!appctx) {
2381 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002382 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002383 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002384
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002385 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002386 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002387 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2388 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002389
Willy Tarreaud420a972015-04-06 00:39:18 +02002390 /* Now create a session, task and stream for this applet */
2391 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2392 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002393 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002394 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002395 }
2396
Willy Tarreau87787ac2017-08-28 16:22:54 +02002397 strm = stream_new(sess, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002398 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002399 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002400 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002401 }
2402
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002403 /* Initialise cross reference between stream and Lua socket object. */
2404 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002405
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002406 /* Configure "right" stream interface. this "si" is used to connect
2407 * and retrieve data from the server. The connection is initialized
2408 * with the "struct server".
2409 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002410 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002411
2412 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002413 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2414 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002415
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002416 /* Update statistics counters. */
2417 socket_proxy.feconn++; /* beconn will be increased later */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002418 totalconn++;
2419
Willy Tarreau87787ac2017-08-28 16:22:54 +02002420 task_wakeup(strm->task, TASK_WOKEN_INIT);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002421 /* Return yield waiting for connection. */
2422 return 1;
2423
Willy Tarreaud420a972015-04-06 00:39:18 +02002424 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002425 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002426 out_fail_sess:
2427 appctx_free(appctx);
2428 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002429 WILL_LJMP(lua_error(L));
2430 return 0;
2431}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002432
2433/*
2434 *
2435 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002436 * Class Channel
2437 *
2438 *
2439 */
2440
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002441/* The state between the channel data and the HTTP parser state can be
2442 * unconsistent, so reset the parser and call it again. Warning, this
2443 * action not revalidate the request and not send a 400 if the modified
2444 * resuest is not valid.
2445 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002446 * This function never fails. The direction is set using dir, which equals
2447 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002448 */
2449static void hlua_resynchonize_proto(struct stream *stream, int dir)
2450{
2451 /* Protocol HTTP. */
2452 if (stream->be->mode == PR_MODE_HTTP) {
2453
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002454 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002455 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002456 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002457 http_txn_reset_res(stream->txn);
2458
2459 if (stream->txn->hdr_idx.v)
2460 hdr_idx_init(&stream->txn->hdr_idx);
2461
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002462 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002463 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002464 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002465 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2466 }
2467}
2468
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002469/* This function is called before the Lua execution. It stores
2470 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002471 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002472static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002473{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002474 c->mode = stream->be->mode;
2475 switch (c->mode) {
2476 case PR_MODE_HTTP:
2477 c->data.http.dir = opt & SMP_OPT_DIR;
2478 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2479 c->data.http.state = stream->txn->req.msg_state;
2480 else
2481 c->data.http.state = stream->txn->rsp.msg_state;
2482 break;
2483 default:
2484 break;
2485 }
2486}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002487
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002488/* This function is called after the Lua execution. it
2489 * returns true if the parser state is consistent, otherwise,
2490 * it return false.
2491 *
2492 * In HTTP mode, the parser state must be in the same state
2493 * or greater when we exit the function. Even if we do a
2494 * control yield. This prevent to break the HTTP message
2495 * from the Lua code.
2496 */
2497static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2498{
2499 if (c->mode != stream->be->mode)
2500 return 0;
2501
2502 switch (c->mode) {
2503 case PR_MODE_HTTP:
2504 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002505 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002506 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2507 return stream->txn->req.msg_state >= c->data.http.state;
2508 else
2509 return stream->txn->rsp.msg_state >= c->data.http.state;
2510 default:
2511 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002512 }
2513 return 1;
2514}
2515
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002516/* Returns the struct hlua_channel join to the class channel in the
2517 * stack entry "ud" or throws an argument error.
2518 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002519__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002520{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002521 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002522}
2523
Willy Tarreau47860ed2015-03-10 14:07:50 +01002524/* Pushes the channel onto the top of the stack. If the stask does not have a
2525 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002526 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002527static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002528{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002529 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002530 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002531 return 0;
2532
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002533 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002534 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002535 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002536
2537 /* Pop a class sesison metatable and affect it to the userdata. */
2538 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2539 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002540 return 1;
2541}
2542
2543/* Duplicate all the data present in the input channel and put it
2544 * in a string LUA variables. Returns -1 and push a nil value in
2545 * the stack if the channel is closed and all the data are consumed,
2546 * returns 0 if no data are available, otherwise it returns the length
2547 * of the builded string.
2548 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002549static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002550{
2551 char *blk1;
2552 char *blk2;
2553 int len1;
2554 int len2;
2555 int ret;
2556 luaL_Buffer b;
2557
Willy Tarreau47860ed2015-03-10 14:07:50 +01002558 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002559 if (unlikely(ret == 0))
2560 return 0;
2561
2562 if (unlikely(ret < 0)) {
2563 lua_pushnil(L);
2564 return -1;
2565 }
2566
2567 luaL_buffinit(L, &b);
2568 luaL_addlstring(&b, blk1, len1);
2569 if (unlikely(ret == 2))
2570 luaL_addlstring(&b, blk2, len2);
2571 luaL_pushresult(&b);
2572
2573 if (unlikely(ret == 2))
2574 return len1 + len2;
2575 return len1;
2576}
2577
2578/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2579 * a yield. This function keep the data in the buffer.
2580 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002581__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002582{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002583 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002584
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002585 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2586
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002587 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002588 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002589 return 1;
2590}
2591
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002592/* Check arguments for the function "hlua_channel_dup_yield". */
2593__LJMP static int hlua_channel_dup(lua_State *L)
2594{
2595 MAY_LJMP(check_args(L, 1, "dup"));
2596 MAY_LJMP(hlua_checkchannel(L, 1));
2597 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2598}
2599
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002600/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2601 * a yield. This function consumes the data in the buffer. It returns
2602 * a string containing the data or a nil pointer if no data are available
2603 * and the channel is closed.
2604 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002605__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002606{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002607 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002608 int ret;
2609
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002610 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002611
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002612 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002613 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002614 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002615
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002616 if (unlikely(ret == -1))
2617 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002618
Willy Tarreau47860ed2015-03-10 14:07:50 +01002619 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002620 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002621 return 1;
2622}
2623
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002624/* Check arguments for the fucntion "hlua_channel_get_yield". */
2625__LJMP static int hlua_channel_get(lua_State *L)
2626{
2627 MAY_LJMP(check_args(L, 1, "get"));
2628 MAY_LJMP(hlua_checkchannel(L, 1));
2629 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2630}
2631
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002632/* This functions consumes and returns one line. If the channel is closed,
2633 * and the last data does not contains a final '\n', the data are returned
2634 * without the final '\n'. When no more data are avalaible, it returns nil
2635 * value.
2636 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002637__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002638{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002639 char *blk1;
2640 char *blk2;
2641 int len1;
2642 int len2;
2643 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002644 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002645 int ret;
2646 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002647
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002648 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2649
Willy Tarreau47860ed2015-03-10 14:07:50 +01002650 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002651 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002652 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002653
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002654 if (ret == -1) {
2655 lua_pushnil(L);
2656 return 1;
2657 }
2658
2659 luaL_buffinit(L, &b);
2660 luaL_addlstring(&b, blk1, len1);
2661 len = len1;
2662 if (unlikely(ret == 2)) {
2663 luaL_addlstring(&b, blk2, len2);
2664 len += len2;
2665 }
2666 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002667 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002668 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002669 return 1;
2670}
2671
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002672/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2673__LJMP static int hlua_channel_getline(lua_State *L)
2674{
2675 MAY_LJMP(check_args(L, 1, "getline"));
2676 MAY_LJMP(hlua_checkchannel(L, 1));
2677 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2678}
2679
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002680/* This function takes a string as input, and append it at the
2681 * input side of channel. If the data is too big, but a space
2682 * is probably available after sending some data, the function
2683 * yield. If the data is bigger than the buffer, or if the
2684 * channel is closed, it returns -1. otherwise, it returns the
2685 * amount of data writed.
2686 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002687__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002688{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002689 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002690 size_t len;
2691 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2692 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2693 int ret;
2694 int max;
2695
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002696 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2697 * the request buffer if its not required.
2698 */
2699 if (chn->buf->size == 0) {
2700 si_applet_cant_put(chn_prod(chn));
2701 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
2702 }
2703
Willy Tarreau47860ed2015-03-10 14:07:50 +01002704 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002705 if (max > len - l)
2706 max = len - l;
2707
Willy Tarreau47860ed2015-03-10 14:07:50 +01002708 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002709 if (ret == -2 || ret == -3) {
2710 lua_pushinteger(L, -1);
2711 return 1;
2712 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002713 if (ret == -1) {
2714 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002715 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002716 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002717 l += ret;
2718 lua_pop(L, 1);
2719 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002720 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002721
Willy Tarreau47860ed2015-03-10 14:07:50 +01002722 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2723 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002724 /* There are no space avalaible, and the output buffer is empty.
2725 * in this case, we cannot add more data, so we cannot yield,
2726 * we return the amount of copyied data.
2727 */
2728 return 1;
2729 }
2730 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002731 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002732 return 1;
2733}
2734
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002735/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002736 * of the writed string, or -1 if the channel is closed or if the
2737 * buffer size is too little for the data.
2738 */
2739__LJMP static int hlua_channel_append(lua_State *L)
2740{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002741 size_t len;
2742
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002743 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002744 MAY_LJMP(hlua_checkchannel(L, 1));
2745 MAY_LJMP(luaL_checklstring(L, 2, &len));
2746 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002747 lua_pushinteger(L, 0);
2748
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002749 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002750}
2751
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002752/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002753 * his process by cleaning the buffer. The result is a replacement
2754 * of the current data. It returns the length of the writed string,
2755 * or -1 if the channel is closed or if the buffer size is too
2756 * little for the data.
2757 */
2758__LJMP static int hlua_channel_set(lua_State *L)
2759{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002760 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002761
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002762 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002763 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002764 lua_pushinteger(L, 0);
2765
Willy Tarreau47860ed2015-03-10 14:07:50 +01002766 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002767
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002768 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002769}
2770
2771/* Append data in the output side of the buffer. This data is immediatly
2772 * sent. The fcuntion returns the ammount of data writed. If the buffer
2773 * cannot contains the data, the function yield. The function returns -1
2774 * if the channel is closed.
2775 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002776__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002777{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002778 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002779 size_t len;
2780 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2781 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2782 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002783 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002784
Willy Tarreau47860ed2015-03-10 14:07:50 +01002785 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002786 lua_pushinteger(L, -1);
2787 return 1;
2788 }
2789
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002790 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2791 * the request buffer if its not required.
2792 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002793 if (chn->buf->size == 0) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002794 si_applet_cant_put(chn_prod(chn));
2795 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002796 }
2797
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002798 /* the writed data will be immediatly sent, so we can check
2799 * the avalaible space without taking in account the reserve.
2800 * The reserve is guaranted for the processing of incoming
2801 * data, because the buffer will be flushed.
2802 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002803 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002804
2805 /* If there are no space avalaible, and the output buffer is empty.
2806 * in this case, we cannot add more data, so we cannot yield,
2807 * we return the amount of copyied data.
2808 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002809 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002810 return 1;
2811
2812 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002813 if (max > len - l)
2814 max = len - l;
2815
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002816 /* The buffer avalaible size may be not contiguous. This test
2817 * detects a non contiguous buffer and realign it.
2818 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002819 if (bi_space_for_replace(chn->buf) < max)
2820 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002821
2822 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002823 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002824
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002825 /* buffer replace considers that the input part is filled.
2826 * so, I must forward these new data in the output part.
2827 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002828 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002829
2830 l += max;
2831 lua_pop(L, 1);
2832 lua_pushinteger(L, l);
2833
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002834 /* If there are no space avalaible, and the output buffer is empty.
2835 * in this case, we cannot add more data, so we cannot yield,
2836 * we return the amount of copyied data.
2837 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002838 max = chn->buf->size - buffer_len(chn->buf);
2839 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002840 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002841
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002842 if (l < len) {
2843 /* If we are waiting for space in the response buffer, we
2844 * must set the flag WAKERESWR. This flag required the task
2845 * wake up if any activity is detected on the response buffer.
2846 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002847 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002848 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002849 else
2850 HLUA_SET_WAKEREQWR(hlua);
2851 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002852 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002853
2854 return 1;
2855}
2856
2857/* Just a wraper of "_hlua_channel_send". This wrapper permits
2858 * yield the LUA process, and resume it without checking the
2859 * input arguments.
2860 */
2861__LJMP static int hlua_channel_send(lua_State *L)
2862{
2863 MAY_LJMP(check_args(L, 2, "send"));
2864 lua_pushinteger(L, 0);
2865
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002866 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002867}
2868
2869/* This function forward and amount of butes. The data pass from
2870 * the input side of the buffer to the output side, and can be
2871 * forwarded. This function never fails.
2872 *
2873 * The Lua function takes an amount of bytes to be forwarded in
2874 * imput. It returns the number of bytes forwarded.
2875 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002876__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002877{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002878 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002879 int len;
2880 int l;
2881 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002882 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002883
2884 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2885 len = MAY_LJMP(luaL_checkinteger(L, 2));
2886 l = MAY_LJMP(luaL_checkinteger(L, -1));
2887
2888 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002889 if (max > chn->buf->i)
2890 max = chn->buf->i;
2891 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002892 l += max;
2893
2894 lua_pop(L, 1);
2895 lua_pushinteger(L, l);
2896
2897 /* Check if it miss bytes to forward. */
2898 if (l < len) {
2899 /* The the input channel or the output channel are closed, we
2900 * must return the amount of data forwarded.
2901 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002902 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002903 return 1;
2904
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002905 /* If we are waiting for space data in the response buffer, we
2906 * must set the flag WAKERESWR. This flag required the task
2907 * wake up if any activity is detected on the response buffer.
2908 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002909 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002910 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002911 else
2912 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002913
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002914 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002915 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002916 }
2917
2918 return 1;
2919}
2920
2921/* Just check the input and prepare the stack for the previous
2922 * function "hlua_channel_forward_yield"
2923 */
2924__LJMP static int hlua_channel_forward(lua_State *L)
2925{
2926 MAY_LJMP(check_args(L, 2, "forward"));
2927 MAY_LJMP(hlua_checkchannel(L, 1));
2928 MAY_LJMP(luaL_checkinteger(L, 2));
2929
2930 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002931 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002932}
2933
2934/* Just returns the number of bytes available in the input
2935 * side of the buffer. This function never fails.
2936 */
2937__LJMP static int hlua_channel_get_in_len(lua_State *L)
2938{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002939 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002940
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002941 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002942 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002943 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002944 return 1;
2945}
2946
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01002947/* Returns true if the channel is full. */
2948__LJMP static int hlua_channel_is_full(lua_State *L)
2949{
2950 struct channel *chn;
2951 int rem;
2952
2953 MAY_LJMP(check_args(L, 1, "is_full"));
2954 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2955
2956 rem = chn->buf->size;
2957 rem -= chn->buf->o; /* Output size */
2958 rem -= chn->buf->i; /* Input size */
2959 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
2960
2961 lua_pushboolean(L, rem <= 0);
2962 return 1;
2963}
2964
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002965/* Just returns the number of bytes available in the output
2966 * side of the buffer. This function never fails.
2967 */
2968__LJMP static int hlua_channel_get_out_len(lua_State *L)
2969{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002970 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002971
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002972 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002973 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002974 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002975 return 1;
2976}
2977
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002978/*
2979 *
2980 *
2981 * Class Fetches
2982 *
2983 *
2984 */
2985
2986/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002987 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002988 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002989__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002990{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002991 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002992}
2993
2994/* This function creates and push in the stack a fetch object according
2995 * with a current TXN.
2996 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002997static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002998{
Willy Tarreau7073c472015-04-06 11:15:40 +02002999 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003000
3001 /* Check stack size. */
3002 if (!lua_checkstack(L, 3))
3003 return 0;
3004
3005 /* Create the object: obj[0] = userdata.
3006 * Note that the base of the Fetches object is the
3007 * transaction object.
3008 */
3009 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003010 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003011 lua_rawseti(L, -2, 0);
3012
Willy Tarreau7073c472015-04-06 11:15:40 +02003013 hsmp->s = txn->s;
3014 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003015 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003016 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003017
3018 /* Pop a class sesison metatable and affect it to the userdata. */
3019 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3020 lua_setmetatable(L, -2);
3021
3022 return 1;
3023}
3024
3025/* This function is an LUA binding. It is called with each sample-fetch.
3026 * It uses closure argument to store the associated sample-fetch. It
3027 * returns only one argument or throws an error. An error is thrown
3028 * only if an error is encountered during the argument parsing. If
3029 * the "sample-fetch" function fails, nil is returned.
3030 */
3031__LJMP static int hlua_run_sample_fetch(lua_State *L)
3032{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003033 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003034 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003035 struct arg args[ARGM_NBARGS + 1];
3036 int i;
3037 struct sample smp;
3038
3039 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003040 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003041
3042 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003043 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003044
Thierry FOURNIERca988662015-12-20 18:43:03 +01003045 /* Check execution authorization. */
3046 if (f->use & SMP_USE_HTTP_ANY &&
3047 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3048 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3049 "is not available in Lua services", f->kw);
3050 WILL_LJMP(lua_error(L));
3051 }
3052
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003053 /* Get extra arguments. */
3054 for (i = 0; i < lua_gettop(L) - 1; i++) {
3055 if (i >= ARGM_NBARGS)
3056 break;
3057 hlua_lua2arg(L, i + 2, &args[i]);
3058 }
3059 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003060 args[i].data.str.str = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003061
3062 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003063 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003064
3065 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003066 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003067 lua_pushfstring(L, "error in arguments");
3068 WILL_LJMP(lua_error(L));
3069 }
3070
3071 /* Initialise the sample. */
3072 memset(&smp, 0, sizeof(smp));
3073
3074 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003075 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003076 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003077 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003078 lua_pushstring(L, "");
3079 else
3080 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003081 return 1;
3082 }
3083
3084 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003085 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003086 hlua_smp2lua_str(L, &smp);
3087 else
3088 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003089 return 1;
3090}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003091
3092/*
3093 *
3094 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003095 * Class Converters
3096 *
3097 *
3098 */
3099
3100/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003101 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003102 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003103__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003104{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003105 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003106}
3107
3108/* This function creates and push in the stack a Converters object
3109 * according with a current TXN.
3110 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003111static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003112{
Willy Tarreau7073c472015-04-06 11:15:40 +02003113 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003114
3115 /* Check stack size. */
3116 if (!lua_checkstack(L, 3))
3117 return 0;
3118
3119 /* Create the object: obj[0] = userdata.
3120 * Note that the base of the Converters object is the
3121 * same than the TXN object.
3122 */
3123 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003124 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003125 lua_rawseti(L, -2, 0);
3126
Willy Tarreau7073c472015-04-06 11:15:40 +02003127 hsmp->s = txn->s;
3128 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003129 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003130 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003131
Willy Tarreau87b09662015-04-03 00:22:06 +02003132 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003133 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3134 lua_setmetatable(L, -2);
3135
3136 return 1;
3137}
3138
3139/* This function is an LUA binding. It is called with each converter.
3140 * It uses closure argument to store the associated converter. It
3141 * returns only one argument or throws an error. An error is thrown
3142 * only if an error is encountered during the argument parsing. If
3143 * the converter function function fails, nil is returned.
3144 */
3145__LJMP static int hlua_run_sample_conv(lua_State *L)
3146{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003147 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003148 struct sample_conv *conv;
3149 struct arg args[ARGM_NBARGS + 1];
3150 int i;
3151 struct sample smp;
3152
3153 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003154 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003155
3156 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003157 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003158
3159 /* Get extra arguments. */
3160 for (i = 0; i < lua_gettop(L) - 2; i++) {
3161 if (i >= ARGM_NBARGS)
3162 break;
3163 hlua_lua2arg(L, i + 3, &args[i]);
3164 }
3165 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003166 args[i].data.str.str = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003167
3168 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003169 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003170
3171 /* Run the special args checker. */
3172 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3173 hlua_pusherror(L, "error in arguments");
3174 WILL_LJMP(lua_error(L));
3175 }
3176
3177 /* Initialise the sample. */
3178 if (!hlua_lua2smp(L, 2, &smp)) {
3179 hlua_pusherror(L, "error in the input argument");
3180 WILL_LJMP(lua_error(L));
3181 }
3182
Willy Tarreau1777ea62016-03-10 16:15:46 +01003183 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3184
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003185 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003186 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003187 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003188 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003189 WILL_LJMP(lua_error(L));
3190 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003191 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3192 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003193 hlua_pusherror(L, "error during the input argument casting");
3194 WILL_LJMP(lua_error(L));
3195 }
3196
3197 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003198 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003199 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003200 lua_pushstring(L, "");
3201 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003202 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003203 return 1;
3204 }
3205
3206 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003207 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003208 hlua_smp2lua_str(L, &smp);
3209 else
3210 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003211 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003212}
3213
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003214/*
3215 *
3216 *
3217 * Class AppletTCP
3218 *
3219 *
3220 */
3221
3222/* Returns a struct hlua_txn if the stack entry "ud" is
3223 * a class stream, otherwise it throws an error.
3224 */
3225__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3226{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003227 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003228}
3229
3230/* This function creates and push in the stack an Applet object
3231 * according with a current TXN.
3232 */
3233static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3234{
3235 struct hlua_appctx *appctx;
3236 struct stream_interface *si = ctx->owner;
3237 struct stream *s = si_strm(si);
3238 struct proxy *p = s->be;
3239
3240 /* Check stack size. */
3241 if (!lua_checkstack(L, 3))
3242 return 0;
3243
3244 /* Create the object: obj[0] = userdata.
3245 * Note that the base of the Converters object is the
3246 * same than the TXN object.
3247 */
3248 lua_newtable(L);
3249 appctx = lua_newuserdata(L, sizeof(*appctx));
3250 lua_rawseti(L, -2, 0);
3251 appctx->appctx = ctx;
3252 appctx->htxn.s = s;
3253 appctx->htxn.p = p;
3254
3255 /* Create the "f" field that contains a list of fetches. */
3256 lua_pushstring(L, "f");
3257 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3258 return 0;
3259 lua_settable(L, -3);
3260
3261 /* Create the "sf" field that contains a list of stringsafe fetches. */
3262 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003263 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003264 return 0;
3265 lua_settable(L, -3);
3266
3267 /* Create the "c" field that contains a list of converters. */
3268 lua_pushstring(L, "c");
3269 if (!hlua_converters_new(L, &appctx->htxn, 0))
3270 return 0;
3271 lua_settable(L, -3);
3272
3273 /* Create the "sc" field that contains a list of stringsafe converters. */
3274 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003275 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003276 return 0;
3277 lua_settable(L, -3);
3278
3279 /* Pop a class stream metatable and affect it to the table. */
3280 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3281 lua_setmetatable(L, -2);
3282
3283 return 1;
3284}
3285
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003286__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3287{
3288 struct hlua_appctx *appctx;
3289 struct stream *s;
3290 const char *name;
3291 size_t len;
3292 struct sample smp;
3293
3294 MAY_LJMP(check_args(L, 3, "set_var"));
3295
3296 /* It is useles to retrieve the stream, but this function
3297 * runs only in a stream context.
3298 */
3299 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3300 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3301 s = appctx->htxn.s;
3302
3303 /* Converts the third argument in a sample. */
3304 hlua_lua2smp(L, 3, &smp);
3305
3306 /* Store the sample in a variable. */
3307 smp_set_owner(&smp, s->be, s->sess, s, 0);
3308 vars_set_by_name(name, len, &smp);
3309 return 0;
3310}
3311
3312__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3313{
3314 struct hlua_appctx *appctx;
3315 struct stream *s;
3316 const char *name;
3317 size_t len;
3318 struct sample smp;
3319
3320 MAY_LJMP(check_args(L, 2, "unset_var"));
3321
3322 /* It is useles to retrieve the stream, but this function
3323 * runs only in a stream context.
3324 */
3325 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3326 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3327 s = appctx->htxn.s;
3328
3329 /* Unset the variable. */
3330 smp_set_owner(&smp, s->be, s->sess, s, 0);
3331 vars_unset_by_name(name, len, &smp);
3332 return 0;
3333}
3334
3335__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3336{
3337 struct hlua_appctx *appctx;
3338 struct stream *s;
3339 const char *name;
3340 size_t len;
3341 struct sample smp;
3342
3343 MAY_LJMP(check_args(L, 2, "get_var"));
3344
3345 /* It is useles to retrieve the stream, but this function
3346 * runs only in a stream context.
3347 */
3348 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3349 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3350 s = appctx->htxn.s;
3351
3352 smp_set_owner(&smp, s->be, s->sess, s, 0);
3353 if (!vars_get_by_name(name, len, &smp)) {
3354 lua_pushnil(L);
3355 return 1;
3356 }
3357
3358 return hlua_smp2lua(L, &smp);
3359}
3360
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003361__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3362{
3363 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3364 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003365 struct hlua *hlua;
3366
3367 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003368 if (!s->hlua)
3369 return 0;
3370 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003371
3372 MAY_LJMP(check_args(L, 2, "set_priv"));
3373
3374 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003375 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003376
3377 /* Get and store new value. */
3378 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3379 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3380
3381 return 0;
3382}
3383
3384__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3385{
3386 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3387 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003388 struct hlua *hlua;
3389
3390 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003391 if (!s->hlua) {
3392 lua_pushnil(L);
3393 return 1;
3394 }
3395 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003396
3397 /* Push configuration index in the stack. */
3398 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3399
3400 return 1;
3401}
3402
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003403/* If expected data not yet available, it returns a yield. This function
3404 * consumes the data in the buffer. It returns a string containing the
3405 * data. This string can be empty.
3406 */
3407__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3408{
3409 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3410 struct stream_interface *si = appctx->appctx->owner;
3411 int ret;
3412 char *blk1;
3413 int len1;
3414 char *blk2;
3415 int len2;
3416
3417 /* Read the maximum amount of data avalaible. */
3418 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3419
3420 /* Data not yet avalaible. return yield. */
3421 if (ret == 0) {
3422 si_applet_cant_get(si);
3423 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3424 }
3425
3426 /* End of data: commit the total strings and return. */
3427 if (ret < 0) {
3428 luaL_pushresult(&appctx->b);
3429 return 1;
3430 }
3431
3432 /* Ensure that the block 2 length is usable. */
3433 if (ret == 1)
3434 len2 = 0;
3435
3436 /* dont check the max length read and dont check. */
3437 luaL_addlstring(&appctx->b, blk1, len1);
3438 luaL_addlstring(&appctx->b, blk2, len2);
3439
3440 /* Consume input channel output buffer data. */
3441 bo_skip(si_oc(si), len1 + len2);
3442 luaL_pushresult(&appctx->b);
3443 return 1;
3444}
3445
3446/* Check arguments for the fucntion "hlua_channel_get_yield". */
3447__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3448{
3449 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3450
3451 /* Initialise the string catenation. */
3452 luaL_buffinit(L, &appctx->b);
3453
3454 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3455}
3456
3457/* If expected data not yet available, it returns a yield. This function
3458 * consumes the data in the buffer. It returns a string containing the
3459 * data. This string can be empty.
3460 */
3461__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3462{
3463 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3464 struct stream_interface *si = appctx->appctx->owner;
3465 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3466 int ret;
3467 char *blk1;
3468 int len1;
3469 char *blk2;
3470 int len2;
3471
3472 /* Read the maximum amount of data avalaible. */
3473 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3474
3475 /* Data not yet avalaible. return yield. */
3476 if (ret == 0) {
3477 si_applet_cant_get(si);
3478 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3479 }
3480
3481 /* End of data: commit the total strings and return. */
3482 if (ret < 0) {
3483 luaL_pushresult(&appctx->b);
3484 return 1;
3485 }
3486
3487 /* Ensure that the block 2 length is usable. */
3488 if (ret == 1)
3489 len2 = 0;
3490
3491 if (len == -1) {
3492
3493 /* If len == -1, catenate all the data avalaile and
3494 * yield because we want to get all the data until
3495 * the end of data stream.
3496 */
3497 luaL_addlstring(&appctx->b, blk1, len1);
3498 luaL_addlstring(&appctx->b, blk2, len2);
3499 bo_skip(si_oc(si), len1 + len2);
3500 si_applet_cant_get(si);
3501 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3502
3503 } else {
3504
3505 /* Copy the fisrt block caping to the length required. */
3506 if (len1 > len)
3507 len1 = len;
3508 luaL_addlstring(&appctx->b, blk1, len1);
3509 len -= len1;
3510
3511 /* Copy the second block. */
3512 if (len2 > len)
3513 len2 = len;
3514 luaL_addlstring(&appctx->b, blk2, len2);
3515 len -= len2;
3516
3517 /* Consume input channel output buffer data. */
3518 bo_skip(si_oc(si), len1 + len2);
3519
3520 /* If we are no other data avalaible, yield waiting for new data. */
3521 if (len > 0) {
3522 lua_pushinteger(L, len);
3523 lua_replace(L, 2);
3524 si_applet_cant_get(si);
3525 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3526 }
3527
3528 /* return the result. */
3529 luaL_pushresult(&appctx->b);
3530 return 1;
3531 }
3532
3533 /* we never executes this */
3534 hlua_pusherror(L, "Lua: internal error");
3535 WILL_LJMP(lua_error(L));
3536 return 0;
3537}
3538
3539/* Check arguments for the fucntion "hlua_channel_get_yield". */
3540__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3541{
3542 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3543 int len = -1;
3544
3545 if (lua_gettop(L) > 2)
3546 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3547 if (lua_gettop(L) >= 2) {
3548 len = MAY_LJMP(luaL_checkinteger(L, 2));
3549 lua_pop(L, 1);
3550 }
3551
3552 /* Confirm or set the required length */
3553 lua_pushinteger(L, len);
3554
3555 /* Initialise the string catenation. */
3556 luaL_buffinit(L, &appctx->b);
3557
3558 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3559}
3560
3561/* Append data in the output side of the buffer. This data is immediatly
3562 * sent. The fcuntion returns the ammount of data writed. If the buffer
3563 * cannot contains the data, the function yield. The function returns -1
3564 * if the channel is closed.
3565 */
3566__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3567{
3568 size_t len;
3569 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3570 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3571 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3572 struct stream_interface *si = appctx->appctx->owner;
3573 struct channel *chn = si_ic(si);
3574 int max;
3575
3576 /* Get the max amount of data which can write as input in the channel. */
3577 max = channel_recv_max(chn);
3578 if (max > (len - l))
3579 max = len - l;
3580
3581 /* Copy data. */
3582 bi_putblk(chn, str + l, max);
3583
3584 /* update counters. */
3585 l += max;
3586 lua_pop(L, 1);
3587 lua_pushinteger(L, l);
3588
3589 /* If some data is not send, declares the situation to the
3590 * applet, and returns a yield.
3591 */
3592 if (l < len) {
3593 si_applet_cant_put(si);
3594 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3595 }
3596
3597 return 1;
3598}
3599
3600/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3601 * yield the LUA process, and resume it without checking the
3602 * input arguments.
3603 */
3604__LJMP static int hlua_applet_tcp_send(lua_State *L)
3605{
3606 MAY_LJMP(check_args(L, 2, "send"));
3607 lua_pushinteger(L, 0);
3608
3609 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3610}
3611
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003612/*
3613 *
3614 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003615 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003616 *
3617 *
3618 */
3619
3620/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003621 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003622 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003623__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003624{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003625 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003626}
3627
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003628/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003629 * according with a current TXN.
3630 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003631static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003632{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003633 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003634 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003635 struct stream_interface *si = ctx->owner;
3636 struct stream *s = si_strm(si);
3637 struct proxy *px = s->be;
3638 struct http_txn *txn = s->txn;
3639 const char *path;
3640 const char *end;
3641 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003642
3643 /* Check stack size. */
3644 if (!lua_checkstack(L, 3))
3645 return 0;
3646
3647 /* Create the object: obj[0] = userdata.
3648 * Note that the base of the Converters object is the
3649 * same than the TXN object.
3650 */
3651 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003652 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003653 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003654 appctx->appctx = ctx;
3655 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003656 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003657 appctx->htxn.s = s;
3658 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003659
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003660 /* Create the "f" field that contains a list of fetches. */
3661 lua_pushstring(L, "f");
3662 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3663 return 0;
3664 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003665
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003666 /* Create the "sf" field that contains a list of stringsafe fetches. */
3667 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003668 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003669 return 0;
3670 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003671
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003672 /* Create the "c" field that contains a list of converters. */
3673 lua_pushstring(L, "c");
3674 if (!hlua_converters_new(L, &appctx->htxn, 0))
3675 return 0;
3676 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003677
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003678 /* Create the "sc" field that contains a list of stringsafe converters. */
3679 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003680 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003681 return 0;
3682 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003683
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003684 /* Stores the request method. */
3685 lua_pushstring(L, "method");
3686 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3687 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003688
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003689 /* Stores the http version. */
3690 lua_pushstring(L, "version");
3691 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3692 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003693
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003694 /* creates an array of headers. hlua_http_get_headers() crates and push
3695 * the array on the top of the stack.
3696 */
3697 lua_pushstring(L, "headers");
3698 htxn.s = s;
3699 htxn.p = px;
3700 htxn.dir = SMP_OPT_DIR_REQ;
3701 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3702 return 0;
3703 lua_settable(L, -3);
3704
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003705 /* Get path and qs */
3706 path = http_get_path(txn);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003707 if (path) {
3708 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3709 p = path;
3710 while (p < end && *p != '?')
3711 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003712
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003713 /* Stores the request path. */
3714 lua_pushstring(L, "path");
3715 lua_pushlstring(L, path, p - path);
3716 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003717
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003718 /* Stores the query string. */
3719 lua_pushstring(L, "qs");
3720 if (*p == '?')
3721 p++;
3722 lua_pushlstring(L, p, end - p);
3723 lua_settable(L, -3);
3724 }
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003725
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003726 /* Stores the request path. */
3727 lua_pushstring(L, "length");
3728 lua_pushinteger(L, txn->req.body_len);
3729 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003730
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003731 /* Create an array of HTTP request headers. */
3732 lua_pushstring(L, "headers");
3733 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3734 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003735
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003736 /* Create an empty array of HTTP request headers. */
3737 lua_pushstring(L, "response");
3738 lua_newtable(L);
3739 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003740
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003741 /* Pop a class stream metatable and affect it to the table. */
3742 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3743 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003744
3745 return 1;
3746}
3747
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003748__LJMP static int hlua_applet_http_set_var(lua_State *L)
3749{
3750 struct hlua_appctx *appctx;
3751 struct stream *s;
3752 const char *name;
3753 size_t len;
3754 struct sample smp;
3755
3756 MAY_LJMP(check_args(L, 3, "set_var"));
3757
3758 /* It is useles to retrieve the stream, but this function
3759 * runs only in a stream context.
3760 */
3761 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3762 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3763 s = appctx->htxn.s;
3764
3765 /* Converts the third argument in a sample. */
3766 hlua_lua2smp(L, 3, &smp);
3767
3768 /* Store the sample in a variable. */
3769 smp_set_owner(&smp, s->be, s->sess, s, 0);
3770 vars_set_by_name(name, len, &smp);
3771 return 0;
3772}
3773
3774__LJMP static int hlua_applet_http_unset_var(lua_State *L)
3775{
3776 struct hlua_appctx *appctx;
3777 struct stream *s;
3778 const char *name;
3779 size_t len;
3780 struct sample smp;
3781
3782 MAY_LJMP(check_args(L, 2, "unset_var"));
3783
3784 /* It is useles to retrieve the stream, but this function
3785 * runs only in a stream context.
3786 */
3787 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3788 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3789 s = appctx->htxn.s;
3790
3791 /* Unset the variable. */
3792 smp_set_owner(&smp, s->be, s->sess, s, 0);
3793 vars_unset_by_name(name, len, &smp);
3794 return 0;
3795}
3796
3797__LJMP static int hlua_applet_http_get_var(lua_State *L)
3798{
3799 struct hlua_appctx *appctx;
3800 struct stream *s;
3801 const char *name;
3802 size_t len;
3803 struct sample smp;
3804
3805 MAY_LJMP(check_args(L, 2, "get_var"));
3806
3807 /* It is useles to retrieve the stream, but this function
3808 * runs only in a stream context.
3809 */
3810 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3811 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3812 s = appctx->htxn.s;
3813
3814 smp_set_owner(&smp, s->be, s->sess, s, 0);
3815 if (!vars_get_by_name(name, len, &smp)) {
3816 lua_pushnil(L);
3817 return 1;
3818 }
3819
3820 return hlua_smp2lua(L, &smp);
3821}
3822
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003823__LJMP static int hlua_applet_http_set_priv(lua_State *L)
3824{
3825 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3826 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003827 struct hlua *hlua;
3828
3829 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003830 if (!s->hlua)
3831 return 0;
3832 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003833
3834 MAY_LJMP(check_args(L, 2, "set_priv"));
3835
3836 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003837 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003838
3839 /* Get and store new value. */
3840 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3841 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3842
3843 return 0;
3844}
3845
3846__LJMP static int hlua_applet_http_get_priv(lua_State *L)
3847{
3848 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3849 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003850 struct hlua *hlua;
3851
3852 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003853 if (!s->hlua) {
3854 lua_pushnil(L);
3855 return 1;
3856 }
3857 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003858
3859 /* Push configuration index in the stack. */
3860 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3861
3862 return 1;
3863}
3864
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003865/* If expected data not yet available, it returns a yield. This function
3866 * consumes the data in the buffer. It returns a string containing the
3867 * data. This string can be empty.
3868 */
3869__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003870{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003871 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3872 struct stream_interface *si = appctx->appctx->owner;
3873 struct channel *chn = si_ic(si);
3874 int ret;
3875 char *blk1;
3876 int len1;
3877 char *blk2;
3878 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003879
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003880 /* Maybe we cant send a 100-continue ? */
3881 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3882 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3883 /* if ret == -2 or -3 the channel closed or the message si too
3884 * big for the buffers. We cant send anything. So, we ignoring
3885 * the error, considers that the 100-continue is sent, and try
3886 * to receive.
3887 * If ret is -1, we dont have room in the buffer, so we yield.
3888 */
3889 if (ret == -1) {
3890 si_applet_cant_put(si);
3891 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3892 }
3893 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3894 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003895
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003896 /* Check for the end of the data. */
3897 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
3898 luaL_pushresult(&appctx->b);
3899 return 1;
3900 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003901
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003902 /* Read the maximum amount of data avalaible. */
3903 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003904
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003905 /* Data not yet avalaible. return yield. */
3906 if (ret == 0) {
3907 si_applet_cant_get(si);
3908 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3909 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003910
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003911 /* End of data: commit the total strings and return. */
3912 if (ret < 0) {
3913 luaL_pushresult(&appctx->b);
3914 return 1;
3915 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003916
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003917 /* Ensure that the block 2 length is usable. */
3918 if (ret == 1)
3919 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003920
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003921 /* Copy the fisrt block caping to the length required. */
3922 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3923 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3924 luaL_addlstring(&appctx->b, blk1, len1);
3925 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003926
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003927 /* Copy the second block. */
3928 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3929 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3930 luaL_addlstring(&appctx->b, blk2, len2);
3931 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003932
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003933 /* Consume input channel output buffer data. */
3934 bo_skip(si_oc(si), len1 + len2);
3935 luaL_pushresult(&appctx->b);
3936 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003937}
3938
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003939/* Check arguments for the fucntion "hlua_channel_get_yield". */
3940__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003941{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003942 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003943
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003944 /* Initialise the string catenation. */
3945 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003946
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003947 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003948}
3949
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003950/* If expected data not yet available, it returns a yield. This function
3951 * consumes the data in the buffer. It returns a string containing the
3952 * data. This string can be empty.
3953 */
3954__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003955{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003956 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3957 struct stream_interface *si = appctx->appctx->owner;
3958 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3959 struct channel *chn = si_ic(si);
3960 int ret;
3961 char *blk1;
3962 int len1;
3963 char *blk2;
3964 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003965
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003966 /* Maybe we cant send a 100-continue ? */
3967 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3968 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3969 /* if ret == -2 or -3 the channel closed or the message si too
3970 * big for the buffers. We cant send anything. So, we ignoring
3971 * the error, considers that the 100-continue is sent, and try
3972 * to receive.
3973 * If ret is -1, we dont have room in the buffer, so we yield.
3974 */
3975 if (ret == -1) {
3976 si_applet_cant_put(si);
3977 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3978 }
3979 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3980 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003981
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003982 /* Read the maximum amount of data avalaible. */
3983 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003984
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003985 /* Data not yet avalaible. return yield. */
3986 if (ret == 0) {
3987 si_applet_cant_get(si);
3988 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3989 }
3990
3991 /* End of data: commit the total strings and return. */
3992 if (ret < 0) {
3993 luaL_pushresult(&appctx->b);
3994 return 1;
3995 }
3996
3997 /* Ensure that the block 2 length is usable. */
3998 if (ret == 1)
3999 len2 = 0;
4000
4001 /* Copy the fisrt block caping to the length required. */
4002 if (len1 > len)
4003 len1 = len;
4004 luaL_addlstring(&appctx->b, blk1, len1);
4005 len -= len1;
4006
4007 /* Copy the second block. */
4008 if (len2 > len)
4009 len2 = len;
4010 luaL_addlstring(&appctx->b, blk2, len2);
4011 len -= len2;
4012
4013 /* Consume input channel output buffer data. */
4014 bo_skip(si_oc(si), len1 + len2);
4015 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
4016 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
4017
4018 /* If we are no other data avalaible, yield waiting for new data. */
4019 if (len > 0) {
4020 lua_pushinteger(L, len);
4021 lua_replace(L, 2);
4022 si_applet_cant_get(si);
4023 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4024 }
4025
4026 /* return the result. */
4027 luaL_pushresult(&appctx->b);
4028 return 1;
4029}
4030
4031/* Check arguments for the fucntion "hlua_channel_get_yield". */
4032__LJMP static int hlua_applet_http_recv(lua_State *L)
4033{
4034 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4035 int len = -1;
4036
4037 /* Check arguments. */
4038 if (lua_gettop(L) > 2)
4039 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4040 if (lua_gettop(L) >= 2) {
4041 len = MAY_LJMP(luaL_checkinteger(L, 2));
4042 lua_pop(L, 1);
4043 }
4044
4045 /* Check the required length */
4046 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4047 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4048 lua_pushinteger(L, len);
4049
4050 /* Initialise the string catenation. */
4051 luaL_buffinit(L, &appctx->b);
4052
4053 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4054}
4055
4056/* Append data in the output side of the buffer. This data is immediatly
4057 * sent. The fcuntion returns the ammount of data writed. If the buffer
4058 * cannot contains the data, the function yield. The function returns -1
4059 * if the channel is closed.
4060 */
4061__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4062{
4063 size_t len;
4064 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4065 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4066 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4067 struct stream_interface *si = appctx->appctx->owner;
4068 struct channel *chn = si_ic(si);
4069 int max;
4070
4071 /* Get the max amount of data which can write as input in the channel. */
4072 max = channel_recv_max(chn);
4073 if (max > (len - l))
4074 max = len - l;
4075
4076 /* Copy data. */
4077 bi_putblk(chn, str + l, max);
4078
4079 /* update counters. */
4080 l += max;
4081 lua_pop(L, 1);
4082 lua_pushinteger(L, l);
4083
4084 /* If some data is not send, declares the situation to the
4085 * applet, and returns a yield.
4086 */
4087 if (l < len) {
4088 si_applet_cant_put(si);
4089 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
4090 }
4091
4092 return 1;
4093}
4094
4095/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4096 * yield the LUA process, and resume it without checking the
4097 * input arguments.
4098 */
4099__LJMP static int hlua_applet_http_send(lua_State *L)
4100{
4101 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4102 size_t len;
4103 char hex[10];
4104
4105 MAY_LJMP(luaL_checklstring(L, 2, &len));
4106
4107 /* If transfer encoding chunked is selected, we surround the data
4108 * by chunk data.
4109 */
4110 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4111 snprintf(hex, 9, "%x", (unsigned int)len);
4112 lua_pushfstring(L, "%s\r\n", hex);
4113 lua_insert(L, 2); /* swap the last 2 entries. */
4114 lua_pushstring(L, "\r\n");
4115 lua_concat(L, 3);
4116 }
4117
4118 /* This interger is used for followinf the amount of data sent. */
4119 lua_pushinteger(L, 0);
4120
4121 /* We want to send some data. Headers must be sent. */
4122 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4123 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4124 WILL_LJMP(lua_error(L));
4125 }
4126
4127 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4128}
4129
4130__LJMP static int hlua_applet_http_addheader(lua_State *L)
4131{
4132 const char *name;
4133 int ret;
4134
4135 MAY_LJMP(hlua_checkapplet_http(L, 1));
4136 name = MAY_LJMP(luaL_checkstring(L, 2));
4137 MAY_LJMP(luaL_checkstring(L, 3));
4138
4139 /* Push in the stack the "response" entry. */
4140 ret = lua_getfield(L, 1, "response");
4141 if (ret != LUA_TTABLE) {
4142 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4143 "is expected as an array. %s found", lua_typename(L, ret));
4144 WILL_LJMP(lua_error(L));
4145 }
4146
4147 /* check if the header is already registered if it is not
4148 * the case, register it.
4149 */
4150 ret = lua_getfield(L, -1, name);
4151 if (ret == LUA_TNIL) {
4152
4153 /* Entry not found. */
4154 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4155
4156 /* Insert the new header name in the array in the top of the stack.
4157 * It left the new array in the top of the stack.
4158 */
4159 lua_newtable(L);
4160 lua_pushvalue(L, 2);
4161 lua_pushvalue(L, -2);
4162 lua_settable(L, -4);
4163
4164 } else if (ret != LUA_TTABLE) {
4165
4166 /* corruption error. */
4167 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4168 "is expected as an array. %s found", name, lua_typename(L, ret));
4169 WILL_LJMP(lua_error(L));
4170 }
4171
4172 /* Now the top od thestack is an array of values. We push
4173 * the header value as new entry.
4174 */
4175 lua_pushvalue(L, 3);
4176 ret = lua_rawlen(L, -2);
4177 lua_rawseti(L, -2, ret + 1);
4178 lua_pushboolean(L, 1);
4179 return 1;
4180}
4181
4182__LJMP static int hlua_applet_http_status(lua_State *L)
4183{
4184 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4185 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004186 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004187
4188 if (status < 100 || status > 599) {
4189 lua_pushboolean(L, 0);
4190 return 1;
4191 }
4192
4193 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004194 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004195 lua_pushboolean(L, 1);
4196 return 1;
4197}
4198
4199/* We will build the status line and the headers of the HTTP response.
4200 * We will try send at once if its not possible, we give back the hand
4201 * waiting for more room.
4202 */
4203__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4204{
4205 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4206 struct stream_interface *si = appctx->appctx->owner;
4207 struct channel *chn = si_ic(si);
4208 int ret;
4209 size_t len;
4210 const char *msg;
4211
4212 /* Get the message as the first argument on the stack. */
4213 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4214
4215 /* Send the message at once. */
4216 ret = bi_putblk(chn, msg, len);
4217
4218 /* if ret == -2 or -3 the channel closed or the message si too
4219 * big for the buffers.
4220 */
4221 if (ret == -2 || ret == -3) {
4222 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4223 WILL_LJMP(lua_error(L));
4224 }
4225
4226 /* If ret is -1, we dont have room in the buffer, so we yield. */
4227 if (ret == -1) {
4228 si_applet_cant_put(si);
4229 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
4230 }
4231
4232 /* Headers sent, set the flag. */
4233 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4234 return 0;
4235}
4236
4237__LJMP static int hlua_applet_http_start_response(lua_State *L)
4238{
4239 struct chunk *tmp = get_trash_chunk();
4240 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004241 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02004242 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004243 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02004244 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004245 int id;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004246 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004247 int hdr_chunked = 0;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004248 const char *reason = appctx->appctx->ctx.hlua_apphttp.reason;
4249
4250 if (reason == NULL)
4251 reason = get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004252
4253 /* Use the same http version than the request. */
4254 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004255 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004256 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004257 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004258
4259 /* Get the array associated to the field "response" in the object AppletHTTP. */
4260 lua_pushvalue(L, 0);
4261 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4262 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4263 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4264 WILL_LJMP(lua_error(L));
4265 }
4266
4267 /* Browse the list of headers. */
4268 lua_pushnil(L);
4269 while(lua_next(L, -2) != 0) {
4270
4271 /* We expect a string as -2. */
4272 if (lua_type(L, -2) != LUA_TSTRING) {
4273 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4274 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4275 lua_typename(L, lua_type(L, -2)));
4276 WILL_LJMP(lua_error(L));
4277 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004278 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004279
4280 /* We expect an array as -1. */
4281 if (lua_type(L, -1) != LUA_TTABLE) {
4282 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4283 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4284 name,
4285 lua_typename(L, lua_type(L, -1)));
4286 WILL_LJMP(lua_error(L));
4287 }
4288
4289 /* Browse the table who is on the top of the stack. */
4290 lua_pushnil(L);
4291 while(lua_next(L, -2) != 0) {
4292
4293 /* We expect a number as -2. */
4294 if (lua_type(L, -2) != LUA_TNUMBER) {
4295 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4296 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4297 name,
4298 lua_typename(L, lua_type(L, -2)));
4299 WILL_LJMP(lua_error(L));
4300 }
4301 id = lua_tointeger(L, -2);
4302
4303 /* We expect a string as -2. */
4304 if (lua_type(L, -1) != LUA_TSTRING) {
4305 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4306 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4307 name, id,
4308 lua_typename(L, lua_type(L, -1)));
4309 WILL_LJMP(lua_error(L));
4310 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004311 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004312
4313 /* Catenate a new header. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004314 if (tmp->len + name_len + 2 + value_len + 2 < tmp->size) {
4315 memcpy(tmp->str + tmp->len, name, name_len);
4316 tmp->len += name_len;
4317 tmp->str[tmp->len++] = ':';
4318 tmp->str[tmp->len++] = ' ';
4319
4320 memcpy(tmp->str + tmp->len, value, value_len);
4321 tmp->len += value_len;
4322 tmp->str[tmp->len++] = '\r';
4323 tmp->str[tmp->len++] = '\n';
4324 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004325
4326 /* Protocol checks. */
4327
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004328 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004329 * is done without control. If it contains a bad value,
4330 * the content-length remains negative so that we can
4331 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004332 */
Willy Tarreaua3294632017-08-23 11:24:47 +02004333 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004334 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004335
4336 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004337 if (name_len == 17 && value_len == 7 &&
4338 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004339 strcasecmp("chunked", value) == 0)
4340 hdr_chunked = 1;
4341
4342 /* Remove the array from the stack, and get next element with a remaining string. */
4343 lua_pop(L, 1);
4344 }
4345
4346 /* Remove the array from the stack, and get next element with a remaining string. */
4347 lua_pop(L, 1);
4348 }
4349
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004350 /* If we dont have a content-length set, and the HTTP version is 1.1
4351 * and the status code implies the presence of a message body, we must
4352 * announce a transfer encoding chunked. This is required by haproxy
4353 * for the keepalive compliance. If the applet annouces a transfer-encoding
4354 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004355 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004356 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004357 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
4358 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4359 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4360 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004361 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4362 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4363 }
4364
4365 /* Finalize headers. */
4366 chunk_appendf(tmp, "\r\n");
4367
4368 /* Remove the last entry and the array of headers */
4369 lua_pop(L, 2);
4370
4371 /* Push the headers block. */
4372 lua_pushlstring(L, tmp->str, tmp->len);
4373
4374 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4375}
4376
4377/*
4378 *
4379 *
4380 * Class HTTP
4381 *
4382 *
4383 */
4384
4385/* Returns a struct hlua_txn if the stack entry "ud" is
4386 * a class stream, otherwise it throws an error.
4387 */
4388__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4389{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004390 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004391}
4392
4393/* This function creates and push in the stack a HTTP object
4394 * according with a current TXN.
4395 */
4396static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4397{
4398 struct hlua_txn *htxn;
4399
4400 /* Check stack size. */
4401 if (!lua_checkstack(L, 3))
4402 return 0;
4403
4404 /* Create the object: obj[0] = userdata.
4405 * Note that the base of the Converters object is the
4406 * same than the TXN object.
4407 */
4408 lua_newtable(L);
4409 htxn = lua_newuserdata(L, sizeof(*htxn));
4410 lua_rawseti(L, -2, 0);
4411
4412 htxn->s = txn->s;
4413 htxn->p = txn->p;
4414
4415 /* Pop a class stream metatable and affect it to the table. */
4416 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4417 lua_setmetatable(L, -2);
4418
4419 return 1;
4420}
4421
4422/* This function creates ans returns an array of HTTP headers.
4423 * This function does not fails. It is used as wrapper with the
4424 * 2 following functions.
4425 */
4426__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4427{
4428 const char *cur_ptr, *cur_next, *p;
4429 int old_idx, cur_idx;
4430 struct hdr_idx_elem *cur_hdr;
4431 const char *hn, *hv;
4432 int hnl, hvl;
4433 int type;
4434 const char *in;
4435 char *out;
4436 int len;
4437
4438 /* Create the table. */
4439 lua_newtable(L);
4440
4441 if (!htxn->s->txn)
4442 return 1;
4443
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004444 /* Check if a valid response is parsed */
4445 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4446 return 1;
4447
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004448 /* Build array of headers. */
4449 old_idx = 0;
4450 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4451
4452 while (1) {
4453 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4454 if (!cur_idx)
4455 break;
4456 old_idx = cur_idx;
4457
4458 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4459 cur_ptr = cur_next;
4460 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4461
4462 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4463 * and the next header starts at cur_next. We'll check
4464 * this header in the list as well as against the default
4465 * rule.
4466 */
4467
4468 /* look for ': *'. */
4469 hn = cur_ptr;
4470 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4471 if (p >= cur_ptr+cur_hdr->len)
4472 continue;
4473 hnl = p - hn;
4474 p++;
4475 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4476 p++;
4477 if (p >= cur_ptr+cur_hdr->len)
4478 continue;
4479 hv = p;
4480 hvl = cur_ptr+cur_hdr->len-p;
4481
4482 /* Lowercase the key. Don't check the size of trash, it have
4483 * the size of one buffer and the input data contains in one
4484 * buffer.
4485 */
4486 out = trash.str;
4487 for (in=hn; in<hn+hnl; in++, out++)
4488 *out = tolower(*in);
4489 *out = '\0';
4490
4491 /* Check for existing entry:
4492 * assume that the table is on the top of the stack, and
4493 * push the key in the stack, the function lua_gettable()
4494 * perform the lookup.
4495 */
4496 lua_pushlstring(L, trash.str, hnl);
4497 lua_gettable(L, -2);
4498 type = lua_type(L, -1);
4499
4500 switch (type) {
4501 case LUA_TNIL:
4502 /* Table not found, create it. */
4503 lua_pop(L, 1); /* remove the nil value. */
4504 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4505 lua_newtable(L); /* create and push empty table. */
4506 lua_pushlstring(L, hv, hvl); /* push header value. */
4507 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4508 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4509 break;
4510
4511 case LUA_TTABLE:
4512 /* Entry found: push the value in the table. */
4513 len = lua_rawlen(L, -1);
4514 lua_pushlstring(L, hv, hvl); /* push header value. */
4515 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4516 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4517 break;
4518
4519 default:
4520 /* Other cases are errors. */
4521 hlua_pusherror(L, "internal error during the parsing of headers.");
4522 WILL_LJMP(lua_error(L));
4523 }
4524 }
4525
4526 return 1;
4527}
4528
4529__LJMP static int hlua_http_req_get_headers(lua_State *L)
4530{
4531 struct hlua_txn *htxn;
4532
4533 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4534 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4535
4536 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4537}
4538
4539__LJMP static int hlua_http_res_get_headers(lua_State *L)
4540{
4541 struct hlua_txn *htxn;
4542
4543 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4544 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4545
4546 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4547}
4548
4549/* This function replace full header, or just a value in
4550 * the request or in the response. It is a wrapper fir the
4551 * 4 following functions.
4552 */
4553__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4554 struct http_msg *msg, int action)
4555{
4556 size_t name_len;
4557 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4558 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4559 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4560 struct my_regex re;
4561
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004562 /* Check if a valid response is parsed */
4563 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4564 return 0;
4565
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004566 if (!regex_comp(reg, &re, 1, 1, NULL))
4567 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4568
4569 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4570 regex_free(&re);
4571 return 0;
4572}
4573
4574__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4575{
4576 struct hlua_txn *htxn;
4577
4578 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4579 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4580
4581 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4582}
4583
4584__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4585{
4586 struct hlua_txn *htxn;
4587
4588 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4589 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4590
4591 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4592}
4593
4594__LJMP static int hlua_http_req_rep_val(lua_State *L)
4595{
4596 struct hlua_txn *htxn;
4597
4598 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4599 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4600
4601 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4602}
4603
4604__LJMP static int hlua_http_res_rep_val(lua_State *L)
4605{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004606 struct hlua_txn *htxn;
4607
4608 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4609 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4610
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004611 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004612}
4613
4614/* This function deletes all the occurences of an header.
4615 * It is a wrapper for the 2 following functions.
4616 */
4617__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4618{
4619 size_t len;
4620 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4621 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004622 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004623
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004624 /* Check if a valid response is parsed */
4625 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4626 return 0;
4627
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004628 ctx.idx = 0;
4629 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4630 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4631 return 0;
4632}
4633
4634__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4635{
4636 struct hlua_txn *htxn;
4637
4638 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4639 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4640
Willy Tarreaueee5b512015-04-03 23:46:31 +02004641 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004642}
4643
4644__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4645{
4646 struct hlua_txn *htxn;
4647
4648 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4649 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4650
Willy Tarreaueee5b512015-04-03 23:46:31 +02004651 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004652}
4653
4654/* This function adds an header. It is a wrapper used by
4655 * the 2 following functions.
4656 */
4657__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4658{
4659 size_t name_len;
4660 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4661 size_t value_len;
4662 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4663 char *p;
4664
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004665 /* Check if a valid message is parsed */
4666 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4667 return 0;
4668
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004669 /* Check length. */
4670 trash.len = value_len + name_len + 2;
4671 if (trash.len > trash.size)
4672 return 0;
4673
4674 /* Creates the header string. */
4675 p = trash.str;
4676 memcpy(p, name, name_len);
4677 p += name_len;
4678 *p = ':';
4679 p++;
4680 *p = ' ';
4681 p++;
4682 memcpy(p, value, value_len);
4683
Willy Tarreaueee5b512015-04-03 23:46:31 +02004684 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004685 trash.str, trash.len) != 0);
4686
4687 return 0;
4688}
4689
4690__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4691{
4692 struct hlua_txn *htxn;
4693
4694 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4695 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4696
Willy Tarreaueee5b512015-04-03 23:46:31 +02004697 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004698}
4699
4700__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4701{
4702 struct hlua_txn *htxn;
4703
4704 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4705 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4706
Willy Tarreaueee5b512015-04-03 23:46:31 +02004707 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004708}
4709
4710static int hlua_http_req_set_hdr(lua_State *L)
4711{
4712 struct hlua_txn *htxn;
4713
4714 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4715 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4716
Willy Tarreaueee5b512015-04-03 23:46:31 +02004717 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4718 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004719}
4720
4721static int hlua_http_res_set_hdr(lua_State *L)
4722{
4723 struct hlua_txn *htxn;
4724
4725 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4726 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4727
Willy Tarreaueee5b512015-04-03 23:46:31 +02004728 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4729 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004730}
4731
4732/* This function set the method. */
4733static int hlua_http_req_set_meth(lua_State *L)
4734{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004735 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004736 size_t name_len;
4737 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004738
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004739 /* Check if a valid request is parsed */
4740 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4741 lua_pushboolean(L, 0);
4742 return 1;
4743 }
4744
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004745 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004746 return 1;
4747}
4748
4749/* This function set the method. */
4750static int hlua_http_req_set_path(lua_State *L)
4751{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004752 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004753 size_t name_len;
4754 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004755
4756 /* Check if a valid request is parsed */
4757 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4758 lua_pushboolean(L, 0);
4759 return 1;
4760 }
4761
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004762 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004763 return 1;
4764}
4765
4766/* This function set the query-string. */
4767static int hlua_http_req_set_query(lua_State *L)
4768{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004769 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004770 size_t name_len;
4771 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004772
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004773 /* Check if a valid request is parsed */
4774 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4775 lua_pushboolean(L, 0);
4776 return 1;
4777 }
4778
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004779 /* Check length. */
4780 if (name_len > trash.size - 1) {
4781 lua_pushboolean(L, 0);
4782 return 1;
4783 }
4784
4785 /* Add the mark question as prefix. */
4786 chunk_reset(&trash);
4787 trash.str[trash.len++] = '?';
4788 memcpy(trash.str + trash.len, name, name_len);
4789 trash.len += name_len;
4790
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004791 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004792 return 1;
4793}
4794
4795/* This function set the uri. */
4796static int hlua_http_req_set_uri(lua_State *L)
4797{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004798 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004799 size_t name_len;
4800 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004801
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004802 /* Check if a valid request is parsed */
4803 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4804 lua_pushboolean(L, 0);
4805 return 1;
4806 }
4807
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004808 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004809 return 1;
4810}
4811
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004812/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004813static int hlua_http_res_set_status(lua_State *L)
4814{
4815 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4816 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004817 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004818
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004819 /* Check if a valid response is parsed */
4820 if (unlikely(htxn->s->txn->rsp.msg_state < HTTP_MSG_BODY))
4821 return 0;
4822
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004823 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004824 return 0;
4825}
4826
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004827/*
4828 *
4829 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004830 * Class TXN
4831 *
4832 *
4833 */
4834
4835/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004836 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004837 */
4838__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
4839{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004840 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004841}
4842
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004843__LJMP static int hlua_set_var(lua_State *L)
4844{
4845 struct hlua_txn *htxn;
4846 const char *name;
4847 size_t len;
4848 struct sample smp;
4849
4850 MAY_LJMP(check_args(L, 3, "set_var"));
4851
4852 /* It is useles to retrieve the stream, but this function
4853 * runs only in a stream context.
4854 */
4855 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4856 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4857
4858 /* Converts the third argument in a sample. */
4859 hlua_lua2smp(L, 3, &smp);
4860
4861 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01004862 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004863 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004864 return 0;
4865}
4866
Christopher Faulet85d79c92016-11-09 16:54:56 +01004867__LJMP static int hlua_unset_var(lua_State *L)
4868{
4869 struct hlua_txn *htxn;
4870 const char *name;
4871 size_t len;
4872 struct sample smp;
4873
4874 MAY_LJMP(check_args(L, 2, "unset_var"));
4875
4876 /* It is useles to retrieve the stream, but this function
4877 * runs only in a stream context.
4878 */
4879 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4880 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4881
4882 /* Unset the variable. */
4883 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
4884 vars_unset_by_name(name, len, &smp);
4885 return 0;
4886}
4887
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004888__LJMP static int hlua_get_var(lua_State *L)
4889{
4890 struct hlua_txn *htxn;
4891 const char *name;
4892 size_t len;
4893 struct sample smp;
4894
4895 MAY_LJMP(check_args(L, 2, "get_var"));
4896
4897 /* It is useles to retrieve the stream, but this function
4898 * runs only in a stream context.
4899 */
4900 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4901 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4902
Willy Tarreau7560dd42016-03-10 16:28:58 +01004903 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004904 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004905 lua_pushnil(L);
4906 return 1;
4907 }
4908
4909 return hlua_smp2lua(L, &smp);
4910}
4911
Willy Tarreau59551662015-03-10 14:23:13 +01004912__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004913{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004914 struct hlua *hlua;
4915
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004916 MAY_LJMP(check_args(L, 2, "set_priv"));
4917
Willy Tarreau87b09662015-04-03 00:22:06 +02004918 /* It is useles to retrieve the stream, but this function
4919 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004920 */
4921 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004922 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004923
4924 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004925 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004926
4927 /* Get and store new value. */
4928 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4929 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4930
4931 return 0;
4932}
4933
Willy Tarreau59551662015-03-10 14:23:13 +01004934__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004935{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004936 struct hlua *hlua;
4937
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004938 MAY_LJMP(check_args(L, 1, "get_priv"));
4939
Willy Tarreau87b09662015-04-03 00:22:06 +02004940 /* It is useles to retrieve the stream, but this function
4941 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004942 */
4943 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004944 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004945
4946 /* Push configuration index in the stack. */
4947 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4948
4949 return 1;
4950}
4951
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004952/* Create stack entry containing a class TXN. This function
4953 * return 0 if the stack does not contains free slots,
4954 * otherwise it returns 1.
4955 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004956static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004957{
Willy Tarreaude491382015-04-06 11:04:28 +02004958 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004959
4960 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004961 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004962 return 0;
4963
4964 /* NOTE: The allocation never fails. The failure
4965 * throw an error, and the function never returns.
4966 * if the throw is not avalaible, the process is aborted.
4967 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004968 /* Create the object: obj[0] = userdata. */
4969 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02004970 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004971 lua_rawseti(L, -2, 0);
4972
Willy Tarreaude491382015-04-06 11:04:28 +02004973 htxn->s = s;
4974 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004975 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004976 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004977
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004978 /* Create the "f" field that contains a list of fetches. */
4979 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004980 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004981 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004982 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004983
4984 /* Create the "sf" field that contains a list of stringsafe fetches. */
4985 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004986 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004987 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004988 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004989
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004990 /* Create the "c" field that contains a list of converters. */
4991 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02004992 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004993 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004994 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004995
4996 /* Create the "sc" field that contains a list of stringsafe converters. */
4997 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004998 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004999 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005000 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005001
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005002 /* Create the "req" field that contains the request channel object. */
5003 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005004 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005005 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005006 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005007
5008 /* Create the "res" field that contains the response channel object. */
5009 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005010 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005011 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005012 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005013
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005014 /* Creates the HTTP object is the current proxy allows http. */
5015 lua_pushstring(L, "http");
5016 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005017 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005018 return 0;
5019 }
5020 else
5021 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005022 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005023
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005024 /* Pop a class sesison metatable and affect it to the userdata. */
5025 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5026 lua_setmetatable(L, -2);
5027
5028 return 1;
5029}
5030
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005031__LJMP static int hlua_txn_deflog(lua_State *L)
5032{
5033 const char *msg;
5034 struct hlua_txn *htxn;
5035
5036 MAY_LJMP(check_args(L, 2, "deflog"));
5037 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5038 msg = MAY_LJMP(luaL_checkstring(L, 2));
5039
5040 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5041 return 0;
5042}
5043
5044__LJMP static int hlua_txn_log(lua_State *L)
5045{
5046 int level;
5047 const char *msg;
5048 struct hlua_txn *htxn;
5049
5050 MAY_LJMP(check_args(L, 3, "log"));
5051 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5052 level = MAY_LJMP(luaL_checkinteger(L, 2));
5053 msg = MAY_LJMP(luaL_checkstring(L, 3));
5054
5055 if (level < 0 || level >= NB_LOG_LEVELS)
5056 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5057
5058 hlua_sendlog(htxn->s->be, level, msg);
5059 return 0;
5060}
5061
5062__LJMP static int hlua_txn_log_debug(lua_State *L)
5063{
5064 const char *msg;
5065 struct hlua_txn *htxn;
5066
5067 MAY_LJMP(check_args(L, 2, "Debug"));
5068 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5069 msg = MAY_LJMP(luaL_checkstring(L, 2));
5070 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5071 return 0;
5072}
5073
5074__LJMP static int hlua_txn_log_info(lua_State *L)
5075{
5076 const char *msg;
5077 struct hlua_txn *htxn;
5078
5079 MAY_LJMP(check_args(L, 2, "Info"));
5080 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5081 msg = MAY_LJMP(luaL_checkstring(L, 2));
5082 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5083 return 0;
5084}
5085
5086__LJMP static int hlua_txn_log_warning(lua_State *L)
5087{
5088 const char *msg;
5089 struct hlua_txn *htxn;
5090
5091 MAY_LJMP(check_args(L, 2, "Warning"));
5092 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5093 msg = MAY_LJMP(luaL_checkstring(L, 2));
5094 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5095 return 0;
5096}
5097
5098__LJMP static int hlua_txn_log_alert(lua_State *L)
5099{
5100 const char *msg;
5101 struct hlua_txn *htxn;
5102
5103 MAY_LJMP(check_args(L, 2, "Alert"));
5104 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5105 msg = MAY_LJMP(luaL_checkstring(L, 2));
5106 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5107 return 0;
5108}
5109
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005110__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5111{
5112 struct hlua_txn *htxn;
5113 int ll;
5114
5115 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5116 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5117 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5118
5119 if (ll < 0 || ll > 7)
5120 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5121
5122 htxn->s->logs.level = ll;
5123 return 0;
5124}
5125
5126__LJMP static int hlua_txn_set_tos(lua_State *L)
5127{
5128 struct hlua_txn *htxn;
5129 struct connection *cli_conn;
5130 int tos;
5131
5132 MAY_LJMP(check_args(L, 2, "set_tos"));
5133 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5134 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5135
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005136 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005137 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005138
5139 return 0;
5140}
5141
5142__LJMP static int hlua_txn_set_mark(lua_State *L)
5143{
5144#ifdef SO_MARK
5145 struct hlua_txn *htxn;
5146 struct connection *cli_conn;
5147 int mark;
5148
5149 MAY_LJMP(check_args(L, 2, "set_mark"));
5150 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5151 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5152
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005153 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005154 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005155#endif
5156 return 0;
5157}
5158
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005159/* This function is an Lua binding that send pending data
5160 * to the client, and close the stream interface.
5161 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005162__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005163{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005164 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005165 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01005166 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005167
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005168 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005169 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005170 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005171
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005172 /* If the flags NOTERM is set, we cannot terminate the http
5173 * session, so we just end the execution of the current
5174 * lua code.
5175 */
5176 if (htxn->flags & HLUA_TXN_NOTERM) {
5177 WILL_LJMP(hlua_done(L));
5178 return 0;
5179 }
5180
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005181 ic = &htxn->s->req;
5182 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005183
Willy Tarreau630ef452015-08-28 10:06:15 +02005184 if (htxn->s->txn) {
5185 /* HTTP mode, let's stay in sync with the stream */
5186 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
5187 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
5188 htxn->s->txn->req.sov = 0;
5189 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
5190 oc->analysers = AN_RES_HTTP_XFER_BODY;
5191 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
5192 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
5193
Willy Tarreau630ef452015-08-28 10:06:15 +02005194 /* Note that if we want to support keep-alive, we need
5195 * to bypass the close/shutr_now calls below, but that
5196 * may only be done if the HTTP request was already
5197 * processed and the connection header is known (ie
5198 * not during TCP rules).
5199 */
5200 }
5201
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005202 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01005203 channel_abort(ic);
5204 channel_auto_close(ic);
5205 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005206
5207 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01005208 channel_auto_read(oc);
5209 channel_auto_close(oc);
5210 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005211
Willy Tarreau0458b082015-08-28 09:40:04 +02005212 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005213
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005214 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005215 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005216 return 0;
5217}
5218
5219__LJMP static int hlua_log(lua_State *L)
5220{
5221 int level;
5222 const char *msg;
5223
5224 MAY_LJMP(check_args(L, 2, "log"));
5225 level = MAY_LJMP(luaL_checkinteger(L, 1));
5226 msg = MAY_LJMP(luaL_checkstring(L, 2));
5227
5228 if (level < 0 || level >= NB_LOG_LEVELS)
5229 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5230
5231 hlua_sendlog(NULL, level, msg);
5232 return 0;
5233}
5234
5235__LJMP static int hlua_log_debug(lua_State *L)
5236{
5237 const char *msg;
5238
5239 MAY_LJMP(check_args(L, 1, "debug"));
5240 msg = MAY_LJMP(luaL_checkstring(L, 1));
5241 hlua_sendlog(NULL, LOG_DEBUG, msg);
5242 return 0;
5243}
5244
5245__LJMP static int hlua_log_info(lua_State *L)
5246{
5247 const char *msg;
5248
5249 MAY_LJMP(check_args(L, 1, "info"));
5250 msg = MAY_LJMP(luaL_checkstring(L, 1));
5251 hlua_sendlog(NULL, LOG_INFO, msg);
5252 return 0;
5253}
5254
5255__LJMP static int hlua_log_warning(lua_State *L)
5256{
5257 const char *msg;
5258
5259 MAY_LJMP(check_args(L, 1, "warning"));
5260 msg = MAY_LJMP(luaL_checkstring(L, 1));
5261 hlua_sendlog(NULL, LOG_WARNING, msg);
5262 return 0;
5263}
5264
5265__LJMP static int hlua_log_alert(lua_State *L)
5266{
5267 const char *msg;
5268
5269 MAY_LJMP(check_args(L, 1, "alert"));
5270 msg = MAY_LJMP(luaL_checkstring(L, 1));
5271 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005272 return 0;
5273}
5274
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005275__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005276{
5277 int wakeup_ms = lua_tointeger(L, -1);
5278 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005279 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005280 return 0;
5281}
5282
5283__LJMP static int hlua_sleep(lua_State *L)
5284{
5285 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005286 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005287
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005288 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005289
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005290 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005291 wakeup_ms = tick_add(now_ms, delay);
5292 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005293
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005294 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5295 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005296}
5297
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005298__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005299{
5300 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005301 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005302
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005303 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005304
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005305 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005306 wakeup_ms = tick_add(now_ms, delay);
5307 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005308
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005309 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5310 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005311}
5312
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005313/* This functionis an LUA binding. it permits to give back
5314 * the hand at the HAProxy scheduler. It is used when the
5315 * LUA processing consumes a lot of time.
5316 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005317__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005318{
5319 return 0;
5320}
5321
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005322__LJMP static int hlua_yield(lua_State *L)
5323{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005324 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
5325 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005326}
5327
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005328/* This function change the nice of the currently executed
5329 * task. It is used set low or high priority at the current
5330 * task.
5331 */
Willy Tarreau59551662015-03-10 14:23:13 +01005332__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005333{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005334 struct hlua *hlua;
5335 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005336
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005337 MAY_LJMP(check_args(L, 1, "set_nice"));
5338 hlua = hlua_gethlua(L);
5339 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005340
5341 /* If he task is not set, I'm in a start mode. */
5342 if (!hlua || !hlua->task)
5343 return 0;
5344
5345 if (nice < -1024)
5346 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005347 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005348 nice = 1024;
5349
5350 hlua->task->nice = nice;
5351 return 0;
5352}
5353
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005354/* This function is used as a calback of a task. It is called by the
5355 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5356 * return an E_AGAIN signal, the emmiter of this signal must set a
5357 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005358 *
5359 * Task wrapper are longjmp safe because the only one Lua code
5360 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005361 */
5362static struct task *hlua_process_task(struct task *task)
5363{
5364 struct hlua *hlua = task->context;
5365 enum hlua_exec status;
5366
5367 /* We need to remove the task from the wait queue before executing
5368 * the Lua code because we don't know if it needs to wait for
5369 * another timer or not in the case of E_AGAIN.
5370 */
5371 task_delete(task);
5372
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005373 /* If it is the first call to the task, we must initialize the
5374 * execution timeouts.
5375 */
5376 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005377 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005378
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005379 /* Execute the Lua code. */
5380 status = hlua_ctx_resume(hlua, 1);
5381
5382 switch (status) {
5383 /* finished or yield */
5384 case HLUA_E_OK:
5385 hlua_ctx_destroy(hlua);
5386 task_delete(task);
5387 task_free(task);
5388 break;
5389
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005390 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
5391 if (hlua->wake_time != TICK_ETERNITY)
5392 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005393 break;
5394
5395 /* finished with error. */
5396 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005397 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005398 hlua_ctx_destroy(hlua);
5399 task_delete(task);
5400 task_free(task);
5401 break;
5402
5403 case HLUA_E_ERR:
5404 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005405 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005406 hlua_ctx_destroy(hlua);
5407 task_delete(task);
5408 task_free(task);
5409 break;
5410 }
5411 return NULL;
5412}
5413
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005414/* This function is an LUA binding that register LUA function to be
5415 * executed after the HAProxy configuration parsing and before the
5416 * HAProxy scheduler starts. This function expect only one LUA
5417 * argument that is a function. This function returns nothing, but
5418 * throws if an error is encountered.
5419 */
5420__LJMP static int hlua_register_init(lua_State *L)
5421{
5422 struct hlua_init_function *init;
5423 int ref;
5424
5425 MAY_LJMP(check_args(L, 1, "register_init"));
5426
5427 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5428
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005429 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005430 if (!init)
5431 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5432
5433 init->function_ref = ref;
5434 LIST_ADDQ(&hlua_init_functions, &init->l);
5435 return 0;
5436}
5437
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005438/* This functio is an LUA binding. It permits to register a task
5439 * executed in parallel of the main HAroxy activity. The task is
5440 * created and it is set in the HAProxy scheduler. It can be called
5441 * from the "init" section, "post init" or during the runtime.
5442 *
5443 * Lua prototype:
5444 *
5445 * <none> core.register_task(<function>)
5446 */
5447static int hlua_register_task(lua_State *L)
5448{
5449 struct hlua *hlua;
5450 struct task *task;
5451 int ref;
5452
5453 MAY_LJMP(check_args(L, 1, "register_task"));
5454
5455 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5456
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005457 hlua = pool_alloc2(pool2_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005458 if (!hlua)
5459 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5460
5461 task = task_new();
5462 task->context = hlua;
5463 task->process = hlua_process_task;
5464
5465 if (!hlua_ctx_init(hlua, task))
5466 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5467
5468 /* Restore the function in the stack. */
5469 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5470 hlua->nargs = 0;
5471
5472 /* Schedule task. */
5473 task_schedule(task, now_ms);
5474
5475 return 0;
5476}
5477
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005478/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5479 * doesn't allow "yield" functions because the HAProxy engine cannot
5480 * resume converters.
5481 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005482static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005483{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005484 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005485 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005486 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005487
Willy Tarreaube508f12016-03-10 11:47:01 +01005488 if (!stream)
5489 return 0;
5490
Willy Tarreau87b09662015-04-03 00:22:06 +02005491 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005492 * Lua context can be not initialized. This behavior
5493 * permits to save performances because a systematic
5494 * Lua initialization cause 5% performances loss.
5495 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005496 if (!stream->hlua) {
5497 stream->hlua = pool_alloc2(pool2_hlua);
5498 if (!stream->hlua) {
5499 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5500 return 0;
5501 }
5502 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5503 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5504 return 0;
5505 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005506 }
5507
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005508 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005509 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005510
5511 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005512 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5513 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5514 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005515 else
5516 error = "critical error";
5517 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005518 return 0;
5519 }
5520
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005521 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005522 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005523 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005524 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005525 return 0;
5526 }
5527
5528 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005529 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005530
5531 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005532 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005533 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005534 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005535 return 0;
5536 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005537 hlua_smp2lua(stream->hlua->T, smp);
5538 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005539
5540 /* push keywords in the stack. */
5541 if (arg_p) {
5542 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005543 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005544 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005545 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005546 return 0;
5547 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005548 hlua_arg2lua(stream->hlua->T, arg_p);
5549 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005550 }
5551 }
5552
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005553 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005554 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005555
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005556 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005557 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005558 }
5559
5560 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005561 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005562 /* finished. */
5563 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005564 /* If the stack is empty, the function fails. */
5565 if (lua_gettop(stream->hlua->T) <= 0)
5566 return 0;
5567
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005568 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005569 hlua_lua2smp(stream->hlua->T, -1, smp);
5570 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005571 return 1;
5572
5573 /* yield. */
5574 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005575 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005576 return 0;
5577
5578 /* finished with error. */
5579 case HLUA_E_ERRMSG:
5580 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005581 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005582 fcn->name, lua_tostring(stream->hlua->T, -1));
5583 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005584 return 0;
5585
5586 case HLUA_E_ERR:
5587 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005588 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005589
5590 default:
5591 return 0;
5592 }
5593}
5594
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005595/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5596 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005597 * resume sample-fetches. This function will be called by the sample
5598 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005599 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005600static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5601 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005602{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005603 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005604 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005605 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005606 const struct chunk msg = { .len = 0 };
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005607
Willy Tarreaube508f12016-03-10 11:47:01 +01005608 if (!stream)
5609 return 0;
5610
Willy Tarreau87b09662015-04-03 00:22:06 +02005611 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005612 * Lua context can be not initialized. This behavior
5613 * permits to save performances because a systematic
5614 * Lua initialization cause 5% performances loss.
5615 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005616 if (!stream->hlua) {
5617 stream->hlua = pool_alloc2(pool2_hlua);
5618 if (!stream->hlua) {
5619 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5620 return 0;
5621 }
5622 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5623 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5624 return 0;
5625 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005626 }
5627
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005628 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005629
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005630 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005631 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005632
5633 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005634 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5635 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5636 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005637 else
5638 error = "critical error";
5639 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005640 return 0;
5641 }
5642
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005643 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005644 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005645 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005646 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005647 return 0;
5648 }
5649
5650 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005651 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005652
5653 /* push arguments in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005654 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR,
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005655 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005656 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005657 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005658 return 0;
5659 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005660 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005661
5662 /* push keywords in the stack. */
5663 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5664 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005665 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005666 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005667 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005668 return 0;
5669 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005670 hlua_arg2lua(stream->hlua->T, arg_p);
5671 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005672 }
5673
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005674 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005675 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005676
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005677 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005678 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005679 }
5680
5681 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005682 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005683 /* finished. */
5684 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005685 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005686 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005687 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005688 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005689 /* If the stack is empty, the function fails. */
5690 if (lua_gettop(stream->hlua->T) <= 0)
5691 return 0;
5692
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005693 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005694 hlua_lua2smp(stream->hlua->T, -1, smp);
5695 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005696
5697 /* Set the end of execution flag. */
5698 smp->flags &= ~SMP_F_MAY_CHANGE;
5699 return 1;
5700
5701 /* yield. */
5702 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005703 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005704 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005705 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005706 return 0;
5707
5708 /* finished with error. */
5709 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005710 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005711 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005712 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005713 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005714 fcn->name, lua_tostring(stream->hlua->T, -1));
5715 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005716 return 0;
5717
5718 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005719 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005720 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005721 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005722 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005723
5724 default:
5725 return 0;
5726 }
5727}
5728
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005729/* This function is an LUA binding used for registering
5730 * "sample-conv" functions. It expects a converter name used
5731 * in the haproxy configuration file, and an LUA function.
5732 */
5733__LJMP static int hlua_register_converters(lua_State *L)
5734{
5735 struct sample_conv_kw_list *sck;
5736 const char *name;
5737 int ref;
5738 int len;
5739 struct hlua_function *fcn;
5740
5741 MAY_LJMP(check_args(L, 2, "register_converters"));
5742
5743 /* First argument : converter name. */
5744 name = MAY_LJMP(luaL_checkstring(L, 1));
5745
5746 /* Second argument : lua function. */
5747 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5748
5749 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005750 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005751 if (!sck)
5752 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005753 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005754 if (!fcn)
5755 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5756
5757 /* Fill fcn. */
5758 fcn->name = strdup(name);
5759 if (!fcn->name)
5760 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5761 fcn->function_ref = ref;
5762
5763 /* List head */
5764 sck->list.n = sck->list.p = NULL;
5765
5766 /* converter keyword. */
5767 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005768 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005769 if (!sck->kw[0].kw)
5770 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5771
5772 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5773 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005774 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 +01005775 sck->kw[0].val_args = NULL;
5776 sck->kw[0].in_type = SMP_T_STR;
5777 sck->kw[0].out_type = SMP_T_STR;
5778 sck->kw[0].private = fcn;
5779
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005780 /* Register this new converter */
5781 sample_register_convs(sck);
5782
5783 return 0;
5784}
5785
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005786/* This fucntion is an LUA binding used for registering
5787 * "sample-fetch" functions. It expects a converter name used
5788 * in the haproxy configuration file, and an LUA function.
5789 */
5790__LJMP static int hlua_register_fetches(lua_State *L)
5791{
5792 const char *name;
5793 int ref;
5794 int len;
5795 struct sample_fetch_kw_list *sfk;
5796 struct hlua_function *fcn;
5797
5798 MAY_LJMP(check_args(L, 2, "register_fetches"));
5799
5800 /* First argument : sample-fetch name. */
5801 name = MAY_LJMP(luaL_checkstring(L, 1));
5802
5803 /* Second argument : lua function. */
5804 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5805
5806 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005807 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005808 if (!sfk)
5809 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005810 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005811 if (!fcn)
5812 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5813
5814 /* Fill fcn. */
5815 fcn->name = strdup(name);
5816 if (!fcn->name)
5817 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5818 fcn->function_ref = ref;
5819
5820 /* List head */
5821 sfk->list.n = sfk->list.p = NULL;
5822
5823 /* sample-fetch keyword. */
5824 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005825 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005826 if (!sfk->kw[0].kw)
5827 return luaL_error(L, "lua out of memory error.");
5828
5829 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
5830 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005831 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 +01005832 sfk->kw[0].val_args = NULL;
5833 sfk->kw[0].out_type = SMP_T_STR;
5834 sfk->kw[0].use = SMP_USE_HTTP_ANY;
5835 sfk->kw[0].val = 0;
5836 sfk->kw[0].private = fcn;
5837
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005838 /* Register this new fetch. */
5839 sample_register_fetches(sfk);
5840
5841 return 0;
5842}
5843
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005844/* This function is a wrapper to execute each LUA function declared
5845 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005846 * return ACT_RET_CONT if the processing is finished (with or without
5847 * error) and return ACT_RET_YIELD if the function must be called again
5848 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005849 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005850static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02005851 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005852{
5853 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005854 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005855 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005856 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005857 const struct chunk msg = { .len = 0 };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005858
5859 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01005860 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
5861 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
5862 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
5863 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005864 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005865 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005866 return ACT_RET_CONT;
5867 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005868
Willy Tarreau87b09662015-04-03 00:22:06 +02005869 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005870 * Lua context can be not initialized. This behavior
5871 * permits to save performances because a systematic
5872 * Lua initialization cause 5% performances loss.
5873 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005874 if (!s->hlua) {
5875 s->hlua = pool_alloc2(pool2_hlua);
5876 if (!s->hlua) {
5877 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
5878 rule->arg.hlua_rule->fcn.name);
5879 return ACT_RET_CONT;
5880 }
5881 if (!hlua_ctx_init(s->hlua, s->task)) {
5882 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
5883 rule->arg.hlua_rule->fcn.name);
5884 return ACT_RET_CONT;
5885 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005886 }
5887
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005888 consistency_set(s, dir, &s->hlua->cons);
5889
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005890 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005891 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005892
5893 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005894 if (!SET_SAFE_LJMP(s->hlua->T)) {
5895 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
5896 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005897 else
5898 error = "critical error";
5899 SEND_ERR(px, "Lua function '%s': %s.\n",
5900 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005901 return ACT_RET_CONT;
5902 }
5903
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005904 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005905 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005906 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005907 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005908 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005909 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005910 }
5911
5912 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005913 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005914
Willy Tarreau87b09662015-04-03 00:22:06 +02005915 /* Create and and push object stream in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005916 if (!hlua_txn_new(s->hlua->T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005917 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005918 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005919 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005920 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005921 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005922 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005923
5924 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005925 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005926 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005927 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005928 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005929 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005930 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005931 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005932 lua_pushstring(s->hlua->T, *arg);
5933 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005934 }
5935
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005936 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005937 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005938
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005939 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005940 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005941 }
5942
5943 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005944 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005945 /* finished. */
5946 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005947 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005948 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005949 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005950 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005951 if (s->hlua->flags & HLUA_STOP)
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005952 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005953 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005954
5955 /* yield. */
5956 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005957 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005958 if (s->hlua->wake_time != TICK_ETERNITY) {
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005959 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005960 s->req.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005961 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005962 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005963 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005964 /* Some actions can be wake up when a "write" event
5965 * is detected on a response channel. This is useful
5966 * only for actions targetted on the requests.
5967 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005968 if (HLUA_IS_WAKERESWR(s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005969 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01005970 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005971 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005972 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005973 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005974 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005975 /* We can quit the fcuntion without consistency check
5976 * because HAProxy is not able to manipulate data, it
5977 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005978 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005979
5980 /* finished with error. */
5981 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005982 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005983 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005984 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005985 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005986 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005987 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005988 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
5989 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005990 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005991
5992 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005993 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005994 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005995 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005996 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005997 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005998 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005999 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006000
6001 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006002 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006003 }
6004}
6005
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006006struct task *hlua_applet_wakeup(struct task *t)
6007{
6008 struct appctx *ctx = t->context;
6009 struct stream_interface *si = ctx->owner;
6010
6011 /* If the applet is wake up without any expected work, the sheduler
6012 * remove it from the run queue. This flag indicate that the applet
6013 * is waiting for write. If the buffer is full, the main processing
6014 * will send some data and after call the applet, otherwise it call
6015 * the applet ASAP.
6016 */
6017 si_applet_cant_put(si);
6018 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006019 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006020 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006021}
6022
6023static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6024{
6025 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006026 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006027 struct task *task;
6028 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006029 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006030
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006031 hlua = pool_alloc2(pool2_hlua);
6032 if (!hlua) {
6033 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6034 ctx->rule->arg.hlua_rule->fcn.name);
6035 return 0;
6036 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006037 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006038 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006039 ctx->ctx.hlua_apptcp.flags = 0;
6040
6041 /* Create task used by signal to wakeup applets. */
6042 task = task_new();
6043 if (!task) {
6044 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6045 ctx->rule->arg.hlua_rule->fcn.name);
6046 return 0;
6047 }
6048 task->nice = 0;
6049 task->context = ctx;
6050 task->process = hlua_applet_wakeup;
6051 ctx->ctx.hlua_apptcp.task = task;
6052
6053 /* In the execution wrappers linked with a stream, the
6054 * Lua context can be not initialized. This behavior
6055 * permits to save performances because a systematic
6056 * Lua initialization cause 5% performances loss.
6057 */
6058 if (!hlua_ctx_init(hlua, task)) {
6059 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6060 ctx->rule->arg.hlua_rule->fcn.name);
6061 return 0;
6062 }
6063
6064 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006065 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006066
6067 /* The following Lua calls can fail. */
6068 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006069 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6070 error = lua_tostring(hlua->T, -1);
6071 else
6072 error = "critical error";
6073 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6074 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006075 RESET_SAFE_LJMP(hlua->T);
6076 return 0;
6077 }
6078
6079 /* Check stack available size. */
6080 if (!lua_checkstack(hlua->T, 1)) {
6081 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6082 ctx->rule->arg.hlua_rule->fcn.name);
6083 RESET_SAFE_LJMP(hlua->T);
6084 return 0;
6085 }
6086
6087 /* Restore the function in the stack. */
6088 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6089
6090 /* Create and and push object stream in the stack. */
6091 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
6092 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6093 ctx->rule->arg.hlua_rule->fcn.name);
6094 RESET_SAFE_LJMP(hlua->T);
6095 return 0;
6096 }
6097 hlua->nargs = 1;
6098
6099 /* push keywords in the stack. */
6100 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6101 if (!lua_checkstack(hlua->T, 1)) {
6102 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6103 ctx->rule->arg.hlua_rule->fcn.name);
6104 RESET_SAFE_LJMP(hlua->T);
6105 return 0;
6106 }
6107 lua_pushstring(hlua->T, *arg);
6108 hlua->nargs++;
6109 }
6110
6111 RESET_SAFE_LJMP(hlua->T);
6112
6113 /* Wakeup the applet ASAP. */
6114 si_applet_cant_get(si);
6115 si_applet_cant_put(si);
6116
6117 return 1;
6118}
6119
6120static void hlua_applet_tcp_fct(struct appctx *ctx)
6121{
6122 struct stream_interface *si = ctx->owner;
6123 struct stream *strm = si_strm(si);
6124 struct channel *res = si_ic(si);
6125 struct act_rule *rule = ctx->rule;
6126 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006127 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006128
6129 /* The applet execution is already done. */
6130 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
6131 return;
6132
6133 /* If the stream is disconnect or closed, ldo nothing. */
6134 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6135 return;
6136
6137 /* Execute the function. */
6138 switch (hlua_ctx_resume(hlua, 1)) {
6139 /* finished. */
6140 case HLUA_E_OK:
6141 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6142
6143 /* log time */
6144 strm->logs.tv_request = now;
6145
6146 /* eat the whole request */
6147 bo_skip(si_oc(si), si_ob(si)->o);
6148 res->flags |= CF_READ_NULL;
6149 si_shutr(si);
6150 return;
6151
6152 /* yield. */
6153 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006154 if (hlua->wake_time != TICK_ETERNITY)
6155 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006156 return;
6157
6158 /* finished with error. */
6159 case HLUA_E_ERRMSG:
6160 /* Display log. */
6161 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6162 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6163 lua_pop(hlua->T, 1);
6164 goto error;
6165
6166 case HLUA_E_ERR:
6167 /* Display log. */
6168 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6169 rule->arg.hlua_rule->fcn.name);
6170 goto error;
6171
6172 default:
6173 goto error;
6174 }
6175
6176error:
6177
6178 /* For all other cases, just close the stream. */
6179 si_shutw(si);
6180 si_shutr(si);
6181 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6182}
6183
6184static void hlua_applet_tcp_release(struct appctx *ctx)
6185{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006186 task_delete(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006187 task_free(ctx->ctx.hlua_apptcp.task);
6188 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006189 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006190 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006191}
6192
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006193/* The function returns 1 if the initialisation is complete, 0 if
6194 * an errors occurs and -1 if more data are required for initializing
6195 * the applet.
6196 */
6197static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6198{
6199 struct stream_interface *si = ctx->owner;
6200 struct channel *req = si_oc(si);
6201 struct http_msg *msg;
6202 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006203 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006204 char **arg;
6205 struct hdr_ctx hdr;
6206 struct task *task;
6207 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01006208 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006209
6210 /* Wait for a full HTTP request. */
6211 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
6212 if (smp.flags & SMP_F_MAY_CHANGE)
6213 return -1;
6214 return 0;
6215 }
6216 txn = strm->txn;
6217 msg = &txn->req;
6218
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006219 /* We want two things in HTTP mode :
6220 * - enforce server-close mode if we were in keep-alive, so that the
6221 * applet is released after each response ;
6222 * - enable request body transfer to the applet in order to resync
6223 * with the response body.
6224 */
6225 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
6226 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006227
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006228 hlua = pool_alloc2(pool2_hlua);
6229 if (!hlua) {
6230 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6231 ctx->rule->arg.hlua_rule->fcn.name);
6232 return 0;
6233 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006234 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006235 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006236 ctx->ctx.hlua_apphttp.left_bytes = -1;
6237 ctx->ctx.hlua_apphttp.flags = 0;
6238
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006239 if (txn->req.flags & HTTP_MSGF_VER_11)
6240 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6241
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006242 /* Create task used by signal to wakeup applets. */
6243 task = task_new();
6244 if (!task) {
6245 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6246 ctx->rule->arg.hlua_rule->fcn.name);
6247 return 0;
6248 }
6249 task->nice = 0;
6250 task->context = ctx;
6251 task->process = hlua_applet_wakeup;
6252 ctx->ctx.hlua_apphttp.task = task;
6253
6254 /* In the execution wrappers linked with a stream, the
6255 * Lua context can be not initialized. This behavior
6256 * permits to save performances because a systematic
6257 * Lua initialization cause 5% performances loss.
6258 */
6259 if (!hlua_ctx_init(hlua, task)) {
6260 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6261 ctx->rule->arg.hlua_rule->fcn.name);
6262 return 0;
6263 }
6264
6265 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006266 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006267
6268 /* The following Lua calls can fail. */
6269 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006270 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6271 error = lua_tostring(hlua->T, -1);
6272 else
6273 error = "critical error";
6274 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6275 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006276 return 0;
6277 }
6278
6279 /* Check stack available size. */
6280 if (!lua_checkstack(hlua->T, 1)) {
6281 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6282 ctx->rule->arg.hlua_rule->fcn.name);
6283 RESET_SAFE_LJMP(hlua->T);
6284 return 0;
6285 }
6286
6287 /* Restore the function in the stack. */
6288 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6289
6290 /* Create and and push object stream in the stack. */
6291 if (!hlua_applet_http_new(hlua->T, ctx)) {
6292 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6293 ctx->rule->arg.hlua_rule->fcn.name);
6294 RESET_SAFE_LJMP(hlua->T);
6295 return 0;
6296 }
6297 hlua->nargs = 1;
6298
6299 /* Look for a 100-continue expected. */
6300 if (msg->flags & HTTP_MSGF_VER_11) {
6301 hdr.idx = 0;
6302 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
6303 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
6304 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
6305 }
6306
6307 /* push keywords in the stack. */
6308 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6309 if (!lua_checkstack(hlua->T, 1)) {
6310 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6311 ctx->rule->arg.hlua_rule->fcn.name);
6312 RESET_SAFE_LJMP(hlua->T);
6313 return 0;
6314 }
6315 lua_pushstring(hlua->T, *arg);
6316 hlua->nargs++;
6317 }
6318
6319 RESET_SAFE_LJMP(hlua->T);
6320
6321 /* Wakeup the applet when data is ready for read. */
6322 si_applet_cant_get(si);
6323
6324 return 1;
6325}
6326
6327static void hlua_applet_http_fct(struct appctx *ctx)
6328{
6329 struct stream_interface *si = ctx->owner;
6330 struct stream *strm = si_strm(si);
6331 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006332 struct act_rule *rule = ctx->rule;
6333 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006334 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006335 char *blk1;
6336 int len1;
6337 char *blk2;
6338 int len2;
6339 int ret;
6340
6341 /* If the stream is disconnect or closed, ldo nothing. */
6342 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6343 return;
6344
6345 /* Set the currently running flag. */
6346 if (!HLUA_IS_RUNNING(hlua) &&
6347 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6348
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006349 /* Wait for full HTTP analysys. */
6350 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6351 si_applet_cant_get(si);
6352 return;
6353 }
6354
6355 /* Store the max amount of bytes that we can read. */
6356 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6357
6358 /* We need to flush the request header. This left the body
6359 * for the Lua.
6360 */
6361
6362 /* Read the maximum amount of data avalaible. */
6363 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
6364 if (ret == -1)
6365 return;
6366
6367 /* No data available, ask for more data. */
6368 if (ret == 1)
6369 len2 = 0;
6370 if (ret == 0)
6371 len1 = 0;
6372 if (len1 + len2 < strm->txn->req.eoh + 2) {
6373 si_applet_cant_get(si);
6374 return;
6375 }
6376
6377 /* skip the requests bytes. */
6378 bo_skip(si_oc(si), strm->txn->req.eoh + 2);
6379 }
6380
6381 /* Executes The applet if it is not done. */
6382 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6383
6384 /* Execute the function. */
6385 switch (hlua_ctx_resume(hlua, 1)) {
6386 /* finished. */
6387 case HLUA_E_OK:
6388 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6389 break;
6390
6391 /* yield. */
6392 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006393 if (hlua->wake_time != TICK_ETERNITY)
6394 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006395 return;
6396
6397 /* finished with error. */
6398 case HLUA_E_ERRMSG:
6399 /* Display log. */
6400 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6401 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6402 lua_pop(hlua->T, 1);
6403 goto error;
6404
6405 case HLUA_E_ERR:
6406 /* Display log. */
6407 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6408 rule->arg.hlua_rule->fcn.name);
6409 goto error;
6410
6411 default:
6412 goto error;
6413 }
6414 }
6415
6416 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6417
6418 /* We must send the final chunk. */
6419 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6420 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6421
6422 /* sent last chunk at once. */
6423 ret = bi_putblk(res, "0\r\n\r\n", 5);
6424
6425 /* critical error. */
6426 if (ret == -2 || ret == -3) {
6427 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6428 rule->arg.hlua_rule->fcn.name);
6429 goto error;
6430 }
6431
6432 /* no enough space error. */
6433 if (ret == -1) {
6434 si_applet_cant_put(si);
6435 return;
6436 }
6437
6438 /* set the last chunk sent. */
6439 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6440 }
6441
6442 /* close the connection. */
6443
6444 /* status / log */
6445 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6446 strm->logs.tv_request = now;
6447
6448 /* eat the whole request */
6449 bo_skip(si_oc(si), si_ob(si)->o);
6450 res->flags |= CF_READ_NULL;
6451 si_shutr(si);
6452
6453 return;
6454 }
6455
6456error:
6457
6458 /* If we are in HTTP mode, and we are not send any
6459 * data, return a 500 server error in best effort:
6460 * if there are no room avalaible in the buffer,
6461 * just close the connection.
6462 */
6463 bi_putblk(res, error_500, strlen(error_500));
6464 if (!(strm->flags & SF_ERR_MASK))
6465 strm->flags |= SF_ERR_RESOURCE;
6466 si_shutw(si);
6467 si_shutr(si);
6468 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6469}
6470
6471static void hlua_applet_http_release(struct appctx *ctx)
6472{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006473 task_delete(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006474 task_free(ctx->ctx.hlua_apphttp.task);
6475 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006476 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006477 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006478}
6479
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006480/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6481 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006482 *
6483 * This function can fail with an abort() due to an Lua critical error.
6484 * We are in the configuration parsing process of HAProxy, this abort() is
6485 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006486 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006487static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6488 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006489{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006490 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006491 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006492
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006493 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006494 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006495 if (!rule->arg.hlua_rule) {
6496 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006497 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006498 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006499
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006500 /* Memory for arguments. */
6501 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
6502 if (!rule->arg.hlua_rule->args) {
6503 memprintf(err, "out of memory error");
6504 return ACT_RET_PRS_ERR;
6505 }
6506
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006507 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006508 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006509
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006510 /* Expect some arguments */
6511 for (i = 0; i < fcn->nargs; i++) {
6512 if (*args[i+1] == '\0') {
6513 memprintf(err, "expect %d arguments", fcn->nargs);
6514 return ACT_RET_PRS_ERR;
6515 }
6516 rule->arg.hlua_rule->args[i] = strdup(args[i + 1]);
6517 if (!rule->arg.hlua_rule->args[i]) {
6518 memprintf(err, "out of memory error");
6519 return ACT_RET_PRS_ERR;
6520 }
6521 (*cur_arg)++;
6522 }
6523 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006524
Thierry FOURNIER42148732015-09-02 17:17:33 +02006525 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006526 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006527 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006528}
6529
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006530static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6531 struct act_rule *rule, char **err)
6532{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006533 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006534
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006535 /* HTTP applets are forbidden in tcp-request rules.
6536 * HTTP applet request requires everything initilized by
6537 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6538 * The applet will be immediately initilized, but its before
6539 * the call of this analyzer.
6540 */
6541 if (rule->from != ACT_F_HTTP_REQ) {
6542 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6543 return ACT_RET_PRS_ERR;
6544 }
6545
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006546 /* Memory for the rule. */
6547 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6548 if (!rule->arg.hlua_rule) {
6549 memprintf(err, "out of memory error");
6550 return ACT_RET_PRS_ERR;
6551 }
6552
6553 /* Reference the Lua function and store the reference. */
6554 rule->arg.hlua_rule->fcn = *fcn;
6555
6556 /* TODO: later accept arguments. */
6557 rule->arg.hlua_rule->args = NULL;
6558
6559 /* Add applet pointer in the rule. */
6560 rule->applet.obj_type = OBJ_TYPE_APPLET;
6561 rule->applet.name = fcn->name;
6562 rule->applet.init = hlua_applet_http_init;
6563 rule->applet.fct = hlua_applet_http_fct;
6564 rule->applet.release = hlua_applet_http_release;
6565 rule->applet.timeout = hlua_timeout_applet;
6566
6567 return ACT_RET_PRS_OK;
6568}
6569
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006570/* This function is an LUA binding used for registering
6571 * "sample-conv" functions. It expects a converter name used
6572 * in the haproxy configuration file, and an LUA function.
6573 */
6574__LJMP static int hlua_register_action(lua_State *L)
6575{
6576 struct action_kw_list *akl;
6577 const char *name;
6578 int ref;
6579 int len;
6580 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006581 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006582
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006583 /* Initialise the number of expected arguments at 0. */
6584 nargs = 0;
6585
6586 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6587 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006588
6589 /* First argument : converter name. */
6590 name = MAY_LJMP(luaL_checkstring(L, 1));
6591
6592 /* Second argument : environment. */
6593 if (lua_type(L, 2) != LUA_TTABLE)
6594 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6595
6596 /* Third argument : lua function. */
6597 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6598
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006599 /* Fouth argument : number of mandatories arguments expected on the configuration line. */
6600 if (lua_gettop(L) >= 4)
6601 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
6602
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006603 /* browse the second argulent as an array. */
6604 lua_pushnil(L);
6605 while (lua_next(L, 2) != 0) {
6606 if (lua_type(L, -1) != LUA_TSTRING)
6607 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6608
6609 /* Check required environment. Only accepted "http" or "tcp". */
6610 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006611 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006612 if (!akl)
6613 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006614 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006615 if (!fcn)
6616 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6617
6618 /* Fill fcn. */
6619 fcn->name = strdup(name);
6620 if (!fcn->name)
6621 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6622 fcn->function_ref = ref;
6623
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006624 /* Set the expected number od arguments. */
6625 fcn->nargs = nargs;
6626
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006627 /* List head */
6628 akl->list.n = akl->list.p = NULL;
6629
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006630 /* action keyword. */
6631 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006632 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006633 if (!akl->kw[0].kw)
6634 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6635
6636 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6637
6638 akl->kw[0].match_pfx = 0;
6639 akl->kw[0].private = fcn;
6640 akl->kw[0].parse = action_register_lua;
6641
6642 /* select the action registering point. */
6643 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6644 tcp_req_cont_keywords_register(akl);
6645 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6646 tcp_res_cont_keywords_register(akl);
6647 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6648 http_req_keywords_register(akl);
6649 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6650 http_res_keywords_register(akl);
6651 else
6652 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
6653 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6654 "are expected.", lua_tostring(L, -1)));
6655
6656 /* pop the environment string. */
6657 lua_pop(L, 1);
6658 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006659 return ACT_RET_PRS_OK;
6660}
6661
6662static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6663 struct act_rule *rule, char **err)
6664{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006665 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006666
6667 /* Memory for the rule. */
6668 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6669 if (!rule->arg.hlua_rule) {
6670 memprintf(err, "out of memory error");
6671 return ACT_RET_PRS_ERR;
6672 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006673
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006674 /* Reference the Lua function and store the reference. */
6675 rule->arg.hlua_rule->fcn = *fcn;
6676
6677 /* TODO: later accept arguments. */
6678 rule->arg.hlua_rule->args = NULL;
6679
6680 /* Add applet pointer in the rule. */
6681 rule->applet.obj_type = OBJ_TYPE_APPLET;
6682 rule->applet.name = fcn->name;
6683 rule->applet.init = hlua_applet_tcp_init;
6684 rule->applet.fct = hlua_applet_tcp_fct;
6685 rule->applet.release = hlua_applet_tcp_release;
6686 rule->applet.timeout = hlua_timeout_applet;
6687
6688 return 0;
6689}
6690
6691/* This function is an LUA binding used for registering
6692 * "sample-conv" functions. It expects a converter name used
6693 * in the haproxy configuration file, and an LUA function.
6694 */
6695__LJMP static int hlua_register_service(lua_State *L)
6696{
6697 struct action_kw_list *akl;
6698 const char *name;
6699 const char *env;
6700 int ref;
6701 int len;
6702 struct hlua_function *fcn;
6703
6704 MAY_LJMP(check_args(L, 3, "register_service"));
6705
6706 /* First argument : converter name. */
6707 name = MAY_LJMP(luaL_checkstring(L, 1));
6708
6709 /* Second argument : environment. */
6710 env = MAY_LJMP(luaL_checkstring(L, 2));
6711
6712 /* Third argument : lua function. */
6713 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6714
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006715 /* Allocate and fill the sample fetch keyword struct. */
6716 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6717 if (!akl)
6718 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6719 fcn = calloc(1, sizeof(*fcn));
6720 if (!fcn)
6721 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6722
6723 /* Fill fcn. */
6724 len = strlen("<lua.>") + strlen(name) + 1;
6725 fcn->name = calloc(1, len);
6726 if (!fcn->name)
6727 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6728 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6729 fcn->function_ref = ref;
6730
6731 /* List head */
6732 akl->list.n = akl->list.p = NULL;
6733
6734 /* converter keyword. */
6735 len = strlen("lua.") + strlen(name) + 1;
6736 akl->kw[0].kw = calloc(1, len);
6737 if (!akl->kw[0].kw)
6738 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6739
6740 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6741
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01006742 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006743 if (strcmp(env, "tcp") == 0)
6744 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006745 else if (strcmp(env, "http") == 0)
6746 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006747 else
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006748 WILL_LJMP(luaL_error(L, "lua service environment '%s' is unknown. "
6749 "'tcp' or 'http' are expected."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006750
6751 akl->kw[0].match_pfx = 0;
6752 akl->kw[0].private = fcn;
6753
6754 /* End of array. */
6755 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6756
6757 /* Register this new converter */
6758 service_keywords_register(akl);
6759
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006760 return 0;
6761}
6762
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006763/* This function initialises Lua cli handler. It copies the
6764 * arguments in the Lua stack and create channel IO objects.
6765 */
6766static int hlua_cli_parse_fct(char **args, struct appctx *appctx, void *private)
6767{
6768 struct hlua *hlua;
6769 struct hlua_function *fcn;
6770 int i;
6771 const char *error;
6772
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006773 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006774 appctx->ctx.hlua_cli.fcn = private;
6775
6776 hlua = pool_alloc2(pool2_hlua);
6777 if (!hlua) {
6778 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006779 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006780 }
6781 HLUA_INIT(hlua);
6782 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006783
6784 /* Create task used by signal to wakeup applets.
6785 * We use the same wakeup fonction than the Lua applet_tcp and
6786 * applet_http. It is absolutely compatible.
6787 */
6788 appctx->ctx.hlua_cli.task = task_new();
6789 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01006790 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006791 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006792 }
6793 appctx->ctx.hlua_cli.task->nice = 0;
6794 appctx->ctx.hlua_cli.task->context = appctx;
6795 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
6796
6797 /* Initialises the Lua context */
6798 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
6799 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006800 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006801 }
6802
6803 /* The following Lua calls can fail. */
6804 if (!SET_SAFE_LJMP(hlua->T)) {
6805 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6806 error = lua_tostring(hlua->T, -1);
6807 else
6808 error = "critical error";
6809 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
6810 goto error;
6811 }
6812
6813 /* Check stack available size. */
6814 if (!lua_checkstack(hlua->T, 2)) {
6815 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6816 goto error;
6817 }
6818
6819 /* Restore the function in the stack. */
6820 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
6821
6822 /* Once the arguments parsed, the CLI is like an AppletTCP,
6823 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006824 */
6825 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
6826 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6827 goto error;
6828 }
6829 hlua->nargs = 1;
6830
6831 /* push keywords in the stack. */
6832 for (i = 0; *args[i]; i++) {
6833 /* Check stack available size. */
6834 if (!lua_checkstack(hlua->T, 1)) {
6835 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6836 goto error;
6837 }
6838 lua_pushstring(hlua->T, args[i]);
6839 hlua->nargs++;
6840 }
6841
6842 /* We must initialize the execution timeouts. */
6843 hlua->max_time = hlua_timeout_session;
6844
6845 /* At this point the execution is safe. */
6846 RESET_SAFE_LJMP(hlua->T);
6847
6848 /* It's ok */
6849 return 0;
6850
6851 /* It's not ok. */
6852error:
6853 RESET_SAFE_LJMP(hlua->T);
6854 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006855 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006856 return 1;
6857}
6858
6859static int hlua_cli_io_handler_fct(struct appctx *appctx)
6860{
6861 struct hlua *hlua;
6862 struct stream_interface *si;
6863 struct hlua_function *fcn;
6864
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006865 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006866 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01006867 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006868
6869 /* If the stream is disconnect or closed, ldo nothing. */
6870 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6871 return 1;
6872
6873 /* Execute the function. */
6874 switch (hlua_ctx_resume(hlua, 1)) {
6875
6876 /* finished. */
6877 case HLUA_E_OK:
6878 return 1;
6879
6880 /* yield. */
6881 case HLUA_E_AGAIN:
6882 /* We want write. */
6883 if (HLUA_IS_WAKERESWR(hlua))
6884 si_applet_cant_put(si);
6885 /* Set the timeout. */
6886 if (hlua->wake_time != TICK_ETERNITY)
6887 task_schedule(hlua->task, hlua->wake_time);
6888 return 0;
6889
6890 /* finished with error. */
6891 case HLUA_E_ERRMSG:
6892 /* Display log. */
6893 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
6894 fcn->name, lua_tostring(hlua->T, -1));
6895 lua_pop(hlua->T, 1);
6896 return 1;
6897
6898 case HLUA_E_ERR:
6899 /* Display log. */
6900 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
6901 fcn->name);
6902 return 1;
6903
6904 default:
6905 return 1;
6906 }
6907
6908 return 1;
6909}
6910
6911static void hlua_cli_io_release_fct(struct appctx *appctx)
6912{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006913 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006914 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006915}
6916
6917/* This function is an LUA binding used for registering
6918 * new keywords in the cli. It expects a list of keywords
6919 * which are the "path". It is limited to 5 keywords. A
6920 * description of the command, a function to be executed
6921 * for the parsing and a function for io handlers.
6922 */
6923__LJMP static int hlua_register_cli(lua_State *L)
6924{
6925 struct cli_kw_list *cli_kws;
6926 const char *message;
6927 int ref_io;
6928 int len;
6929 struct hlua_function *fcn;
6930 int index;
6931 int i;
6932
6933 MAY_LJMP(check_args(L, 3, "register_cli"));
6934
6935 /* First argument : an array of maximum 5 keywords. */
6936 if (!lua_istable(L, 1))
6937 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
6938
6939 /* Second argument : string with contextual message. */
6940 message = MAY_LJMP(luaL_checkstring(L, 2));
6941
6942 /* Third and fourth argument : lua function. */
6943 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
6944
6945 /* Allocate and fill the sample fetch keyword struct. */
6946 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
6947 if (!cli_kws)
6948 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6949 fcn = calloc(1, sizeof(*fcn));
6950 if (!fcn)
6951 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6952
6953 /* Fill path. */
6954 index = 0;
6955 lua_pushnil(L);
6956 while(lua_next(L, 1) != 0) {
6957 if (index >= 5)
6958 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
6959 if (lua_type(L, -1) != LUA_TSTRING)
6960 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
6961 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
6962 if (!cli_kws->kw[0].str_kw[index])
6963 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6964 index++;
6965 lua_pop(L, 1);
6966 }
6967
6968 /* Copy help message. */
6969 cli_kws->kw[0].usage = strdup(message);
6970 if (!cli_kws->kw[0].usage)
6971 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6972
6973 /* Fill fcn io handler. */
6974 len = strlen("<lua.cli>") + 1;
6975 for (i = 0; i < index; i++)
6976 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
6977 fcn->name = calloc(1, len);
6978 if (!fcn->name)
6979 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6980 strncat((char *)fcn->name, "<lua.cli", len);
6981 for (i = 0; i < index; i++) {
6982 strncat((char *)fcn->name, ".", len);
6983 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
6984 }
6985 strncat((char *)fcn->name, ">", len);
6986 fcn->function_ref = ref_io;
6987
6988 /* Fill last entries. */
6989 cli_kws->kw[0].private = fcn;
6990 cli_kws->kw[0].parse = hlua_cli_parse_fct;
6991 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
6992 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
6993
6994 /* Register this new converter */
6995 cli_register_kw(cli_kws);
6996
6997 return 0;
6998}
6999
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007000static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
7001 struct proxy *defpx, const char *file, int line,
7002 char **err, unsigned int *timeout)
7003{
7004 const char *error;
7005
7006 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
7007 if (error && *error != '\0') {
7008 memprintf(err, "%s: invalid timeout", args[0]);
7009 return -1;
7010 }
7011 return 0;
7012}
7013
7014static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
7015 struct proxy *defpx, const char *file, int line,
7016 char **err)
7017{
7018 return hlua_read_timeout(args, section_type, curpx, defpx,
7019 file, line, err, &hlua_timeout_session);
7020}
7021
7022static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
7023 struct proxy *defpx, const char *file, int line,
7024 char **err)
7025{
7026 return hlua_read_timeout(args, section_type, curpx, defpx,
7027 file, line, err, &hlua_timeout_task);
7028}
7029
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007030static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
7031 struct proxy *defpx, const char *file, int line,
7032 char **err)
7033{
7034 return hlua_read_timeout(args, section_type, curpx, defpx,
7035 file, line, err, &hlua_timeout_applet);
7036}
7037
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007038static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
7039 struct proxy *defpx, const char *file, int line,
7040 char **err)
7041{
7042 char *error;
7043
7044 hlua_nb_instruction = strtoll(args[1], &error, 10);
7045 if (*error != '\0') {
7046 memprintf(err, "%s: invalid number", args[0]);
7047 return -1;
7048 }
7049 return 0;
7050}
7051
Willy Tarreau32f61e22015-03-18 17:54:59 +01007052static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
7053 struct proxy *defpx, const char *file, int line,
7054 char **err)
7055{
7056 char *error;
7057
7058 if (*(args[1]) == 0) {
7059 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
7060 return -1;
7061 }
7062 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
7063 if (*error != '\0') {
7064 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
7065 return -1;
7066 }
7067 return 0;
7068}
7069
7070
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007071/* This function is called by the main configuration key "lua-load". It loads and
7072 * execute an lua file during the parsing of the HAProxy configuration file. It is
7073 * the main lua entry point.
7074 *
7075 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
7076 * occured, otherwise it returns 0.
7077 *
7078 * In some error case, LUA set an error message in top of the stack. This function
7079 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007080 *
7081 * This function can fail with an abort() due to an Lua critical error.
7082 * We are in the configuration parsing process of HAProxy, this abort() is
7083 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007084 */
7085static int hlua_load(char **args, int section_type, struct proxy *curpx,
7086 struct proxy *defpx, const char *file, int line,
7087 char **err)
7088{
7089 int error;
7090
7091 /* Just load and compile the file. */
7092 error = luaL_loadfile(gL.T, args[1]);
7093 if (error) {
7094 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
7095 lua_pop(gL.T, 1);
7096 return -1;
7097 }
7098
7099 /* If no syntax error where detected, execute the code. */
7100 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
7101 switch (error) {
7102 case LUA_OK:
7103 break;
7104 case LUA_ERRRUN:
7105 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
7106 lua_pop(gL.T, 1);
7107 return -1;
7108 case LUA_ERRMEM:
7109 memprintf(err, "lua out of memory error\n");
7110 return -1;
7111 case LUA_ERRERR:
7112 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
7113 lua_pop(gL.T, 1);
7114 return -1;
7115 case LUA_ERRGCMM:
7116 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
7117 lua_pop(gL.T, 1);
7118 return -1;
7119 default:
7120 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
7121 lua_pop(gL.T, 1);
7122 return -1;
7123 }
7124
7125 return 0;
7126}
7127
7128/* configuration keywords declaration */
7129static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007130 { CFG_GLOBAL, "lua-load", hlua_load },
7131 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
7132 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02007133 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007134 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01007135 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007136 { 0, NULL, NULL },
7137}};
7138
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007139/* This function can fail with an abort() due to an Lua critical error.
7140 * We are in the initialisation process of HAProxy, this abort() is
7141 * tolerated.
7142 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007143int hlua_post_init()
7144{
7145 struct hlua_init_function *init;
7146 const char *msg;
7147 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007148 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007149
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007150 /* Call post initialisation function in safe environement. */
7151 if (!SET_SAFE_LJMP(gL.T)) {
7152 if (lua_type(gL.T, -1) == LUA_TSTRING)
7153 error = lua_tostring(gL.T, -1);
7154 else
7155 error = "critical error";
7156 fprintf(stderr, "Lua post-init: %s.\n", error);
7157 exit(1);
7158 }
7159 hlua_fcn_post_init(gL.T);
7160 RESET_SAFE_LJMP(gL.T);
7161
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007162 list_for_each_entry(init, &hlua_init_functions, l) {
7163 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7164 ret = hlua_ctx_resume(&gL, 0);
7165 switch (ret) {
7166 case HLUA_E_OK:
7167 lua_pop(gL.T, -1);
7168 return 1;
7169 case HLUA_E_AGAIN:
7170 Alert("lua init: yield not allowed.\n");
7171 return 0;
7172 case HLUA_E_ERRMSG:
7173 msg = lua_tostring(gL.T, -1);
7174 Alert("lua init: %s.\n", msg);
7175 return 0;
7176 case HLUA_E_ERR:
7177 default:
7178 Alert("lua init: unknown runtime error.\n");
7179 return 0;
7180 }
7181 }
7182 return 1;
7183}
7184
Willy Tarreau32f61e22015-03-18 17:54:59 +01007185/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7186 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7187 * is the previously allocated size or the kind of object in case of a new
7188 * allocation. <nsize> is the requested new size.
7189 */
7190static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7191{
7192 struct hlua_mem_allocator *zone = ud;
7193
7194 if (nsize == 0) {
7195 /* it's a free */
7196 if (ptr)
7197 zone->allocated -= osize;
7198 free(ptr);
7199 return NULL;
7200 }
7201
7202 if (!ptr) {
7203 /* it's a new allocation */
7204 if (zone->limit && zone->allocated + nsize > zone->limit)
7205 return NULL;
7206
7207 ptr = malloc(nsize);
7208 if (ptr)
7209 zone->allocated += nsize;
7210 return ptr;
7211 }
7212
7213 /* it's a realloc */
7214 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7215 return NULL;
7216
7217 ptr = realloc(ptr, nsize);
7218 if (ptr)
7219 zone->allocated += nsize - osize;
7220 return ptr;
7221}
7222
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007223/* Ithis function can fail with an abort() due to an Lua critical error.
7224 * We are in the initialisation process of HAProxy, this abort() is
7225 * tolerated.
7226 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007227void hlua_init(void)
7228{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007229 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007230 int idx;
7231 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007232 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007233 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007234 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007235#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007236 struct srv_kw *kw;
7237 int tmp_error;
7238 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007239 char *args[] = { /* SSL client configuration. */
7240 "ssl",
7241 "verify",
7242 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007243 NULL
7244 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007245#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007246
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007247 /* Initialise struct hlua and com signals pool */
7248 pool2_hlua = create_pool("hlua", sizeof(struct hlua), MEM_F_SHARED);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007249
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007250 /* Register configuration keywords. */
7251 cfg_register_keywords(&cfg_kws);
7252
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007253 /* Init main lua stack. */
7254 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01007255 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007256 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02007257 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007258 hlua_sethlua(&gL);
7259 gL.Tref = LUA_REFNIL;
7260 gL.task = NULL;
7261
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007262 /* From this point, until the end of the initialisation fucntion,
7263 * the Lua function can fail with an abort. We are in the initialisation
7264 * process of HAProxy, this abort() is tolerated.
7265 */
7266
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007267 /* Initialise lua. */
7268 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007269
Thierry Fournier75933d42016-01-21 09:30:18 +01007270 /* Set safe environment for the initialisation. */
7271 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007272 if (lua_type(gL.T, -1) == LUA_TSTRING)
7273 error_msg = lua_tostring(gL.T, -1);
7274 else
7275 error_msg = "critical error";
7276 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01007277 exit(1);
7278 }
7279
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007280 /*
7281 *
7282 * Create "core" object.
7283 *
7284 */
7285
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01007286 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007287 lua_newtable(gL.T);
7288
7289 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007290 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007291 hlua_class_const_int(gL.T, log_levels[i], i);
7292
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007293 /* Register special functions. */
7294 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007295 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007296 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007297 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007298 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007299 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007300 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007301 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01007302 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007303 hlua_class_function(gL.T, "sleep", hlua_sleep);
7304 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01007305 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
7306 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
7307 hlua_class_function(gL.T, "set_map", hlua_set_map);
7308 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007309 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007310 hlua_class_function(gL.T, "log", hlua_log);
7311 hlua_class_function(gL.T, "Debug", hlua_log_debug);
7312 hlua_class_function(gL.T, "Info", hlua_log_info);
7313 hlua_class_function(gL.T, "Warning", hlua_log_warning);
7314 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02007315 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01007316 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007317
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007318 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007319
7320 /*
7321 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007322 * Register class Map
7323 *
7324 */
7325
7326 /* This table entry is the object "Map" base. */
7327 lua_newtable(gL.T);
7328
7329 /* register pattern types. */
7330 for (i=0; i<PAT_MATCH_NUM; i++)
7331 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007332 for (i=0; i<PAT_MATCH_NUM; i++) {
7333 snprintf(trash.str, trash.size, "_%s", pat_match_names[i]);
7334 hlua_class_const_int(gL.T, trash.str, i);
7335 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007336
7337 /* register constructor. */
7338 hlua_class_function(gL.T, "new", hlua_map_new);
7339
7340 /* Create and fill the metatable. */
7341 lua_newtable(gL.T);
7342
7343 /* Create and fille the __index entry. */
7344 lua_pushstring(gL.T, "__index");
7345 lua_newtable(gL.T);
7346
7347 /* Register . */
7348 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
7349 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
7350
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007351 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007352
Thierry Fournier45e78d72016-02-19 18:34:46 +01007353 /* Register previous table in the registry with reference and named entry.
7354 * The function hlua_register_metatable() pops the stack, so we
7355 * previously create a copy of the table.
7356 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007357 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007358 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007359
7360 /* Assign the metatable to the mai Map object. */
7361 lua_setmetatable(gL.T, -2);
7362
7363 /* Set a name to the table. */
7364 lua_setglobal(gL.T, "Map");
7365
7366 /*
7367 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007368 * Register class Channel
7369 *
7370 */
7371
7372 /* Create and fill the metatable. */
7373 lua_newtable(gL.T);
7374
7375 /* Create and fille the __index entry. */
7376 lua_pushstring(gL.T, "__index");
7377 lua_newtable(gL.T);
7378
7379 /* Register . */
7380 hlua_class_function(gL.T, "get", hlua_channel_get);
7381 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7382 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7383 hlua_class_function(gL.T, "set", hlua_channel_set);
7384 hlua_class_function(gL.T, "append", hlua_channel_append);
7385 hlua_class_function(gL.T, "send", hlua_channel_send);
7386 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7387 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7388 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007389 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007390
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007391 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007392
7393 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007394 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007395
7396 /*
7397 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007398 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007399 *
7400 */
7401
7402 /* Create and fill the metatable. */
7403 lua_newtable(gL.T);
7404
7405 /* Create and fille the __index entry. */
7406 lua_pushstring(gL.T, "__index");
7407 lua_newtable(gL.T);
7408
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007409 /* Browse existing fetches and create the associated
7410 * object method.
7411 */
7412 sf = NULL;
7413 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7414
7415 /* Dont register the keywork if the arguments check function are
7416 * not safe during the runtime.
7417 */
7418 if ((sf->val_args != NULL) &&
7419 (sf->val_args != val_payload_lv) &&
7420 (sf->val_args != val_hdr))
7421 continue;
7422
7423 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7424 * by an underscore.
7425 */
7426 strncpy(trash.str, sf->kw, trash.size);
7427 trash.str[trash.size - 1] = '\0';
7428 for (p = trash.str; *p; p++)
7429 if (*p == '.' || *p == '-' || *p == '+')
7430 *p = '_';
7431
7432 /* Register the function. */
7433 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007434 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007435 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007436 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007437 }
7438
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007439 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007440
7441 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007442 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007443
7444 /*
7445 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007446 * Register class Converters
7447 *
7448 */
7449
7450 /* Create and fill the metatable. */
7451 lua_newtable(gL.T);
7452
7453 /* Create and fill the __index entry. */
7454 lua_pushstring(gL.T, "__index");
7455 lua_newtable(gL.T);
7456
7457 /* Browse existing converters and create the associated
7458 * object method.
7459 */
7460 sc = NULL;
7461 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7462 /* Dont register the keywork if the arguments check function are
7463 * not safe during the runtime.
7464 */
7465 if (sc->val_args != NULL)
7466 continue;
7467
7468 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7469 * by an underscore.
7470 */
7471 strncpy(trash.str, sc->kw, trash.size);
7472 trash.str[trash.size - 1] = '\0';
7473 for (p = trash.str; *p; p++)
7474 if (*p == '.' || *p == '-' || *p == '+')
7475 *p = '_';
7476
7477 /* Register the function. */
7478 lua_pushstring(gL.T, trash.str);
7479 lua_pushlightuserdata(gL.T, sc);
7480 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007481 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007482 }
7483
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007484 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007485
7486 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007487 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007488
7489 /*
7490 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007491 * Register class HTTP
7492 *
7493 */
7494
7495 /* Create and fill the metatable. */
7496 lua_newtable(gL.T);
7497
7498 /* Create and fille the __index entry. */
7499 lua_pushstring(gL.T, "__index");
7500 lua_newtable(gL.T);
7501
7502 /* Register Lua functions. */
7503 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7504 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7505 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7506 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7507 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7508 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7509 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7510 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7511 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7512 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7513
7514 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7515 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7516 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7517 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7518 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7519 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007520 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007521
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007522 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007523
7524 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007525 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007526
7527 /*
7528 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007529 * Register class AppletTCP
7530 *
7531 */
7532
7533 /* Create and fill the metatable. */
7534 lua_newtable(gL.T);
7535
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007536 /* Create and fille the __index entry. */
7537 lua_pushstring(gL.T, "__index");
7538 lua_newtable(gL.T);
7539
7540 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01007541 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7542 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7543 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7544 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7545 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007546 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
7547 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
7548 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007549
7550 lua_settable(gL.T, -3);
7551
7552 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007553 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007554
7555 /*
7556 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007557 * Register class AppletHTTP
7558 *
7559 */
7560
7561 /* Create and fill the metatable. */
7562 lua_newtable(gL.T);
7563
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007564 /* Create and fille the __index entry. */
7565 lua_pushstring(gL.T, "__index");
7566 lua_newtable(gL.T);
7567
7568 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007569 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7570 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007571 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
7572 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
7573 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007574 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7575 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7576 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7577 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7578 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7579 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7580
7581 lua_settable(gL.T, -3);
7582
7583 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007584 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007585
7586 /*
7587 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007588 * Register class TXN
7589 *
7590 */
7591
7592 /* Create and fill the metatable. */
7593 lua_newtable(gL.T);
7594
7595 /* Create and fille the __index entry. */
7596 lua_pushstring(gL.T, "__index");
7597 lua_newtable(gL.T);
7598
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007599 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01007600 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7601 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007602 hlua_class_function(gL.T, "set_var", hlua_set_var);
Christopher Faulet85d79c92016-11-09 16:54:56 +01007603 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007604 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007605 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007606 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
7607 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7608 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007609 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7610 hlua_class_function(gL.T, "log", hlua_txn_log);
7611 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7612 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7613 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7614 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007615
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007616 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007617
7618 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007619 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007620
7621 /*
7622 *
7623 * Register class Socket
7624 *
7625 */
7626
7627 /* Create and fill the metatable. */
7628 lua_newtable(gL.T);
7629
7630 /* Create and fille the __index entry. */
7631 lua_pushstring(gL.T, "__index");
7632 lua_newtable(gL.T);
7633
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007634#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007635 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007636#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007637 hlua_class_function(gL.T, "connect", hlua_socket_connect);
7638 hlua_class_function(gL.T, "send", hlua_socket_send);
7639 hlua_class_function(gL.T, "receive", hlua_socket_receive);
7640 hlua_class_function(gL.T, "close", hlua_socket_close);
7641 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
7642 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
7643 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
7644 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
7645
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007646 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007647
7648 /* Register the garbage collector entry. */
7649 lua_pushstring(gL.T, "__gc");
7650 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007651 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007652
7653 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007654 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007655
7656 /* Proxy and server configuration initialisation. */
7657 memset(&socket_proxy, 0, sizeof(socket_proxy));
7658 init_new_proxy(&socket_proxy);
7659 socket_proxy.parent = NULL;
7660 socket_proxy.last_change = now.tv_sec;
7661 socket_proxy.id = "LUA-SOCKET";
7662 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
7663 socket_proxy.maxconn = 0;
7664 socket_proxy.accept = NULL;
7665 socket_proxy.options2 |= PR_O2_INDEPSTR;
7666 socket_proxy.srv = NULL;
7667 socket_proxy.conn_retries = 0;
7668 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
7669
7670 /* Init TCP server: unchanged parameters */
7671 memset(&socket_tcp, 0, sizeof(socket_tcp));
7672 socket_tcp.next = NULL;
7673 socket_tcp.proxy = &socket_proxy;
7674 socket_tcp.obj_type = OBJ_TYPE_SERVER;
7675 LIST_INIT(&socket_tcp.actconns);
7676 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007677 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007678 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007679 LIST_INIT(&socket_tcp.safe_conns);
Emeric Brun52a91d32017-08-31 14:41:55 +02007680 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007681 socket_tcp.last_change = 0;
7682 socket_tcp.id = "LUA-TCP-CONN";
7683 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7684 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7685 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
7686
7687 /* XXX: Copy default parameter from default server,
7688 * but the default server is not initialized.
7689 */
7690 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
7691 socket_tcp.minconn = socket_proxy.defsrv.minconn;
7692 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
7693 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
7694 socket_tcp.onerror = socket_proxy.defsrv.onerror;
7695 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7696 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
7697 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7698 socket_tcp.uweight = socket_proxy.defsrv.iweight;
7699 socket_tcp.iweight = socket_proxy.defsrv.iweight;
7700
7701 socket_tcp.check.status = HCHK_STATUS_INI;
7702 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
7703 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
7704 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
7705 socket_tcp.check.server = &socket_tcp;
7706
7707 socket_tcp.agent.status = HCHK_STATUS_INI;
7708 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
7709 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
7710 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
7711 socket_tcp.agent.server = &socket_tcp;
7712
Willy Tarreaua261e9b2016-12-22 20:44:00 +01007713 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007714
7715#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007716 /* Init TCP server: unchanged parameters */
7717 memset(&socket_ssl, 0, sizeof(socket_ssl));
7718 socket_ssl.next = NULL;
7719 socket_ssl.proxy = &socket_proxy;
7720 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7721 LIST_INIT(&socket_ssl.actconns);
7722 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007723 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007724 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007725 LIST_INIT(&socket_ssl.safe_conns);
Emeric Brun52a91d32017-08-31 14:41:55 +02007726 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007727 socket_ssl.last_change = 0;
7728 socket_ssl.id = "LUA-SSL-CONN";
7729 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7730 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7731 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7732
7733 /* XXX: Copy default parameter from default server,
7734 * but the default server is not initialized.
7735 */
7736 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7737 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7738 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7739 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7740 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7741 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7742 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7743 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7744 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7745 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7746
7747 socket_ssl.check.status = HCHK_STATUS_INI;
7748 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7749 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7750 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7751 socket_ssl.check.server = &socket_ssl;
7752
7753 socket_ssl.agent.status = HCHK_STATUS_INI;
7754 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7755 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7756 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7757 socket_ssl.agent.server = &socket_ssl;
7758
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007759 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01007760 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007761
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007762 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007763 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7764 /*
7765 *
7766 * If the keyword is not known, we can search in the registered
7767 * server keywords. This is usefull to configure special SSL
7768 * features like client certificates and ssl_verify.
7769 *
7770 */
7771 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7772 if (tmp_error != 0) {
7773 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7774 abort(); /* This must be never arrives because the command line
7775 not editable by the user. */
7776 }
7777 idx += kw->skip;
7778 }
7779 }
7780
7781 /* Initialize SSL server. */
Willy Tarreau17d45382016-12-22 21:16:08 +01007782 if (socket_ssl.xprt->prepare_srv)
7783 socket_ssl.xprt->prepare_srv(&socket_ssl);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007784#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01007785
7786 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007787}
Willy Tarreaubb57d942016-12-21 19:04:56 +01007788
7789__attribute__((constructor))
7790static void __hlua_init(void)
7791{
7792 char *ptr = NULL;
7793 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
7794 hap_register_build_opts(ptr, 1);
7795}