blob: acf5896968f91082e4ca09338f2a986083ac4f29 [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 */
2418 jobs++;
2419 totalconn++;
2420
Willy Tarreau87787ac2017-08-28 16:22:54 +02002421 task_wakeup(strm->task, TASK_WOKEN_INIT);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002422 /* Return yield waiting for connection. */
2423 return 1;
2424
Willy Tarreaud420a972015-04-06 00:39:18 +02002425 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002426 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002427 out_fail_sess:
2428 appctx_free(appctx);
2429 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002430 WILL_LJMP(lua_error(L));
2431 return 0;
2432}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002433
2434/*
2435 *
2436 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002437 * Class Channel
2438 *
2439 *
2440 */
2441
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002442/* The state between the channel data and the HTTP parser state can be
2443 * unconsistent, so reset the parser and call it again. Warning, this
2444 * action not revalidate the request and not send a 400 if the modified
2445 * resuest is not valid.
2446 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002447 * This function never fails. The direction is set using dir, which equals
2448 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002449 */
2450static void hlua_resynchonize_proto(struct stream *stream, int dir)
2451{
2452 /* Protocol HTTP. */
2453 if (stream->be->mode == PR_MODE_HTTP) {
2454
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002455 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002456 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002457 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002458 http_txn_reset_res(stream->txn);
2459
2460 if (stream->txn->hdr_idx.v)
2461 hdr_idx_init(&stream->txn->hdr_idx);
2462
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002463 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002464 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002465 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002466 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2467 }
2468}
2469
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002470/* This function is called before the Lua execution. It stores
2471 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002472 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002473static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002474{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002475 c->mode = stream->be->mode;
2476 switch (c->mode) {
2477 case PR_MODE_HTTP:
2478 c->data.http.dir = opt & SMP_OPT_DIR;
2479 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2480 c->data.http.state = stream->txn->req.msg_state;
2481 else
2482 c->data.http.state = stream->txn->rsp.msg_state;
2483 break;
2484 default:
2485 break;
2486 }
2487}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002488
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002489/* This function is called after the Lua execution. it
2490 * returns true if the parser state is consistent, otherwise,
2491 * it return false.
2492 *
2493 * In HTTP mode, the parser state must be in the same state
2494 * or greater when we exit the function. Even if we do a
2495 * control yield. This prevent to break the HTTP message
2496 * from the Lua code.
2497 */
2498static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2499{
2500 if (c->mode != stream->be->mode)
2501 return 0;
2502
2503 switch (c->mode) {
2504 case PR_MODE_HTTP:
2505 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002506 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002507 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2508 return stream->txn->req.msg_state >= c->data.http.state;
2509 else
2510 return stream->txn->rsp.msg_state >= c->data.http.state;
2511 default:
2512 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002513 }
2514 return 1;
2515}
2516
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002517/* Returns the struct hlua_channel join to the class channel in the
2518 * stack entry "ud" or throws an argument error.
2519 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002520__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002521{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002522 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002523}
2524
Willy Tarreau47860ed2015-03-10 14:07:50 +01002525/* Pushes the channel onto the top of the stack. If the stask does not have a
2526 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002527 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002528static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002529{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002530 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002531 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002532 return 0;
2533
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002534 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002535 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002536 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002537
2538 /* Pop a class sesison metatable and affect it to the userdata. */
2539 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2540 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002541 return 1;
2542}
2543
2544/* Duplicate all the data present in the input channel and put it
2545 * in a string LUA variables. Returns -1 and push a nil value in
2546 * the stack if the channel is closed and all the data are consumed,
2547 * returns 0 if no data are available, otherwise it returns the length
2548 * of the builded string.
2549 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002550static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002551{
2552 char *blk1;
2553 char *blk2;
2554 int len1;
2555 int len2;
2556 int ret;
2557 luaL_Buffer b;
2558
Willy Tarreau47860ed2015-03-10 14:07:50 +01002559 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002560 if (unlikely(ret == 0))
2561 return 0;
2562
2563 if (unlikely(ret < 0)) {
2564 lua_pushnil(L);
2565 return -1;
2566 }
2567
2568 luaL_buffinit(L, &b);
2569 luaL_addlstring(&b, blk1, len1);
2570 if (unlikely(ret == 2))
2571 luaL_addlstring(&b, blk2, len2);
2572 luaL_pushresult(&b);
2573
2574 if (unlikely(ret == 2))
2575 return len1 + len2;
2576 return len1;
2577}
2578
2579/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2580 * a yield. This function keep the data in the buffer.
2581 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002582__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002583{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002584 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002585
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002586 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2587
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002588 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002589 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002590 return 1;
2591}
2592
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002593/* Check arguments for the function "hlua_channel_dup_yield". */
2594__LJMP static int hlua_channel_dup(lua_State *L)
2595{
2596 MAY_LJMP(check_args(L, 1, "dup"));
2597 MAY_LJMP(hlua_checkchannel(L, 1));
2598 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2599}
2600
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002601/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2602 * a yield. This function consumes the data in the buffer. It returns
2603 * a string containing the data or a nil pointer if no data are available
2604 * and the channel is closed.
2605 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002606__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002607{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002608 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002609 int ret;
2610
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002611 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002612
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002613 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002614 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002615 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002616
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002617 if (unlikely(ret == -1))
2618 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002619
Willy Tarreau47860ed2015-03-10 14:07:50 +01002620 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002621 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002622 return 1;
2623}
2624
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002625/* Check arguments for the fucntion "hlua_channel_get_yield". */
2626__LJMP static int hlua_channel_get(lua_State *L)
2627{
2628 MAY_LJMP(check_args(L, 1, "get"));
2629 MAY_LJMP(hlua_checkchannel(L, 1));
2630 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2631}
2632
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002633/* This functions consumes and returns one line. If the channel is closed,
2634 * and the last data does not contains a final '\n', the data are returned
2635 * without the final '\n'. When no more data are avalaible, it returns nil
2636 * value.
2637 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002638__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002639{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002640 char *blk1;
2641 char *blk2;
2642 int len1;
2643 int len2;
2644 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002645 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002646 int ret;
2647 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002648
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002649 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2650
Willy Tarreau47860ed2015-03-10 14:07:50 +01002651 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002652 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002653 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002654
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002655 if (ret == -1) {
2656 lua_pushnil(L);
2657 return 1;
2658 }
2659
2660 luaL_buffinit(L, &b);
2661 luaL_addlstring(&b, blk1, len1);
2662 len = len1;
2663 if (unlikely(ret == 2)) {
2664 luaL_addlstring(&b, blk2, len2);
2665 len += len2;
2666 }
2667 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002668 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002669 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002670 return 1;
2671}
2672
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002673/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2674__LJMP static int hlua_channel_getline(lua_State *L)
2675{
2676 MAY_LJMP(check_args(L, 1, "getline"));
2677 MAY_LJMP(hlua_checkchannel(L, 1));
2678 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2679}
2680
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002681/* This function takes a string as input, and append it at the
2682 * input side of channel. If the data is too big, but a space
2683 * is probably available after sending some data, the function
2684 * yield. If the data is bigger than the buffer, or if the
2685 * channel is closed, it returns -1. otherwise, it returns the
2686 * amount of data writed.
2687 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002688__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002689{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002690 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002691 size_t len;
2692 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2693 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2694 int ret;
2695 int max;
2696
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002697 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2698 * the request buffer if its not required.
2699 */
2700 if (chn->buf->size == 0) {
2701 si_applet_cant_put(chn_prod(chn));
2702 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
2703 }
2704
Willy Tarreau47860ed2015-03-10 14:07:50 +01002705 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002706 if (max > len - l)
2707 max = len - l;
2708
Willy Tarreau47860ed2015-03-10 14:07:50 +01002709 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002710 if (ret == -2 || ret == -3) {
2711 lua_pushinteger(L, -1);
2712 return 1;
2713 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002714 if (ret == -1) {
2715 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002716 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002717 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002718 l += ret;
2719 lua_pop(L, 1);
2720 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002721 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002722
Willy Tarreau47860ed2015-03-10 14:07:50 +01002723 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2724 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002725 /* There are no space avalaible, and the output buffer is empty.
2726 * in this case, we cannot add more data, so we cannot yield,
2727 * we return the amount of copyied data.
2728 */
2729 return 1;
2730 }
2731 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002732 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002733 return 1;
2734}
2735
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002736/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002737 * of the writed string, or -1 if the channel is closed or if the
2738 * buffer size is too little for the data.
2739 */
2740__LJMP static int hlua_channel_append(lua_State *L)
2741{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002742 size_t len;
2743
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002744 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002745 MAY_LJMP(hlua_checkchannel(L, 1));
2746 MAY_LJMP(luaL_checklstring(L, 2, &len));
2747 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002748 lua_pushinteger(L, 0);
2749
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002750 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002751}
2752
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002753/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002754 * his process by cleaning the buffer. The result is a replacement
2755 * of the current data. It returns the length of the writed string,
2756 * or -1 if the channel is closed or if the buffer size is too
2757 * little for the data.
2758 */
2759__LJMP static int hlua_channel_set(lua_State *L)
2760{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002761 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002762
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002763 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002764 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002765 lua_pushinteger(L, 0);
2766
Willy Tarreau47860ed2015-03-10 14:07:50 +01002767 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002768
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002769 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002770}
2771
2772/* Append data in the output side of the buffer. This data is immediatly
2773 * sent. The fcuntion returns the ammount of data writed. If the buffer
2774 * cannot contains the data, the function yield. The function returns -1
2775 * if the channel is closed.
2776 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002777__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002778{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002779 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002780 size_t len;
2781 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2782 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2783 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002784 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002785
Willy Tarreau47860ed2015-03-10 14:07:50 +01002786 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002787 lua_pushinteger(L, -1);
2788 return 1;
2789 }
2790
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002791 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2792 * the request buffer if its not required.
2793 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002794 if (chn->buf->size == 0) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002795 si_applet_cant_put(chn_prod(chn));
2796 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002797 }
2798
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002799 /* the writed data will be immediatly sent, so we can check
2800 * the avalaible space without taking in account the reserve.
2801 * The reserve is guaranted for the processing of incoming
2802 * data, because the buffer will be flushed.
2803 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002804 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002805
2806 /* If there are no space avalaible, and the output buffer is empty.
2807 * in this case, we cannot add more data, so we cannot yield,
2808 * we return the amount of copyied data.
2809 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002810 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002811 return 1;
2812
2813 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002814 if (max > len - l)
2815 max = len - l;
2816
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002817 /* The buffer avalaible size may be not contiguous. This test
2818 * detects a non contiguous buffer and realign it.
2819 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002820 if (bi_space_for_replace(chn->buf) < max)
2821 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002822
2823 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002824 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002825
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002826 /* buffer replace considers that the input part is filled.
2827 * so, I must forward these new data in the output part.
2828 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002829 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002830
2831 l += max;
2832 lua_pop(L, 1);
2833 lua_pushinteger(L, l);
2834
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002835 /* If there are no space avalaible, and the output buffer is empty.
2836 * in this case, we cannot add more data, so we cannot yield,
2837 * we return the amount of copyied data.
2838 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002839 max = chn->buf->size - buffer_len(chn->buf);
2840 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002841 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002842
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002843 if (l < len) {
2844 /* If we are waiting for space in the response buffer, we
2845 * must set the flag WAKERESWR. This flag required the task
2846 * wake up if any activity is detected on the response buffer.
2847 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002848 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002849 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002850 else
2851 HLUA_SET_WAKEREQWR(hlua);
2852 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002853 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002854
2855 return 1;
2856}
2857
2858/* Just a wraper of "_hlua_channel_send". This wrapper permits
2859 * yield the LUA process, and resume it without checking the
2860 * input arguments.
2861 */
2862__LJMP static int hlua_channel_send(lua_State *L)
2863{
2864 MAY_LJMP(check_args(L, 2, "send"));
2865 lua_pushinteger(L, 0);
2866
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002867 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002868}
2869
2870/* This function forward and amount of butes. The data pass from
2871 * the input side of the buffer to the output side, and can be
2872 * forwarded. This function never fails.
2873 *
2874 * The Lua function takes an amount of bytes to be forwarded in
2875 * imput. It returns the number of bytes forwarded.
2876 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002877__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002878{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002879 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002880 int len;
2881 int l;
2882 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002883 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002884
2885 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2886 len = MAY_LJMP(luaL_checkinteger(L, 2));
2887 l = MAY_LJMP(luaL_checkinteger(L, -1));
2888
2889 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002890 if (max > chn->buf->i)
2891 max = chn->buf->i;
2892 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002893 l += max;
2894
2895 lua_pop(L, 1);
2896 lua_pushinteger(L, l);
2897
2898 /* Check if it miss bytes to forward. */
2899 if (l < len) {
2900 /* The the input channel or the output channel are closed, we
2901 * must return the amount of data forwarded.
2902 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002903 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002904 return 1;
2905
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002906 /* If we are waiting for space data in the response buffer, we
2907 * must set the flag WAKERESWR. This flag required the task
2908 * wake up if any activity is detected on the response buffer.
2909 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002910 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002911 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002912 else
2913 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002914
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002915 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002916 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002917 }
2918
2919 return 1;
2920}
2921
2922/* Just check the input and prepare the stack for the previous
2923 * function "hlua_channel_forward_yield"
2924 */
2925__LJMP static int hlua_channel_forward(lua_State *L)
2926{
2927 MAY_LJMP(check_args(L, 2, "forward"));
2928 MAY_LJMP(hlua_checkchannel(L, 1));
2929 MAY_LJMP(luaL_checkinteger(L, 2));
2930
2931 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002932 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002933}
2934
2935/* Just returns the number of bytes available in the input
2936 * side of the buffer. This function never fails.
2937 */
2938__LJMP static int hlua_channel_get_in_len(lua_State *L)
2939{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002940 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002941
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002942 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002943 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002944 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002945 return 1;
2946}
2947
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01002948/* Returns true if the channel is full. */
2949__LJMP static int hlua_channel_is_full(lua_State *L)
2950{
2951 struct channel *chn;
2952 int rem;
2953
2954 MAY_LJMP(check_args(L, 1, "is_full"));
2955 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2956
2957 rem = chn->buf->size;
2958 rem -= chn->buf->o; /* Output size */
2959 rem -= chn->buf->i; /* Input size */
2960 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
2961
2962 lua_pushboolean(L, rem <= 0);
2963 return 1;
2964}
2965
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002966/* Just returns the number of bytes available in the output
2967 * side of the buffer. This function never fails.
2968 */
2969__LJMP static int hlua_channel_get_out_len(lua_State *L)
2970{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002971 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002972
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002973 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002974 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002975 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002976 return 1;
2977}
2978
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002979/*
2980 *
2981 *
2982 * Class Fetches
2983 *
2984 *
2985 */
2986
2987/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002988 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002989 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002990__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002991{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002992 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002993}
2994
2995/* This function creates and push in the stack a fetch object according
2996 * with a current TXN.
2997 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002998static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002999{
Willy Tarreau7073c472015-04-06 11:15:40 +02003000 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003001
3002 /* Check stack size. */
3003 if (!lua_checkstack(L, 3))
3004 return 0;
3005
3006 /* Create the object: obj[0] = userdata.
3007 * Note that the base of the Fetches object is the
3008 * transaction object.
3009 */
3010 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003011 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003012 lua_rawseti(L, -2, 0);
3013
Willy Tarreau7073c472015-04-06 11:15:40 +02003014 hsmp->s = txn->s;
3015 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003016 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003017 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003018
3019 /* Pop a class sesison metatable and affect it to the userdata. */
3020 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3021 lua_setmetatable(L, -2);
3022
3023 return 1;
3024}
3025
3026/* This function is an LUA binding. It is called with each sample-fetch.
3027 * It uses closure argument to store the associated sample-fetch. It
3028 * returns only one argument or throws an error. An error is thrown
3029 * only if an error is encountered during the argument parsing. If
3030 * the "sample-fetch" function fails, nil is returned.
3031 */
3032__LJMP static int hlua_run_sample_fetch(lua_State *L)
3033{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003034 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003035 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003036 struct arg args[ARGM_NBARGS + 1];
3037 int i;
3038 struct sample smp;
3039
3040 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003041 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003042
3043 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003044 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003045
Thierry FOURNIERca988662015-12-20 18:43:03 +01003046 /* Check execution authorization. */
3047 if (f->use & SMP_USE_HTTP_ANY &&
3048 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3049 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3050 "is not available in Lua services", f->kw);
3051 WILL_LJMP(lua_error(L));
3052 }
3053
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003054 /* Get extra arguments. */
3055 for (i = 0; i < lua_gettop(L) - 1; i++) {
3056 if (i >= ARGM_NBARGS)
3057 break;
3058 hlua_lua2arg(L, i + 2, &args[i]);
3059 }
3060 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003061 args[i].data.str.str = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003062
3063 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003064 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003065
3066 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003067 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003068 lua_pushfstring(L, "error in arguments");
3069 WILL_LJMP(lua_error(L));
3070 }
3071
3072 /* Initialise the sample. */
3073 memset(&smp, 0, sizeof(smp));
3074
3075 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003076 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003077 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003078 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003079 lua_pushstring(L, "");
3080 else
3081 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003082 return 1;
3083 }
3084
3085 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003086 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003087 hlua_smp2lua_str(L, &smp);
3088 else
3089 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003090 return 1;
3091}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003092
3093/*
3094 *
3095 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003096 * Class Converters
3097 *
3098 *
3099 */
3100
3101/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003102 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003103 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003104__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003105{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003106 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003107}
3108
3109/* This function creates and push in the stack a Converters object
3110 * according with a current TXN.
3111 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003112static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003113{
Willy Tarreau7073c472015-04-06 11:15:40 +02003114 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003115
3116 /* Check stack size. */
3117 if (!lua_checkstack(L, 3))
3118 return 0;
3119
3120 /* Create the object: obj[0] = userdata.
3121 * Note that the base of the Converters object is the
3122 * same than the TXN object.
3123 */
3124 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003125 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003126 lua_rawseti(L, -2, 0);
3127
Willy Tarreau7073c472015-04-06 11:15:40 +02003128 hsmp->s = txn->s;
3129 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003130 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003131 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003132
Willy Tarreau87b09662015-04-03 00:22:06 +02003133 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003134 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3135 lua_setmetatable(L, -2);
3136
3137 return 1;
3138}
3139
3140/* This function is an LUA binding. It is called with each converter.
3141 * It uses closure argument to store the associated converter. It
3142 * returns only one argument or throws an error. An error is thrown
3143 * only if an error is encountered during the argument parsing. If
3144 * the converter function function fails, nil is returned.
3145 */
3146__LJMP static int hlua_run_sample_conv(lua_State *L)
3147{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003148 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003149 struct sample_conv *conv;
3150 struct arg args[ARGM_NBARGS + 1];
3151 int i;
3152 struct sample smp;
3153
3154 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003155 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003156
3157 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003158 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003159
3160 /* Get extra arguments. */
3161 for (i = 0; i < lua_gettop(L) - 2; i++) {
3162 if (i >= ARGM_NBARGS)
3163 break;
3164 hlua_lua2arg(L, i + 3, &args[i]);
3165 }
3166 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003167 args[i].data.str.str = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003168
3169 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003170 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003171
3172 /* Run the special args checker. */
3173 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3174 hlua_pusherror(L, "error in arguments");
3175 WILL_LJMP(lua_error(L));
3176 }
3177
3178 /* Initialise the sample. */
3179 if (!hlua_lua2smp(L, 2, &smp)) {
3180 hlua_pusherror(L, "error in the input argument");
3181 WILL_LJMP(lua_error(L));
3182 }
3183
Willy Tarreau1777ea62016-03-10 16:15:46 +01003184 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3185
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003186 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003187 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003188 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003189 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003190 WILL_LJMP(lua_error(L));
3191 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003192 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3193 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003194 hlua_pusherror(L, "error during the input argument casting");
3195 WILL_LJMP(lua_error(L));
3196 }
3197
3198 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003199 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003200 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003201 lua_pushstring(L, "");
3202 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003203 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003204 return 1;
3205 }
3206
3207 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003208 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003209 hlua_smp2lua_str(L, &smp);
3210 else
3211 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003212 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003213}
3214
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003215/*
3216 *
3217 *
3218 * Class AppletTCP
3219 *
3220 *
3221 */
3222
3223/* Returns a struct hlua_txn if the stack entry "ud" is
3224 * a class stream, otherwise it throws an error.
3225 */
3226__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3227{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003228 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003229}
3230
3231/* This function creates and push in the stack an Applet object
3232 * according with a current TXN.
3233 */
3234static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3235{
3236 struct hlua_appctx *appctx;
3237 struct stream_interface *si = ctx->owner;
3238 struct stream *s = si_strm(si);
3239 struct proxy *p = s->be;
3240
3241 /* Check stack size. */
3242 if (!lua_checkstack(L, 3))
3243 return 0;
3244
3245 /* Create the object: obj[0] = userdata.
3246 * Note that the base of the Converters object is the
3247 * same than the TXN object.
3248 */
3249 lua_newtable(L);
3250 appctx = lua_newuserdata(L, sizeof(*appctx));
3251 lua_rawseti(L, -2, 0);
3252 appctx->appctx = ctx;
3253 appctx->htxn.s = s;
3254 appctx->htxn.p = p;
3255
3256 /* Create the "f" field that contains a list of fetches. */
3257 lua_pushstring(L, "f");
3258 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3259 return 0;
3260 lua_settable(L, -3);
3261
3262 /* Create the "sf" field that contains a list of stringsafe fetches. */
3263 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003264 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003265 return 0;
3266 lua_settable(L, -3);
3267
3268 /* Create the "c" field that contains a list of converters. */
3269 lua_pushstring(L, "c");
3270 if (!hlua_converters_new(L, &appctx->htxn, 0))
3271 return 0;
3272 lua_settable(L, -3);
3273
3274 /* Create the "sc" field that contains a list of stringsafe converters. */
3275 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003276 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003277 return 0;
3278 lua_settable(L, -3);
3279
3280 /* Pop a class stream metatable and affect it to the table. */
3281 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3282 lua_setmetatable(L, -2);
3283
3284 return 1;
3285}
3286
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003287__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3288{
3289 struct hlua_appctx *appctx;
3290 struct stream *s;
3291 const char *name;
3292 size_t len;
3293 struct sample smp;
3294
3295 MAY_LJMP(check_args(L, 3, "set_var"));
3296
3297 /* It is useles to retrieve the stream, but this function
3298 * runs only in a stream context.
3299 */
3300 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3301 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3302 s = appctx->htxn.s;
3303
3304 /* Converts the third argument in a sample. */
3305 hlua_lua2smp(L, 3, &smp);
3306
3307 /* Store the sample in a variable. */
3308 smp_set_owner(&smp, s->be, s->sess, s, 0);
3309 vars_set_by_name(name, len, &smp);
3310 return 0;
3311}
3312
3313__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3314{
3315 struct hlua_appctx *appctx;
3316 struct stream *s;
3317 const char *name;
3318 size_t len;
3319 struct sample smp;
3320
3321 MAY_LJMP(check_args(L, 2, "unset_var"));
3322
3323 /* It is useles to retrieve the stream, but this function
3324 * runs only in a stream context.
3325 */
3326 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3327 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3328 s = appctx->htxn.s;
3329
3330 /* Unset the variable. */
3331 smp_set_owner(&smp, s->be, s->sess, s, 0);
3332 vars_unset_by_name(name, len, &smp);
3333 return 0;
3334}
3335
3336__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3337{
3338 struct hlua_appctx *appctx;
3339 struct stream *s;
3340 const char *name;
3341 size_t len;
3342 struct sample smp;
3343
3344 MAY_LJMP(check_args(L, 2, "get_var"));
3345
3346 /* It is useles to retrieve the stream, but this function
3347 * runs only in a stream context.
3348 */
3349 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3350 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3351 s = appctx->htxn.s;
3352
3353 smp_set_owner(&smp, s->be, s->sess, s, 0);
3354 if (!vars_get_by_name(name, len, &smp)) {
3355 lua_pushnil(L);
3356 return 1;
3357 }
3358
3359 return hlua_smp2lua(L, &smp);
3360}
3361
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003362__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3363{
3364 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3365 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003366 struct hlua *hlua;
3367
3368 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003369 if (!s->hlua)
3370 return 0;
3371 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003372
3373 MAY_LJMP(check_args(L, 2, "set_priv"));
3374
3375 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003376 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003377
3378 /* Get and store new value. */
3379 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3380 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3381
3382 return 0;
3383}
3384
3385__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3386{
3387 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3388 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003389 struct hlua *hlua;
3390
3391 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003392 if (!s->hlua) {
3393 lua_pushnil(L);
3394 return 1;
3395 }
3396 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003397
3398 /* Push configuration index in the stack. */
3399 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3400
3401 return 1;
3402}
3403
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003404/* If expected data not yet available, it returns a yield. This function
3405 * consumes the data in the buffer. It returns a string containing the
3406 * data. This string can be empty.
3407 */
3408__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3409{
3410 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3411 struct stream_interface *si = appctx->appctx->owner;
3412 int ret;
3413 char *blk1;
3414 int len1;
3415 char *blk2;
3416 int len2;
3417
3418 /* Read the maximum amount of data avalaible. */
3419 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3420
3421 /* Data not yet avalaible. return yield. */
3422 if (ret == 0) {
3423 si_applet_cant_get(si);
3424 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3425 }
3426
3427 /* End of data: commit the total strings and return. */
3428 if (ret < 0) {
3429 luaL_pushresult(&appctx->b);
3430 return 1;
3431 }
3432
3433 /* Ensure that the block 2 length is usable. */
3434 if (ret == 1)
3435 len2 = 0;
3436
3437 /* dont check the max length read and dont check. */
3438 luaL_addlstring(&appctx->b, blk1, len1);
3439 luaL_addlstring(&appctx->b, blk2, len2);
3440
3441 /* Consume input channel output buffer data. */
3442 bo_skip(si_oc(si), len1 + len2);
3443 luaL_pushresult(&appctx->b);
3444 return 1;
3445}
3446
3447/* Check arguments for the fucntion "hlua_channel_get_yield". */
3448__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3449{
3450 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3451
3452 /* Initialise the string catenation. */
3453 luaL_buffinit(L, &appctx->b);
3454
3455 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3456}
3457
3458/* If expected data not yet available, it returns a yield. This function
3459 * consumes the data in the buffer. It returns a string containing the
3460 * data. This string can be empty.
3461 */
3462__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3463{
3464 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3465 struct stream_interface *si = appctx->appctx->owner;
3466 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3467 int ret;
3468 char *blk1;
3469 int len1;
3470 char *blk2;
3471 int len2;
3472
3473 /* Read the maximum amount of data avalaible. */
3474 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3475
3476 /* Data not yet avalaible. return yield. */
3477 if (ret == 0) {
3478 si_applet_cant_get(si);
3479 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3480 }
3481
3482 /* End of data: commit the total strings and return. */
3483 if (ret < 0) {
3484 luaL_pushresult(&appctx->b);
3485 return 1;
3486 }
3487
3488 /* Ensure that the block 2 length is usable. */
3489 if (ret == 1)
3490 len2 = 0;
3491
3492 if (len == -1) {
3493
3494 /* If len == -1, catenate all the data avalaile and
3495 * yield because we want to get all the data until
3496 * the end of data stream.
3497 */
3498 luaL_addlstring(&appctx->b, blk1, len1);
3499 luaL_addlstring(&appctx->b, blk2, len2);
3500 bo_skip(si_oc(si), len1 + len2);
3501 si_applet_cant_get(si);
3502 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3503
3504 } else {
3505
3506 /* Copy the fisrt block caping to the length required. */
3507 if (len1 > len)
3508 len1 = len;
3509 luaL_addlstring(&appctx->b, blk1, len1);
3510 len -= len1;
3511
3512 /* Copy the second block. */
3513 if (len2 > len)
3514 len2 = len;
3515 luaL_addlstring(&appctx->b, blk2, len2);
3516 len -= len2;
3517
3518 /* Consume input channel output buffer data. */
3519 bo_skip(si_oc(si), len1 + len2);
3520
3521 /* If we are no other data avalaible, yield waiting for new data. */
3522 if (len > 0) {
3523 lua_pushinteger(L, len);
3524 lua_replace(L, 2);
3525 si_applet_cant_get(si);
3526 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3527 }
3528
3529 /* return the result. */
3530 luaL_pushresult(&appctx->b);
3531 return 1;
3532 }
3533
3534 /* we never executes this */
3535 hlua_pusherror(L, "Lua: internal error");
3536 WILL_LJMP(lua_error(L));
3537 return 0;
3538}
3539
3540/* Check arguments for the fucntion "hlua_channel_get_yield". */
3541__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3542{
3543 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3544 int len = -1;
3545
3546 if (lua_gettop(L) > 2)
3547 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3548 if (lua_gettop(L) >= 2) {
3549 len = MAY_LJMP(luaL_checkinteger(L, 2));
3550 lua_pop(L, 1);
3551 }
3552
3553 /* Confirm or set the required length */
3554 lua_pushinteger(L, len);
3555
3556 /* Initialise the string catenation. */
3557 luaL_buffinit(L, &appctx->b);
3558
3559 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3560}
3561
3562/* Append data in the output side of the buffer. This data is immediatly
3563 * sent. The fcuntion returns the ammount of data writed. If the buffer
3564 * cannot contains the data, the function yield. The function returns -1
3565 * if the channel is closed.
3566 */
3567__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3568{
3569 size_t len;
3570 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3571 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3572 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3573 struct stream_interface *si = appctx->appctx->owner;
3574 struct channel *chn = si_ic(si);
3575 int max;
3576
3577 /* Get the max amount of data which can write as input in the channel. */
3578 max = channel_recv_max(chn);
3579 if (max > (len - l))
3580 max = len - l;
3581
3582 /* Copy data. */
3583 bi_putblk(chn, str + l, max);
3584
3585 /* update counters. */
3586 l += max;
3587 lua_pop(L, 1);
3588 lua_pushinteger(L, l);
3589
3590 /* If some data is not send, declares the situation to the
3591 * applet, and returns a yield.
3592 */
3593 if (l < len) {
3594 si_applet_cant_put(si);
3595 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3596 }
3597
3598 return 1;
3599}
3600
3601/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3602 * yield the LUA process, and resume it without checking the
3603 * input arguments.
3604 */
3605__LJMP static int hlua_applet_tcp_send(lua_State *L)
3606{
3607 MAY_LJMP(check_args(L, 2, "send"));
3608 lua_pushinteger(L, 0);
3609
3610 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3611}
3612
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003613/*
3614 *
3615 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003616 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003617 *
3618 *
3619 */
3620
3621/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003622 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003623 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003624__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003625{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003626 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003627}
3628
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003629/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003630 * according with a current TXN.
3631 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003632static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003633{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003634 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003635 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003636 struct stream_interface *si = ctx->owner;
3637 struct stream *s = si_strm(si);
3638 struct proxy *px = s->be;
3639 struct http_txn *txn = s->txn;
3640 const char *path;
3641 const char *end;
3642 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003643
3644 /* Check stack size. */
3645 if (!lua_checkstack(L, 3))
3646 return 0;
3647
3648 /* Create the object: obj[0] = userdata.
3649 * Note that the base of the Converters object is the
3650 * same than the TXN object.
3651 */
3652 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003653 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003654 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003655 appctx->appctx = ctx;
3656 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003657 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003658 appctx->htxn.s = s;
3659 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003660
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003661 /* Create the "f" field that contains a list of fetches. */
3662 lua_pushstring(L, "f");
3663 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3664 return 0;
3665 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003666
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003667 /* Create the "sf" field that contains a list of stringsafe fetches. */
3668 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003669 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003670 return 0;
3671 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003672
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003673 /* Create the "c" field that contains a list of converters. */
3674 lua_pushstring(L, "c");
3675 if (!hlua_converters_new(L, &appctx->htxn, 0))
3676 return 0;
3677 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003678
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003679 /* Create the "sc" field that contains a list of stringsafe converters. */
3680 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003681 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003682 return 0;
3683 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003684
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003685 /* Stores the request method. */
3686 lua_pushstring(L, "method");
3687 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3688 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003689
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003690 /* Stores the http version. */
3691 lua_pushstring(L, "version");
3692 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3693 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003694
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003695 /* creates an array of headers. hlua_http_get_headers() crates and push
3696 * the array on the top of the stack.
3697 */
3698 lua_pushstring(L, "headers");
3699 htxn.s = s;
3700 htxn.p = px;
3701 htxn.dir = SMP_OPT_DIR_REQ;
3702 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3703 return 0;
3704 lua_settable(L, -3);
3705
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003706 /* Get path and qs */
3707 path = http_get_path(txn);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003708 if (path) {
3709 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3710 p = path;
3711 while (p < end && *p != '?')
3712 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003713
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003714 /* Stores the request path. */
3715 lua_pushstring(L, "path");
3716 lua_pushlstring(L, path, p - path);
3717 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003718
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003719 /* Stores the query string. */
3720 lua_pushstring(L, "qs");
3721 if (*p == '?')
3722 p++;
3723 lua_pushlstring(L, p, end - p);
3724 lua_settable(L, -3);
3725 }
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003726
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003727 /* Stores the request path. */
3728 lua_pushstring(L, "length");
3729 lua_pushinteger(L, txn->req.body_len);
3730 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003731
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003732 /* Create an array of HTTP request headers. */
3733 lua_pushstring(L, "headers");
3734 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3735 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003736
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003737 /* Create an empty array of HTTP request headers. */
3738 lua_pushstring(L, "response");
3739 lua_newtable(L);
3740 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003741
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003742 /* Pop a class stream metatable and affect it to the table. */
3743 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3744 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003745
3746 return 1;
3747}
3748
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003749__LJMP static int hlua_applet_http_set_var(lua_State *L)
3750{
3751 struct hlua_appctx *appctx;
3752 struct stream *s;
3753 const char *name;
3754 size_t len;
3755 struct sample smp;
3756
3757 MAY_LJMP(check_args(L, 3, "set_var"));
3758
3759 /* It is useles to retrieve the stream, but this function
3760 * runs only in a stream context.
3761 */
3762 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3763 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3764 s = appctx->htxn.s;
3765
3766 /* Converts the third argument in a sample. */
3767 hlua_lua2smp(L, 3, &smp);
3768
3769 /* Store the sample in a variable. */
3770 smp_set_owner(&smp, s->be, s->sess, s, 0);
3771 vars_set_by_name(name, len, &smp);
3772 return 0;
3773}
3774
3775__LJMP static int hlua_applet_http_unset_var(lua_State *L)
3776{
3777 struct hlua_appctx *appctx;
3778 struct stream *s;
3779 const char *name;
3780 size_t len;
3781 struct sample smp;
3782
3783 MAY_LJMP(check_args(L, 2, "unset_var"));
3784
3785 /* It is useles to retrieve the stream, but this function
3786 * runs only in a stream context.
3787 */
3788 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3789 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3790 s = appctx->htxn.s;
3791
3792 /* Unset the variable. */
3793 smp_set_owner(&smp, s->be, s->sess, s, 0);
3794 vars_unset_by_name(name, len, &smp);
3795 return 0;
3796}
3797
3798__LJMP static int hlua_applet_http_get_var(lua_State *L)
3799{
3800 struct hlua_appctx *appctx;
3801 struct stream *s;
3802 const char *name;
3803 size_t len;
3804 struct sample smp;
3805
3806 MAY_LJMP(check_args(L, 2, "get_var"));
3807
3808 /* It is useles to retrieve the stream, but this function
3809 * runs only in a stream context.
3810 */
3811 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3812 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3813 s = appctx->htxn.s;
3814
3815 smp_set_owner(&smp, s->be, s->sess, s, 0);
3816 if (!vars_get_by_name(name, len, &smp)) {
3817 lua_pushnil(L);
3818 return 1;
3819 }
3820
3821 return hlua_smp2lua(L, &smp);
3822}
3823
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003824__LJMP static int hlua_applet_http_set_priv(lua_State *L)
3825{
3826 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3827 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003828 struct hlua *hlua;
3829
3830 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003831 if (!s->hlua)
3832 return 0;
3833 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003834
3835 MAY_LJMP(check_args(L, 2, "set_priv"));
3836
3837 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003838 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003839
3840 /* Get and store new value. */
3841 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3842 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3843
3844 return 0;
3845}
3846
3847__LJMP static int hlua_applet_http_get_priv(lua_State *L)
3848{
3849 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3850 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003851 struct hlua *hlua;
3852
3853 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003854 if (!s->hlua) {
3855 lua_pushnil(L);
3856 return 1;
3857 }
3858 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003859
3860 /* Push configuration index in the stack. */
3861 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3862
3863 return 1;
3864}
3865
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003866/* If expected data not yet available, it returns a yield. This function
3867 * consumes the data in the buffer. It returns a string containing the
3868 * data. This string can be empty.
3869 */
3870__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003871{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003872 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3873 struct stream_interface *si = appctx->appctx->owner;
3874 struct channel *chn = si_ic(si);
3875 int ret;
3876 char *blk1;
3877 int len1;
3878 char *blk2;
3879 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003880
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003881 /* Maybe we cant send a 100-continue ? */
3882 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3883 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3884 /* if ret == -2 or -3 the channel closed or the message si too
3885 * big for the buffers. We cant send anything. So, we ignoring
3886 * the error, considers that the 100-continue is sent, and try
3887 * to receive.
3888 * If ret is -1, we dont have room in the buffer, so we yield.
3889 */
3890 if (ret == -1) {
3891 si_applet_cant_put(si);
3892 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3893 }
3894 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3895 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003896
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003897 /* Check for the end of the data. */
3898 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
3899 luaL_pushresult(&appctx->b);
3900 return 1;
3901 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003902
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003903 /* Read the maximum amount of data avalaible. */
3904 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003905
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003906 /* Data not yet avalaible. return yield. */
3907 if (ret == 0) {
3908 si_applet_cant_get(si);
3909 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3910 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003911
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003912 /* End of data: commit the total strings and return. */
3913 if (ret < 0) {
3914 luaL_pushresult(&appctx->b);
3915 return 1;
3916 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003917
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003918 /* Ensure that the block 2 length is usable. */
3919 if (ret == 1)
3920 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003921
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003922 /* Copy the fisrt block caping to the length required. */
3923 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3924 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3925 luaL_addlstring(&appctx->b, blk1, len1);
3926 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003927
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003928 /* Copy the second block. */
3929 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3930 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3931 luaL_addlstring(&appctx->b, blk2, len2);
3932 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003933
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003934 /* Consume input channel output buffer data. */
3935 bo_skip(si_oc(si), len1 + len2);
3936 luaL_pushresult(&appctx->b);
3937 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003938}
3939
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003940/* Check arguments for the fucntion "hlua_channel_get_yield". */
3941__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003942{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003943 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003944
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003945 /* Initialise the string catenation. */
3946 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003947
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003948 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003949}
3950
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003951/* If expected data not yet available, it returns a yield. This function
3952 * consumes the data in the buffer. It returns a string containing the
3953 * data. This string can be empty.
3954 */
3955__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003956{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003957 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3958 struct stream_interface *si = appctx->appctx->owner;
3959 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3960 struct channel *chn = si_ic(si);
3961 int ret;
3962 char *blk1;
3963 int len1;
3964 char *blk2;
3965 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003966
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003967 /* Maybe we cant send a 100-continue ? */
3968 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3969 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3970 /* if ret == -2 or -3 the channel closed or the message si too
3971 * big for the buffers. We cant send anything. So, we ignoring
3972 * the error, considers that the 100-continue is sent, and try
3973 * to receive.
3974 * If ret is -1, we dont have room in the buffer, so we yield.
3975 */
3976 if (ret == -1) {
3977 si_applet_cant_put(si);
3978 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3979 }
3980 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3981 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003982
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003983 /* Read the maximum amount of data avalaible. */
3984 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003985
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003986 /* Data not yet avalaible. return yield. */
3987 if (ret == 0) {
3988 si_applet_cant_get(si);
3989 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3990 }
3991
3992 /* End of data: commit the total strings and return. */
3993 if (ret < 0) {
3994 luaL_pushresult(&appctx->b);
3995 return 1;
3996 }
3997
3998 /* Ensure that the block 2 length is usable. */
3999 if (ret == 1)
4000 len2 = 0;
4001
4002 /* Copy the fisrt block caping to the length required. */
4003 if (len1 > len)
4004 len1 = len;
4005 luaL_addlstring(&appctx->b, blk1, len1);
4006 len -= len1;
4007
4008 /* Copy the second block. */
4009 if (len2 > len)
4010 len2 = len;
4011 luaL_addlstring(&appctx->b, blk2, len2);
4012 len -= len2;
4013
4014 /* Consume input channel output buffer data. */
4015 bo_skip(si_oc(si), len1 + len2);
4016 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
4017 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
4018
4019 /* If we are no other data avalaible, yield waiting for new data. */
4020 if (len > 0) {
4021 lua_pushinteger(L, len);
4022 lua_replace(L, 2);
4023 si_applet_cant_get(si);
4024 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4025 }
4026
4027 /* return the result. */
4028 luaL_pushresult(&appctx->b);
4029 return 1;
4030}
4031
4032/* Check arguments for the fucntion "hlua_channel_get_yield". */
4033__LJMP static int hlua_applet_http_recv(lua_State *L)
4034{
4035 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4036 int len = -1;
4037
4038 /* Check arguments. */
4039 if (lua_gettop(L) > 2)
4040 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4041 if (lua_gettop(L) >= 2) {
4042 len = MAY_LJMP(luaL_checkinteger(L, 2));
4043 lua_pop(L, 1);
4044 }
4045
4046 /* Check the required length */
4047 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4048 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4049 lua_pushinteger(L, len);
4050
4051 /* Initialise the string catenation. */
4052 luaL_buffinit(L, &appctx->b);
4053
4054 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4055}
4056
4057/* Append data in the output side of the buffer. This data is immediatly
4058 * sent. The fcuntion returns the ammount of data writed. If the buffer
4059 * cannot contains the data, the function yield. The function returns -1
4060 * if the channel is closed.
4061 */
4062__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4063{
4064 size_t len;
4065 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4066 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4067 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4068 struct stream_interface *si = appctx->appctx->owner;
4069 struct channel *chn = si_ic(si);
4070 int max;
4071
4072 /* Get the max amount of data which can write as input in the channel. */
4073 max = channel_recv_max(chn);
4074 if (max > (len - l))
4075 max = len - l;
4076
4077 /* Copy data. */
4078 bi_putblk(chn, str + l, max);
4079
4080 /* update counters. */
4081 l += max;
4082 lua_pop(L, 1);
4083 lua_pushinteger(L, l);
4084
4085 /* If some data is not send, declares the situation to the
4086 * applet, and returns a yield.
4087 */
4088 if (l < len) {
4089 si_applet_cant_put(si);
4090 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
4091 }
4092
4093 return 1;
4094}
4095
4096/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4097 * yield the LUA process, and resume it without checking the
4098 * input arguments.
4099 */
4100__LJMP static int hlua_applet_http_send(lua_State *L)
4101{
4102 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4103 size_t len;
4104 char hex[10];
4105
4106 MAY_LJMP(luaL_checklstring(L, 2, &len));
4107
4108 /* If transfer encoding chunked is selected, we surround the data
4109 * by chunk data.
4110 */
4111 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4112 snprintf(hex, 9, "%x", (unsigned int)len);
4113 lua_pushfstring(L, "%s\r\n", hex);
4114 lua_insert(L, 2); /* swap the last 2 entries. */
4115 lua_pushstring(L, "\r\n");
4116 lua_concat(L, 3);
4117 }
4118
4119 /* This interger is used for followinf the amount of data sent. */
4120 lua_pushinteger(L, 0);
4121
4122 /* We want to send some data. Headers must be sent. */
4123 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4124 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4125 WILL_LJMP(lua_error(L));
4126 }
4127
4128 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4129}
4130
4131__LJMP static int hlua_applet_http_addheader(lua_State *L)
4132{
4133 const char *name;
4134 int ret;
4135
4136 MAY_LJMP(hlua_checkapplet_http(L, 1));
4137 name = MAY_LJMP(luaL_checkstring(L, 2));
4138 MAY_LJMP(luaL_checkstring(L, 3));
4139
4140 /* Push in the stack the "response" entry. */
4141 ret = lua_getfield(L, 1, "response");
4142 if (ret != LUA_TTABLE) {
4143 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4144 "is expected as an array. %s found", lua_typename(L, ret));
4145 WILL_LJMP(lua_error(L));
4146 }
4147
4148 /* check if the header is already registered if it is not
4149 * the case, register it.
4150 */
4151 ret = lua_getfield(L, -1, name);
4152 if (ret == LUA_TNIL) {
4153
4154 /* Entry not found. */
4155 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4156
4157 /* Insert the new header name in the array in the top of the stack.
4158 * It left the new array in the top of the stack.
4159 */
4160 lua_newtable(L);
4161 lua_pushvalue(L, 2);
4162 lua_pushvalue(L, -2);
4163 lua_settable(L, -4);
4164
4165 } else if (ret != LUA_TTABLE) {
4166
4167 /* corruption error. */
4168 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4169 "is expected as an array. %s found", name, lua_typename(L, ret));
4170 WILL_LJMP(lua_error(L));
4171 }
4172
4173 /* Now the top od thestack is an array of values. We push
4174 * the header value as new entry.
4175 */
4176 lua_pushvalue(L, 3);
4177 ret = lua_rawlen(L, -2);
4178 lua_rawseti(L, -2, ret + 1);
4179 lua_pushboolean(L, 1);
4180 return 1;
4181}
4182
4183__LJMP static int hlua_applet_http_status(lua_State *L)
4184{
4185 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4186 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004187 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004188
4189 if (status < 100 || status > 599) {
4190 lua_pushboolean(L, 0);
4191 return 1;
4192 }
4193
4194 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004195 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004196 lua_pushboolean(L, 1);
4197 return 1;
4198}
4199
4200/* We will build the status line and the headers of the HTTP response.
4201 * We will try send at once if its not possible, we give back the hand
4202 * waiting for more room.
4203 */
4204__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4205{
4206 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4207 struct stream_interface *si = appctx->appctx->owner;
4208 struct channel *chn = si_ic(si);
4209 int ret;
4210 size_t len;
4211 const char *msg;
4212
4213 /* Get the message as the first argument on the stack. */
4214 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4215
4216 /* Send the message at once. */
4217 ret = bi_putblk(chn, msg, len);
4218
4219 /* if ret == -2 or -3 the channel closed or the message si too
4220 * big for the buffers.
4221 */
4222 if (ret == -2 || ret == -3) {
4223 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4224 WILL_LJMP(lua_error(L));
4225 }
4226
4227 /* If ret is -1, we dont have room in the buffer, so we yield. */
4228 if (ret == -1) {
4229 si_applet_cant_put(si);
4230 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
4231 }
4232
4233 /* Headers sent, set the flag. */
4234 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4235 return 0;
4236}
4237
4238__LJMP static int hlua_applet_http_start_response(lua_State *L)
4239{
4240 struct chunk *tmp = get_trash_chunk();
4241 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004242 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02004243 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004244 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02004245 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004246 int id;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004247 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004248 int hdr_chunked = 0;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004249 const char *reason = appctx->appctx->ctx.hlua_apphttp.reason;
4250
4251 if (reason == NULL)
4252 reason = get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004253
4254 /* Use the same http version than the request. */
4255 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004256 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004257 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004258 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004259
4260 /* Get the array associated to the field "response" in the object AppletHTTP. */
4261 lua_pushvalue(L, 0);
4262 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4263 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4264 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4265 WILL_LJMP(lua_error(L));
4266 }
4267
4268 /* Browse the list of headers. */
4269 lua_pushnil(L);
4270 while(lua_next(L, -2) != 0) {
4271
4272 /* We expect a string as -2. */
4273 if (lua_type(L, -2) != LUA_TSTRING) {
4274 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4275 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4276 lua_typename(L, lua_type(L, -2)));
4277 WILL_LJMP(lua_error(L));
4278 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004279 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004280
4281 /* We expect an array as -1. */
4282 if (lua_type(L, -1) != LUA_TTABLE) {
4283 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4284 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4285 name,
4286 lua_typename(L, lua_type(L, -1)));
4287 WILL_LJMP(lua_error(L));
4288 }
4289
4290 /* Browse the table who is on the top of the stack. */
4291 lua_pushnil(L);
4292 while(lua_next(L, -2) != 0) {
4293
4294 /* We expect a number as -2. */
4295 if (lua_type(L, -2) != LUA_TNUMBER) {
4296 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4297 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4298 name,
4299 lua_typename(L, lua_type(L, -2)));
4300 WILL_LJMP(lua_error(L));
4301 }
4302 id = lua_tointeger(L, -2);
4303
4304 /* We expect a string as -2. */
4305 if (lua_type(L, -1) != LUA_TSTRING) {
4306 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4307 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4308 name, id,
4309 lua_typename(L, lua_type(L, -1)));
4310 WILL_LJMP(lua_error(L));
4311 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004312 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004313
4314 /* Catenate a new header. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004315 if (tmp->len + name_len + 2 + value_len + 2 < tmp->size) {
4316 memcpy(tmp->str + tmp->len, name, name_len);
4317 tmp->len += name_len;
4318 tmp->str[tmp->len++] = ':';
4319 tmp->str[tmp->len++] = ' ';
4320
4321 memcpy(tmp->str + tmp->len, value, value_len);
4322 tmp->len += value_len;
4323 tmp->str[tmp->len++] = '\r';
4324 tmp->str[tmp->len++] = '\n';
4325 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004326
4327 /* Protocol checks. */
4328
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004329 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004330 * is done without control. If it contains a bad value,
4331 * the content-length remains negative so that we can
4332 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004333 */
Willy Tarreaua3294632017-08-23 11:24:47 +02004334 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004335 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004336
4337 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004338 if (name_len == 17 && value_len == 7 &&
4339 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004340 strcasecmp("chunked", value) == 0)
4341 hdr_chunked = 1;
4342
4343 /* Remove the array from the stack, and get next element with a remaining string. */
4344 lua_pop(L, 1);
4345 }
4346
4347 /* Remove the array from the stack, and get next element with a remaining string. */
4348 lua_pop(L, 1);
4349 }
4350
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004351 /* If we dont have a content-length set, and the HTTP version is 1.1
4352 * and the status code implies the presence of a message body, we must
4353 * announce a transfer encoding chunked. This is required by haproxy
4354 * for the keepalive compliance. If the applet annouces a transfer-encoding
4355 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004356 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004357 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004358 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
4359 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4360 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4361 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004362 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4363 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4364 }
4365
4366 /* Finalize headers. */
4367 chunk_appendf(tmp, "\r\n");
4368
4369 /* Remove the last entry and the array of headers */
4370 lua_pop(L, 2);
4371
4372 /* Push the headers block. */
4373 lua_pushlstring(L, tmp->str, tmp->len);
4374
4375 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4376}
4377
4378/*
4379 *
4380 *
4381 * Class HTTP
4382 *
4383 *
4384 */
4385
4386/* Returns a struct hlua_txn if the stack entry "ud" is
4387 * a class stream, otherwise it throws an error.
4388 */
4389__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4390{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004391 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004392}
4393
4394/* This function creates and push in the stack a HTTP object
4395 * according with a current TXN.
4396 */
4397static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4398{
4399 struct hlua_txn *htxn;
4400
4401 /* Check stack size. */
4402 if (!lua_checkstack(L, 3))
4403 return 0;
4404
4405 /* Create the object: obj[0] = userdata.
4406 * Note that the base of the Converters object is the
4407 * same than the TXN object.
4408 */
4409 lua_newtable(L);
4410 htxn = lua_newuserdata(L, sizeof(*htxn));
4411 lua_rawseti(L, -2, 0);
4412
4413 htxn->s = txn->s;
4414 htxn->p = txn->p;
4415
4416 /* Pop a class stream metatable and affect it to the table. */
4417 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4418 lua_setmetatable(L, -2);
4419
4420 return 1;
4421}
4422
4423/* This function creates ans returns an array of HTTP headers.
4424 * This function does not fails. It is used as wrapper with the
4425 * 2 following functions.
4426 */
4427__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4428{
4429 const char *cur_ptr, *cur_next, *p;
4430 int old_idx, cur_idx;
4431 struct hdr_idx_elem *cur_hdr;
4432 const char *hn, *hv;
4433 int hnl, hvl;
4434 int type;
4435 const char *in;
4436 char *out;
4437 int len;
4438
4439 /* Create the table. */
4440 lua_newtable(L);
4441
4442 if (!htxn->s->txn)
4443 return 1;
4444
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004445 /* Check if a valid response is parsed */
4446 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4447 return 1;
4448
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004449 /* Build array of headers. */
4450 old_idx = 0;
4451 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4452
4453 while (1) {
4454 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4455 if (!cur_idx)
4456 break;
4457 old_idx = cur_idx;
4458
4459 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4460 cur_ptr = cur_next;
4461 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4462
4463 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4464 * and the next header starts at cur_next. We'll check
4465 * this header in the list as well as against the default
4466 * rule.
4467 */
4468
4469 /* look for ': *'. */
4470 hn = cur_ptr;
4471 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4472 if (p >= cur_ptr+cur_hdr->len)
4473 continue;
4474 hnl = p - hn;
4475 p++;
4476 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4477 p++;
4478 if (p >= cur_ptr+cur_hdr->len)
4479 continue;
4480 hv = p;
4481 hvl = cur_ptr+cur_hdr->len-p;
4482
4483 /* Lowercase the key. Don't check the size of trash, it have
4484 * the size of one buffer and the input data contains in one
4485 * buffer.
4486 */
4487 out = trash.str;
4488 for (in=hn; in<hn+hnl; in++, out++)
4489 *out = tolower(*in);
4490 *out = '\0';
4491
4492 /* Check for existing entry:
4493 * assume that the table is on the top of the stack, and
4494 * push the key in the stack, the function lua_gettable()
4495 * perform the lookup.
4496 */
4497 lua_pushlstring(L, trash.str, hnl);
4498 lua_gettable(L, -2);
4499 type = lua_type(L, -1);
4500
4501 switch (type) {
4502 case LUA_TNIL:
4503 /* Table not found, create it. */
4504 lua_pop(L, 1); /* remove the nil value. */
4505 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4506 lua_newtable(L); /* create and push empty table. */
4507 lua_pushlstring(L, hv, hvl); /* push header value. */
4508 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4509 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4510 break;
4511
4512 case LUA_TTABLE:
4513 /* Entry found: push the value in the table. */
4514 len = lua_rawlen(L, -1);
4515 lua_pushlstring(L, hv, hvl); /* push header value. */
4516 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4517 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4518 break;
4519
4520 default:
4521 /* Other cases are errors. */
4522 hlua_pusherror(L, "internal error during the parsing of headers.");
4523 WILL_LJMP(lua_error(L));
4524 }
4525 }
4526
4527 return 1;
4528}
4529
4530__LJMP static int hlua_http_req_get_headers(lua_State *L)
4531{
4532 struct hlua_txn *htxn;
4533
4534 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4535 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4536
4537 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4538}
4539
4540__LJMP static int hlua_http_res_get_headers(lua_State *L)
4541{
4542 struct hlua_txn *htxn;
4543
4544 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4545 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4546
4547 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4548}
4549
4550/* This function replace full header, or just a value in
4551 * the request or in the response. It is a wrapper fir the
4552 * 4 following functions.
4553 */
4554__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4555 struct http_msg *msg, int action)
4556{
4557 size_t name_len;
4558 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4559 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4560 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4561 struct my_regex re;
4562
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004563 /* Check if a valid response is parsed */
4564 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4565 return 0;
4566
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004567 if (!regex_comp(reg, &re, 1, 1, NULL))
4568 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4569
4570 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4571 regex_free(&re);
4572 return 0;
4573}
4574
4575__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4576{
4577 struct hlua_txn *htxn;
4578
4579 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4580 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4581
4582 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4583}
4584
4585__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4586{
4587 struct hlua_txn *htxn;
4588
4589 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4590 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4591
4592 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4593}
4594
4595__LJMP static int hlua_http_req_rep_val(lua_State *L)
4596{
4597 struct hlua_txn *htxn;
4598
4599 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4600 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4601
4602 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4603}
4604
4605__LJMP static int hlua_http_res_rep_val(lua_State *L)
4606{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004607 struct hlua_txn *htxn;
4608
4609 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4610 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4611
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004612 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004613}
4614
4615/* This function deletes all the occurences of an header.
4616 * It is a wrapper for the 2 following functions.
4617 */
4618__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4619{
4620 size_t len;
4621 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4622 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004623 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004624
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004625 /* Check if a valid response is parsed */
4626 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4627 return 0;
4628
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004629 ctx.idx = 0;
4630 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4631 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4632 return 0;
4633}
4634
4635__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4636{
4637 struct hlua_txn *htxn;
4638
4639 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4640 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4641
Willy Tarreaueee5b512015-04-03 23:46:31 +02004642 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004643}
4644
4645__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4646{
4647 struct hlua_txn *htxn;
4648
4649 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4650 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4651
Willy Tarreaueee5b512015-04-03 23:46:31 +02004652 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004653}
4654
4655/* This function adds an header. It is a wrapper used by
4656 * the 2 following functions.
4657 */
4658__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4659{
4660 size_t name_len;
4661 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4662 size_t value_len;
4663 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4664 char *p;
4665
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004666 /* Check if a valid message is parsed */
4667 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4668 return 0;
4669
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004670 /* Check length. */
4671 trash.len = value_len + name_len + 2;
4672 if (trash.len > trash.size)
4673 return 0;
4674
4675 /* Creates the header string. */
4676 p = trash.str;
4677 memcpy(p, name, name_len);
4678 p += name_len;
4679 *p = ':';
4680 p++;
4681 *p = ' ';
4682 p++;
4683 memcpy(p, value, value_len);
4684
Willy Tarreaueee5b512015-04-03 23:46:31 +02004685 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004686 trash.str, trash.len) != 0);
4687
4688 return 0;
4689}
4690
4691__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4692{
4693 struct hlua_txn *htxn;
4694
4695 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4696 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4697
Willy Tarreaueee5b512015-04-03 23:46:31 +02004698 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004699}
4700
4701__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4702{
4703 struct hlua_txn *htxn;
4704
4705 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4706 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4707
Willy Tarreaueee5b512015-04-03 23:46:31 +02004708 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004709}
4710
4711static int hlua_http_req_set_hdr(lua_State *L)
4712{
4713 struct hlua_txn *htxn;
4714
4715 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4716 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4717
Willy Tarreaueee5b512015-04-03 23:46:31 +02004718 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4719 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004720}
4721
4722static int hlua_http_res_set_hdr(lua_State *L)
4723{
4724 struct hlua_txn *htxn;
4725
4726 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4727 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4728
Willy Tarreaueee5b512015-04-03 23:46:31 +02004729 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4730 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004731}
4732
4733/* This function set the method. */
4734static int hlua_http_req_set_meth(lua_State *L)
4735{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004736 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004737 size_t name_len;
4738 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004739
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004740 /* Check if a valid request is parsed */
4741 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4742 lua_pushboolean(L, 0);
4743 return 1;
4744 }
4745
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004746 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004747 return 1;
4748}
4749
4750/* This function set the method. */
4751static int hlua_http_req_set_path(lua_State *L)
4752{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004753 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004754 size_t name_len;
4755 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004756
4757 /* Check if a valid request is parsed */
4758 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4759 lua_pushboolean(L, 0);
4760 return 1;
4761 }
4762
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004763 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004764 return 1;
4765}
4766
4767/* This function set the query-string. */
4768static int hlua_http_req_set_query(lua_State *L)
4769{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004770 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004771 size_t name_len;
4772 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004773
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004774 /* Check if a valid request is parsed */
4775 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4776 lua_pushboolean(L, 0);
4777 return 1;
4778 }
4779
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004780 /* Check length. */
4781 if (name_len > trash.size - 1) {
4782 lua_pushboolean(L, 0);
4783 return 1;
4784 }
4785
4786 /* Add the mark question as prefix. */
4787 chunk_reset(&trash);
4788 trash.str[trash.len++] = '?';
4789 memcpy(trash.str + trash.len, name, name_len);
4790 trash.len += name_len;
4791
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004792 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004793 return 1;
4794}
4795
4796/* This function set the uri. */
4797static int hlua_http_req_set_uri(lua_State *L)
4798{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004799 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004800 size_t name_len;
4801 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004802
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004803 /* Check if a valid request is parsed */
4804 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4805 lua_pushboolean(L, 0);
4806 return 1;
4807 }
4808
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004809 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004810 return 1;
4811}
4812
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004813/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004814static int hlua_http_res_set_status(lua_State *L)
4815{
4816 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4817 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004818 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004819
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004820 /* Check if a valid response is parsed */
4821 if (unlikely(htxn->s->txn->rsp.msg_state < HTTP_MSG_BODY))
4822 return 0;
4823
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004824 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004825 return 0;
4826}
4827
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004828/*
4829 *
4830 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004831 * Class TXN
4832 *
4833 *
4834 */
4835
4836/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004837 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004838 */
4839__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
4840{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004841 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004842}
4843
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004844__LJMP static int hlua_set_var(lua_State *L)
4845{
4846 struct hlua_txn *htxn;
4847 const char *name;
4848 size_t len;
4849 struct sample smp;
4850
4851 MAY_LJMP(check_args(L, 3, "set_var"));
4852
4853 /* It is useles to retrieve the stream, but this function
4854 * runs only in a stream context.
4855 */
4856 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4857 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4858
4859 /* Converts the third argument in a sample. */
4860 hlua_lua2smp(L, 3, &smp);
4861
4862 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01004863 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004864 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004865 return 0;
4866}
4867
Christopher Faulet85d79c92016-11-09 16:54:56 +01004868__LJMP static int hlua_unset_var(lua_State *L)
4869{
4870 struct hlua_txn *htxn;
4871 const char *name;
4872 size_t len;
4873 struct sample smp;
4874
4875 MAY_LJMP(check_args(L, 2, "unset_var"));
4876
4877 /* It is useles to retrieve the stream, but this function
4878 * runs only in a stream context.
4879 */
4880 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4881 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4882
4883 /* Unset the variable. */
4884 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
4885 vars_unset_by_name(name, len, &smp);
4886 return 0;
4887}
4888
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004889__LJMP static int hlua_get_var(lua_State *L)
4890{
4891 struct hlua_txn *htxn;
4892 const char *name;
4893 size_t len;
4894 struct sample smp;
4895
4896 MAY_LJMP(check_args(L, 2, "get_var"));
4897
4898 /* It is useles to retrieve the stream, but this function
4899 * runs only in a stream context.
4900 */
4901 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4902 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4903
Willy Tarreau7560dd42016-03-10 16:28:58 +01004904 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004905 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004906 lua_pushnil(L);
4907 return 1;
4908 }
4909
4910 return hlua_smp2lua(L, &smp);
4911}
4912
Willy Tarreau59551662015-03-10 14:23:13 +01004913__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004914{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004915 struct hlua *hlua;
4916
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004917 MAY_LJMP(check_args(L, 2, "set_priv"));
4918
Willy Tarreau87b09662015-04-03 00:22:06 +02004919 /* It is useles to retrieve the stream, but this function
4920 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004921 */
4922 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004923 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004924
4925 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004926 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004927
4928 /* Get and store new value. */
4929 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4930 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4931
4932 return 0;
4933}
4934
Willy Tarreau59551662015-03-10 14:23:13 +01004935__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004936{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004937 struct hlua *hlua;
4938
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004939 MAY_LJMP(check_args(L, 1, "get_priv"));
4940
Willy Tarreau87b09662015-04-03 00:22:06 +02004941 /* It is useles to retrieve the stream, but this function
4942 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004943 */
4944 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004945 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004946
4947 /* Push configuration index in the stack. */
4948 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4949
4950 return 1;
4951}
4952
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004953/* Create stack entry containing a class TXN. This function
4954 * return 0 if the stack does not contains free slots,
4955 * otherwise it returns 1.
4956 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004957static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004958{
Willy Tarreaude491382015-04-06 11:04:28 +02004959 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004960
4961 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004962 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004963 return 0;
4964
4965 /* NOTE: The allocation never fails. The failure
4966 * throw an error, and the function never returns.
4967 * if the throw is not avalaible, the process is aborted.
4968 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004969 /* Create the object: obj[0] = userdata. */
4970 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02004971 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004972 lua_rawseti(L, -2, 0);
4973
Willy Tarreaude491382015-04-06 11:04:28 +02004974 htxn->s = s;
4975 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004976 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004977 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004978
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004979 /* Create the "f" field that contains a list of fetches. */
4980 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004981 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004982 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004983 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004984
4985 /* Create the "sf" field that contains a list of stringsafe fetches. */
4986 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004987 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004988 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004989 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004990
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004991 /* Create the "c" field that contains a list of converters. */
4992 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02004993 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004994 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004995 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004996
4997 /* Create the "sc" field that contains a list of stringsafe converters. */
4998 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004999 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005000 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005001 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005002
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005003 /* Create the "req" field that contains the request channel object. */
5004 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005005 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005006 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005007 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005008
5009 /* Create the "res" field that contains the response channel object. */
5010 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005011 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005012 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005013 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005014
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005015 /* Creates the HTTP object is the current proxy allows http. */
5016 lua_pushstring(L, "http");
5017 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005018 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005019 return 0;
5020 }
5021 else
5022 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005023 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005024
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005025 /* Pop a class sesison metatable and affect it to the userdata. */
5026 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5027 lua_setmetatable(L, -2);
5028
5029 return 1;
5030}
5031
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005032__LJMP static int hlua_txn_deflog(lua_State *L)
5033{
5034 const char *msg;
5035 struct hlua_txn *htxn;
5036
5037 MAY_LJMP(check_args(L, 2, "deflog"));
5038 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5039 msg = MAY_LJMP(luaL_checkstring(L, 2));
5040
5041 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5042 return 0;
5043}
5044
5045__LJMP static int hlua_txn_log(lua_State *L)
5046{
5047 int level;
5048 const char *msg;
5049 struct hlua_txn *htxn;
5050
5051 MAY_LJMP(check_args(L, 3, "log"));
5052 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5053 level = MAY_LJMP(luaL_checkinteger(L, 2));
5054 msg = MAY_LJMP(luaL_checkstring(L, 3));
5055
5056 if (level < 0 || level >= NB_LOG_LEVELS)
5057 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5058
5059 hlua_sendlog(htxn->s->be, level, msg);
5060 return 0;
5061}
5062
5063__LJMP static int hlua_txn_log_debug(lua_State *L)
5064{
5065 const char *msg;
5066 struct hlua_txn *htxn;
5067
5068 MAY_LJMP(check_args(L, 2, "Debug"));
5069 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5070 msg = MAY_LJMP(luaL_checkstring(L, 2));
5071 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5072 return 0;
5073}
5074
5075__LJMP static int hlua_txn_log_info(lua_State *L)
5076{
5077 const char *msg;
5078 struct hlua_txn *htxn;
5079
5080 MAY_LJMP(check_args(L, 2, "Info"));
5081 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5082 msg = MAY_LJMP(luaL_checkstring(L, 2));
5083 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5084 return 0;
5085}
5086
5087__LJMP static int hlua_txn_log_warning(lua_State *L)
5088{
5089 const char *msg;
5090 struct hlua_txn *htxn;
5091
5092 MAY_LJMP(check_args(L, 2, "Warning"));
5093 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5094 msg = MAY_LJMP(luaL_checkstring(L, 2));
5095 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5096 return 0;
5097}
5098
5099__LJMP static int hlua_txn_log_alert(lua_State *L)
5100{
5101 const char *msg;
5102 struct hlua_txn *htxn;
5103
5104 MAY_LJMP(check_args(L, 2, "Alert"));
5105 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5106 msg = MAY_LJMP(luaL_checkstring(L, 2));
5107 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5108 return 0;
5109}
5110
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005111__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5112{
5113 struct hlua_txn *htxn;
5114 int ll;
5115
5116 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5117 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5118 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5119
5120 if (ll < 0 || ll > 7)
5121 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5122
5123 htxn->s->logs.level = ll;
5124 return 0;
5125}
5126
5127__LJMP static int hlua_txn_set_tos(lua_State *L)
5128{
5129 struct hlua_txn *htxn;
5130 struct connection *cli_conn;
5131 int tos;
5132
5133 MAY_LJMP(check_args(L, 2, "set_tos"));
5134 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5135 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5136
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005137 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005138 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005139
5140 return 0;
5141}
5142
5143__LJMP static int hlua_txn_set_mark(lua_State *L)
5144{
5145#ifdef SO_MARK
5146 struct hlua_txn *htxn;
5147 struct connection *cli_conn;
5148 int mark;
5149
5150 MAY_LJMP(check_args(L, 2, "set_mark"));
5151 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5152 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5153
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005154 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005155 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005156#endif
5157 return 0;
5158}
5159
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005160/* This function is an Lua binding that send pending data
5161 * to the client, and close the stream interface.
5162 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005163__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005164{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005165 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005166 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01005167 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005168
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005169 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005170 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005171 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005172
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005173 /* If the flags NOTERM is set, we cannot terminate the http
5174 * session, so we just end the execution of the current
5175 * lua code.
5176 */
5177 if (htxn->flags & HLUA_TXN_NOTERM) {
5178 WILL_LJMP(hlua_done(L));
5179 return 0;
5180 }
5181
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005182 ic = &htxn->s->req;
5183 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005184
Willy Tarreau630ef452015-08-28 10:06:15 +02005185 if (htxn->s->txn) {
5186 /* HTTP mode, let's stay in sync with the stream */
5187 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
5188 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
5189 htxn->s->txn->req.sov = 0;
5190 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
5191 oc->analysers = AN_RES_HTTP_XFER_BODY;
5192 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
5193 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
5194
Willy Tarreau630ef452015-08-28 10:06:15 +02005195 /* Note that if we want to support keep-alive, we need
5196 * to bypass the close/shutr_now calls below, but that
5197 * may only be done if the HTTP request was already
5198 * processed and the connection header is known (ie
5199 * not during TCP rules).
5200 */
5201 }
5202
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005203 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01005204 channel_abort(ic);
5205 channel_auto_close(ic);
5206 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005207
5208 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01005209 channel_auto_read(oc);
5210 channel_auto_close(oc);
5211 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005212
Willy Tarreau0458b082015-08-28 09:40:04 +02005213 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005214
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005215 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005216 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005217 return 0;
5218}
5219
5220__LJMP static int hlua_log(lua_State *L)
5221{
5222 int level;
5223 const char *msg;
5224
5225 MAY_LJMP(check_args(L, 2, "log"));
5226 level = MAY_LJMP(luaL_checkinteger(L, 1));
5227 msg = MAY_LJMP(luaL_checkstring(L, 2));
5228
5229 if (level < 0 || level >= NB_LOG_LEVELS)
5230 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5231
5232 hlua_sendlog(NULL, level, msg);
5233 return 0;
5234}
5235
5236__LJMP static int hlua_log_debug(lua_State *L)
5237{
5238 const char *msg;
5239
5240 MAY_LJMP(check_args(L, 1, "debug"));
5241 msg = MAY_LJMP(luaL_checkstring(L, 1));
5242 hlua_sendlog(NULL, LOG_DEBUG, msg);
5243 return 0;
5244}
5245
5246__LJMP static int hlua_log_info(lua_State *L)
5247{
5248 const char *msg;
5249
5250 MAY_LJMP(check_args(L, 1, "info"));
5251 msg = MAY_LJMP(luaL_checkstring(L, 1));
5252 hlua_sendlog(NULL, LOG_INFO, msg);
5253 return 0;
5254}
5255
5256__LJMP static int hlua_log_warning(lua_State *L)
5257{
5258 const char *msg;
5259
5260 MAY_LJMP(check_args(L, 1, "warning"));
5261 msg = MAY_LJMP(luaL_checkstring(L, 1));
5262 hlua_sendlog(NULL, LOG_WARNING, msg);
5263 return 0;
5264}
5265
5266__LJMP static int hlua_log_alert(lua_State *L)
5267{
5268 const char *msg;
5269
5270 MAY_LJMP(check_args(L, 1, "alert"));
5271 msg = MAY_LJMP(luaL_checkstring(L, 1));
5272 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005273 return 0;
5274}
5275
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005276__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005277{
5278 int wakeup_ms = lua_tointeger(L, -1);
5279 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005280 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005281 return 0;
5282}
5283
5284__LJMP static int hlua_sleep(lua_State *L)
5285{
5286 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005287 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005288
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005289 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005290
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005291 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005292 wakeup_ms = tick_add(now_ms, delay);
5293 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005294
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005295 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5296 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005297}
5298
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005299__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005300{
5301 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005302 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005303
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005304 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005305
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005306 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005307 wakeup_ms = tick_add(now_ms, delay);
5308 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005309
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005310 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5311 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005312}
5313
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005314/* This functionis an LUA binding. it permits to give back
5315 * the hand at the HAProxy scheduler. It is used when the
5316 * LUA processing consumes a lot of time.
5317 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005318__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005319{
5320 return 0;
5321}
5322
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005323__LJMP static int hlua_yield(lua_State *L)
5324{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005325 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
5326 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005327}
5328
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005329/* This function change the nice of the currently executed
5330 * task. It is used set low or high priority at the current
5331 * task.
5332 */
Willy Tarreau59551662015-03-10 14:23:13 +01005333__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005334{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005335 struct hlua *hlua;
5336 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005337
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005338 MAY_LJMP(check_args(L, 1, "set_nice"));
5339 hlua = hlua_gethlua(L);
5340 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005341
5342 /* If he task is not set, I'm in a start mode. */
5343 if (!hlua || !hlua->task)
5344 return 0;
5345
5346 if (nice < -1024)
5347 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005348 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005349 nice = 1024;
5350
5351 hlua->task->nice = nice;
5352 return 0;
5353}
5354
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005355/* This function is used as a calback of a task. It is called by the
5356 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5357 * return an E_AGAIN signal, the emmiter of this signal must set a
5358 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005359 *
5360 * Task wrapper are longjmp safe because the only one Lua code
5361 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005362 */
5363static struct task *hlua_process_task(struct task *task)
5364{
5365 struct hlua *hlua = task->context;
5366 enum hlua_exec status;
5367
5368 /* We need to remove the task from the wait queue before executing
5369 * the Lua code because we don't know if it needs to wait for
5370 * another timer or not in the case of E_AGAIN.
5371 */
5372 task_delete(task);
5373
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005374 /* If it is the first call to the task, we must initialize the
5375 * execution timeouts.
5376 */
5377 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005378 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005379
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005380 /* Execute the Lua code. */
5381 status = hlua_ctx_resume(hlua, 1);
5382
5383 switch (status) {
5384 /* finished or yield */
5385 case HLUA_E_OK:
5386 hlua_ctx_destroy(hlua);
5387 task_delete(task);
5388 task_free(task);
5389 break;
5390
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005391 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
5392 if (hlua->wake_time != TICK_ETERNITY)
5393 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005394 break;
5395
5396 /* finished with error. */
5397 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005398 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005399 hlua_ctx_destroy(hlua);
5400 task_delete(task);
5401 task_free(task);
5402 break;
5403
5404 case HLUA_E_ERR:
5405 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005406 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005407 hlua_ctx_destroy(hlua);
5408 task_delete(task);
5409 task_free(task);
5410 break;
5411 }
5412 return NULL;
5413}
5414
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005415/* This function is an LUA binding that register LUA function to be
5416 * executed after the HAProxy configuration parsing and before the
5417 * HAProxy scheduler starts. This function expect only one LUA
5418 * argument that is a function. This function returns nothing, but
5419 * throws if an error is encountered.
5420 */
5421__LJMP static int hlua_register_init(lua_State *L)
5422{
5423 struct hlua_init_function *init;
5424 int ref;
5425
5426 MAY_LJMP(check_args(L, 1, "register_init"));
5427
5428 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5429
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005430 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005431 if (!init)
5432 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5433
5434 init->function_ref = ref;
5435 LIST_ADDQ(&hlua_init_functions, &init->l);
5436 return 0;
5437}
5438
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005439/* This functio is an LUA binding. It permits to register a task
5440 * executed in parallel of the main HAroxy activity. The task is
5441 * created and it is set in the HAProxy scheduler. It can be called
5442 * from the "init" section, "post init" or during the runtime.
5443 *
5444 * Lua prototype:
5445 *
5446 * <none> core.register_task(<function>)
5447 */
5448static int hlua_register_task(lua_State *L)
5449{
5450 struct hlua *hlua;
5451 struct task *task;
5452 int ref;
5453
5454 MAY_LJMP(check_args(L, 1, "register_task"));
5455
5456 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5457
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005458 hlua = pool_alloc2(pool2_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005459 if (!hlua)
5460 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5461
5462 task = task_new();
5463 task->context = hlua;
5464 task->process = hlua_process_task;
5465
5466 if (!hlua_ctx_init(hlua, task))
5467 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5468
5469 /* Restore the function in the stack. */
5470 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5471 hlua->nargs = 0;
5472
5473 /* Schedule task. */
5474 task_schedule(task, now_ms);
5475
5476 return 0;
5477}
5478
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005479/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5480 * doesn't allow "yield" functions because the HAProxy engine cannot
5481 * resume converters.
5482 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005483static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005484{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005485 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005486 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005487 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005488
Willy Tarreaube508f12016-03-10 11:47:01 +01005489 if (!stream)
5490 return 0;
5491
Willy Tarreau87b09662015-04-03 00:22:06 +02005492 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005493 * Lua context can be not initialized. This behavior
5494 * permits to save performances because a systematic
5495 * Lua initialization cause 5% performances loss.
5496 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005497 if (!stream->hlua) {
5498 stream->hlua = pool_alloc2(pool2_hlua);
5499 if (!stream->hlua) {
5500 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5501 return 0;
5502 }
5503 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5504 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5505 return 0;
5506 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005507 }
5508
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005509 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005510 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005511
5512 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005513 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5514 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5515 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005516 else
5517 error = "critical error";
5518 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005519 return 0;
5520 }
5521
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005522 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005523 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005524 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005525 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005526 return 0;
5527 }
5528
5529 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005530 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005531
5532 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005533 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005534 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005535 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005536 return 0;
5537 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005538 hlua_smp2lua(stream->hlua->T, smp);
5539 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005540
5541 /* push keywords in the stack. */
5542 if (arg_p) {
5543 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005544 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005545 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005546 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005547 return 0;
5548 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005549 hlua_arg2lua(stream->hlua->T, arg_p);
5550 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005551 }
5552 }
5553
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005554 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005555 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005556
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005557 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005558 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005559 }
5560
5561 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005562 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005563 /* finished. */
5564 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005565 /* If the stack is empty, the function fails. */
5566 if (lua_gettop(stream->hlua->T) <= 0)
5567 return 0;
5568
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005569 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005570 hlua_lua2smp(stream->hlua->T, -1, smp);
5571 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005572 return 1;
5573
5574 /* yield. */
5575 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005576 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005577 return 0;
5578
5579 /* finished with error. */
5580 case HLUA_E_ERRMSG:
5581 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005582 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005583 fcn->name, lua_tostring(stream->hlua->T, -1));
5584 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005585 return 0;
5586
5587 case HLUA_E_ERR:
5588 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005589 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005590
5591 default:
5592 return 0;
5593 }
5594}
5595
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005596/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5597 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005598 * resume sample-fetches. This function will be called by the sample
5599 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005600 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005601static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5602 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005603{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005604 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005605 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005606 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005607 const struct chunk msg = { .len = 0 };
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005608
Willy Tarreaube508f12016-03-10 11:47:01 +01005609 if (!stream)
5610 return 0;
5611
Willy Tarreau87b09662015-04-03 00:22:06 +02005612 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005613 * Lua context can be not initialized. This behavior
5614 * permits to save performances because a systematic
5615 * Lua initialization cause 5% performances loss.
5616 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005617 if (!stream->hlua) {
5618 stream->hlua = pool_alloc2(pool2_hlua);
5619 if (!stream->hlua) {
5620 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5621 return 0;
5622 }
5623 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5624 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5625 return 0;
5626 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005627 }
5628
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005629 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005630
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005631 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005632 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005633
5634 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005635 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5636 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5637 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005638 else
5639 error = "critical error";
5640 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005641 return 0;
5642 }
5643
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005644 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005645 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005646 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005647 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005648 return 0;
5649 }
5650
5651 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005652 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005653
5654 /* push arguments in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005655 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR,
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005656 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005657 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005658 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005659 return 0;
5660 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005661 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005662
5663 /* push keywords in the stack. */
5664 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5665 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005666 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005667 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005668 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005669 return 0;
5670 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005671 hlua_arg2lua(stream->hlua->T, arg_p);
5672 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005673 }
5674
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005675 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005676 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005677
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005678 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005679 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005680 }
5681
5682 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005683 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005684 /* finished. */
5685 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005686 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005687 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005688 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005689 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005690 /* If the stack is empty, the function fails. */
5691 if (lua_gettop(stream->hlua->T) <= 0)
5692 return 0;
5693
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005694 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005695 hlua_lua2smp(stream->hlua->T, -1, smp);
5696 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005697
5698 /* Set the end of execution flag. */
5699 smp->flags &= ~SMP_F_MAY_CHANGE;
5700 return 1;
5701
5702 /* yield. */
5703 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005704 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005705 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005706 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005707 return 0;
5708
5709 /* finished with error. */
5710 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005711 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005712 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005713 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005714 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005715 fcn->name, lua_tostring(stream->hlua->T, -1));
5716 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005717 return 0;
5718
5719 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005720 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005721 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005722 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005723 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005724
5725 default:
5726 return 0;
5727 }
5728}
5729
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005730/* This function is an LUA binding used for registering
5731 * "sample-conv" functions. It expects a converter name used
5732 * in the haproxy configuration file, and an LUA function.
5733 */
5734__LJMP static int hlua_register_converters(lua_State *L)
5735{
5736 struct sample_conv_kw_list *sck;
5737 const char *name;
5738 int ref;
5739 int len;
5740 struct hlua_function *fcn;
5741
5742 MAY_LJMP(check_args(L, 2, "register_converters"));
5743
5744 /* First argument : converter name. */
5745 name = MAY_LJMP(luaL_checkstring(L, 1));
5746
5747 /* Second argument : lua function. */
5748 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5749
5750 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005751 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005752 if (!sck)
5753 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005754 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005755 if (!fcn)
5756 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5757
5758 /* Fill fcn. */
5759 fcn->name = strdup(name);
5760 if (!fcn->name)
5761 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5762 fcn->function_ref = ref;
5763
5764 /* List head */
5765 sck->list.n = sck->list.p = NULL;
5766
5767 /* converter keyword. */
5768 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005769 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005770 if (!sck->kw[0].kw)
5771 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5772
5773 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5774 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005775 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 +01005776 sck->kw[0].val_args = NULL;
5777 sck->kw[0].in_type = SMP_T_STR;
5778 sck->kw[0].out_type = SMP_T_STR;
5779 sck->kw[0].private = fcn;
5780
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005781 /* Register this new converter */
5782 sample_register_convs(sck);
5783
5784 return 0;
5785}
5786
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005787/* This fucntion is an LUA binding used for registering
5788 * "sample-fetch" functions. It expects a converter name used
5789 * in the haproxy configuration file, and an LUA function.
5790 */
5791__LJMP static int hlua_register_fetches(lua_State *L)
5792{
5793 const char *name;
5794 int ref;
5795 int len;
5796 struct sample_fetch_kw_list *sfk;
5797 struct hlua_function *fcn;
5798
5799 MAY_LJMP(check_args(L, 2, "register_fetches"));
5800
5801 /* First argument : sample-fetch name. */
5802 name = MAY_LJMP(luaL_checkstring(L, 1));
5803
5804 /* Second argument : lua function. */
5805 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5806
5807 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005808 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005809 if (!sfk)
5810 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005811 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005812 if (!fcn)
5813 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5814
5815 /* Fill fcn. */
5816 fcn->name = strdup(name);
5817 if (!fcn->name)
5818 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5819 fcn->function_ref = ref;
5820
5821 /* List head */
5822 sfk->list.n = sfk->list.p = NULL;
5823
5824 /* sample-fetch keyword. */
5825 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005826 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005827 if (!sfk->kw[0].kw)
5828 return luaL_error(L, "lua out of memory error.");
5829
5830 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
5831 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005832 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 +01005833 sfk->kw[0].val_args = NULL;
5834 sfk->kw[0].out_type = SMP_T_STR;
5835 sfk->kw[0].use = SMP_USE_HTTP_ANY;
5836 sfk->kw[0].val = 0;
5837 sfk->kw[0].private = fcn;
5838
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005839 /* Register this new fetch. */
5840 sample_register_fetches(sfk);
5841
5842 return 0;
5843}
5844
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005845/* This function is a wrapper to execute each LUA function declared
5846 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005847 * return ACT_RET_CONT if the processing is finished (with or without
5848 * error) and return ACT_RET_YIELD if the function must be called again
5849 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005850 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005851static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02005852 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005853{
5854 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005855 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005856 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005857 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005858 const struct chunk msg = { .len = 0 };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005859
5860 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01005861 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
5862 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
5863 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
5864 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005865 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005866 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005867 return ACT_RET_CONT;
5868 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005869
Willy Tarreau87b09662015-04-03 00:22:06 +02005870 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005871 * Lua context can be not initialized. This behavior
5872 * permits to save performances because a systematic
5873 * Lua initialization cause 5% performances loss.
5874 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005875 if (!s->hlua) {
5876 s->hlua = pool_alloc2(pool2_hlua);
5877 if (!s->hlua) {
5878 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
5879 rule->arg.hlua_rule->fcn.name);
5880 return ACT_RET_CONT;
5881 }
5882 if (!hlua_ctx_init(s->hlua, s->task)) {
5883 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
5884 rule->arg.hlua_rule->fcn.name);
5885 return ACT_RET_CONT;
5886 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005887 }
5888
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005889 consistency_set(s, dir, &s->hlua->cons);
5890
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005891 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005892 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005893
5894 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005895 if (!SET_SAFE_LJMP(s->hlua->T)) {
5896 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
5897 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005898 else
5899 error = "critical error";
5900 SEND_ERR(px, "Lua function '%s': %s.\n",
5901 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005902 return ACT_RET_CONT;
5903 }
5904
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005905 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005906 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005907 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005908 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005909 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005910 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005911 }
5912
5913 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005914 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005915
Willy Tarreau87b09662015-04-03 00:22:06 +02005916 /* Create and and push object stream in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005917 if (!hlua_txn_new(s->hlua->T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005918 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005919 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005920 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005921 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005922 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005923 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005924
5925 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005926 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005927 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005928 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005929 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005930 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005931 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005932 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005933 lua_pushstring(s->hlua->T, *arg);
5934 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005935 }
5936
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005937 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005938 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005939
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005940 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005941 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005942 }
5943
5944 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005945 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005946 /* finished. */
5947 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005948 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005949 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005950 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005951 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005952 if (s->hlua->flags & HLUA_STOP)
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005953 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005954 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005955
5956 /* yield. */
5957 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005958 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005959 if (s->hlua->wake_time != TICK_ETERNITY) {
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005960 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005961 s->req.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005962 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005963 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005964 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005965 /* Some actions can be wake up when a "write" event
5966 * is detected on a response channel. This is useful
5967 * only for actions targetted on the requests.
5968 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005969 if (HLUA_IS_WAKERESWR(s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005970 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01005971 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005972 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005973 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005974 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005975 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005976 /* We can quit the fcuntion without consistency check
5977 * because HAProxy is not able to manipulate data, it
5978 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005979 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005980
5981 /* finished with error. */
5982 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005983 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005984 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005985 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005986 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005987 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005988 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005989 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
5990 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005991 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005992
5993 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005994 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005995 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005996 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005997 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005998 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005999 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006000 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006001
6002 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006003 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006004 }
6005}
6006
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006007struct task *hlua_applet_wakeup(struct task *t)
6008{
6009 struct appctx *ctx = t->context;
6010 struct stream_interface *si = ctx->owner;
6011
6012 /* If the applet is wake up without any expected work, the sheduler
6013 * remove it from the run queue. This flag indicate that the applet
6014 * is waiting for write. If the buffer is full, the main processing
6015 * will send some data and after call the applet, otherwise it call
6016 * the applet ASAP.
6017 */
6018 si_applet_cant_put(si);
6019 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006020 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006021 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006022}
6023
6024static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6025{
6026 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006027 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006028 struct task *task;
6029 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006030 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006031
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006032 hlua = pool_alloc2(pool2_hlua);
6033 if (!hlua) {
6034 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6035 ctx->rule->arg.hlua_rule->fcn.name);
6036 return 0;
6037 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006038 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006039 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006040 ctx->ctx.hlua_apptcp.flags = 0;
6041
6042 /* Create task used by signal to wakeup applets. */
6043 task = task_new();
6044 if (!task) {
6045 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6046 ctx->rule->arg.hlua_rule->fcn.name);
6047 return 0;
6048 }
6049 task->nice = 0;
6050 task->context = ctx;
6051 task->process = hlua_applet_wakeup;
6052 ctx->ctx.hlua_apptcp.task = task;
6053
6054 /* In the execution wrappers linked with a stream, the
6055 * Lua context can be not initialized. This behavior
6056 * permits to save performances because a systematic
6057 * Lua initialization cause 5% performances loss.
6058 */
6059 if (!hlua_ctx_init(hlua, task)) {
6060 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6061 ctx->rule->arg.hlua_rule->fcn.name);
6062 return 0;
6063 }
6064
6065 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006066 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006067
6068 /* The following Lua calls can fail. */
6069 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006070 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6071 error = lua_tostring(hlua->T, -1);
6072 else
6073 error = "critical error";
6074 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6075 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006076 RESET_SAFE_LJMP(hlua->T);
6077 return 0;
6078 }
6079
6080 /* Check stack available size. */
6081 if (!lua_checkstack(hlua->T, 1)) {
6082 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6083 ctx->rule->arg.hlua_rule->fcn.name);
6084 RESET_SAFE_LJMP(hlua->T);
6085 return 0;
6086 }
6087
6088 /* Restore the function in the stack. */
6089 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6090
6091 /* Create and and push object stream in the stack. */
6092 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
6093 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6094 ctx->rule->arg.hlua_rule->fcn.name);
6095 RESET_SAFE_LJMP(hlua->T);
6096 return 0;
6097 }
6098 hlua->nargs = 1;
6099
6100 /* push keywords in the stack. */
6101 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6102 if (!lua_checkstack(hlua->T, 1)) {
6103 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6104 ctx->rule->arg.hlua_rule->fcn.name);
6105 RESET_SAFE_LJMP(hlua->T);
6106 return 0;
6107 }
6108 lua_pushstring(hlua->T, *arg);
6109 hlua->nargs++;
6110 }
6111
6112 RESET_SAFE_LJMP(hlua->T);
6113
6114 /* Wakeup the applet ASAP. */
6115 si_applet_cant_get(si);
6116 si_applet_cant_put(si);
6117
6118 return 1;
6119}
6120
6121static void hlua_applet_tcp_fct(struct appctx *ctx)
6122{
6123 struct stream_interface *si = ctx->owner;
6124 struct stream *strm = si_strm(si);
6125 struct channel *res = si_ic(si);
6126 struct act_rule *rule = ctx->rule;
6127 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006128 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006129
6130 /* The applet execution is already done. */
6131 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
6132 return;
6133
6134 /* If the stream is disconnect or closed, ldo nothing. */
6135 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6136 return;
6137
6138 /* Execute the function. */
6139 switch (hlua_ctx_resume(hlua, 1)) {
6140 /* finished. */
6141 case HLUA_E_OK:
6142 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6143
6144 /* log time */
6145 strm->logs.tv_request = now;
6146
6147 /* eat the whole request */
6148 bo_skip(si_oc(si), si_ob(si)->o);
6149 res->flags |= CF_READ_NULL;
6150 si_shutr(si);
6151 return;
6152
6153 /* yield. */
6154 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006155 if (hlua->wake_time != TICK_ETERNITY)
6156 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006157 return;
6158
6159 /* finished with error. */
6160 case HLUA_E_ERRMSG:
6161 /* Display log. */
6162 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6163 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6164 lua_pop(hlua->T, 1);
6165 goto error;
6166
6167 case HLUA_E_ERR:
6168 /* Display log. */
6169 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6170 rule->arg.hlua_rule->fcn.name);
6171 goto error;
6172
6173 default:
6174 goto error;
6175 }
6176
6177error:
6178
6179 /* For all other cases, just close the stream. */
6180 si_shutw(si);
6181 si_shutr(si);
6182 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6183}
6184
6185static void hlua_applet_tcp_release(struct appctx *ctx)
6186{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006187 task_delete(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006188 task_free(ctx->ctx.hlua_apptcp.task);
6189 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006190 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006191 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006192}
6193
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006194/* The function returns 1 if the initialisation is complete, 0 if
6195 * an errors occurs and -1 if more data are required for initializing
6196 * the applet.
6197 */
6198static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6199{
6200 struct stream_interface *si = ctx->owner;
6201 struct channel *req = si_oc(si);
6202 struct http_msg *msg;
6203 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006204 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006205 char **arg;
6206 struct hdr_ctx hdr;
6207 struct task *task;
6208 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01006209 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006210
6211 /* Wait for a full HTTP request. */
6212 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
6213 if (smp.flags & SMP_F_MAY_CHANGE)
6214 return -1;
6215 return 0;
6216 }
6217 txn = strm->txn;
6218 msg = &txn->req;
6219
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006220 /* We want two things in HTTP mode :
6221 * - enforce server-close mode if we were in keep-alive, so that the
6222 * applet is released after each response ;
6223 * - enable request body transfer to the applet in order to resync
6224 * with the response body.
6225 */
6226 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
6227 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006228
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006229 hlua = pool_alloc2(pool2_hlua);
6230 if (!hlua) {
6231 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6232 ctx->rule->arg.hlua_rule->fcn.name);
6233 return 0;
6234 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006235 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006236 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006237 ctx->ctx.hlua_apphttp.left_bytes = -1;
6238 ctx->ctx.hlua_apphttp.flags = 0;
6239
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006240 if (txn->req.flags & HTTP_MSGF_VER_11)
6241 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6242
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006243 /* Create task used by signal to wakeup applets. */
6244 task = task_new();
6245 if (!task) {
6246 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6247 ctx->rule->arg.hlua_rule->fcn.name);
6248 return 0;
6249 }
6250 task->nice = 0;
6251 task->context = ctx;
6252 task->process = hlua_applet_wakeup;
6253 ctx->ctx.hlua_apphttp.task = task;
6254
6255 /* In the execution wrappers linked with a stream, the
6256 * Lua context can be not initialized. This behavior
6257 * permits to save performances because a systematic
6258 * Lua initialization cause 5% performances loss.
6259 */
6260 if (!hlua_ctx_init(hlua, task)) {
6261 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6262 ctx->rule->arg.hlua_rule->fcn.name);
6263 return 0;
6264 }
6265
6266 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006267 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006268
6269 /* The following Lua calls can fail. */
6270 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006271 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6272 error = lua_tostring(hlua->T, -1);
6273 else
6274 error = "critical error";
6275 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6276 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006277 return 0;
6278 }
6279
6280 /* Check stack available size. */
6281 if (!lua_checkstack(hlua->T, 1)) {
6282 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6283 ctx->rule->arg.hlua_rule->fcn.name);
6284 RESET_SAFE_LJMP(hlua->T);
6285 return 0;
6286 }
6287
6288 /* Restore the function in the stack. */
6289 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6290
6291 /* Create and and push object stream in the stack. */
6292 if (!hlua_applet_http_new(hlua->T, ctx)) {
6293 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6294 ctx->rule->arg.hlua_rule->fcn.name);
6295 RESET_SAFE_LJMP(hlua->T);
6296 return 0;
6297 }
6298 hlua->nargs = 1;
6299
6300 /* Look for a 100-continue expected. */
6301 if (msg->flags & HTTP_MSGF_VER_11) {
6302 hdr.idx = 0;
6303 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
6304 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
6305 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
6306 }
6307
6308 /* push keywords in the stack. */
6309 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6310 if (!lua_checkstack(hlua->T, 1)) {
6311 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6312 ctx->rule->arg.hlua_rule->fcn.name);
6313 RESET_SAFE_LJMP(hlua->T);
6314 return 0;
6315 }
6316 lua_pushstring(hlua->T, *arg);
6317 hlua->nargs++;
6318 }
6319
6320 RESET_SAFE_LJMP(hlua->T);
6321
6322 /* Wakeup the applet when data is ready for read. */
6323 si_applet_cant_get(si);
6324
6325 return 1;
6326}
6327
6328static void hlua_applet_http_fct(struct appctx *ctx)
6329{
6330 struct stream_interface *si = ctx->owner;
6331 struct stream *strm = si_strm(si);
6332 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006333 struct act_rule *rule = ctx->rule;
6334 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006335 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006336 char *blk1;
6337 int len1;
6338 char *blk2;
6339 int len2;
6340 int ret;
6341
6342 /* If the stream is disconnect or closed, ldo nothing. */
6343 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6344 return;
6345
6346 /* Set the currently running flag. */
6347 if (!HLUA_IS_RUNNING(hlua) &&
6348 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6349
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006350 /* Wait for full HTTP analysys. */
6351 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6352 si_applet_cant_get(si);
6353 return;
6354 }
6355
6356 /* Store the max amount of bytes that we can read. */
6357 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6358
6359 /* We need to flush the request header. This left the body
6360 * for the Lua.
6361 */
6362
6363 /* Read the maximum amount of data avalaible. */
6364 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
6365 if (ret == -1)
6366 return;
6367
6368 /* No data available, ask for more data. */
6369 if (ret == 1)
6370 len2 = 0;
6371 if (ret == 0)
6372 len1 = 0;
6373 if (len1 + len2 < strm->txn->req.eoh + 2) {
6374 si_applet_cant_get(si);
6375 return;
6376 }
6377
6378 /* skip the requests bytes. */
6379 bo_skip(si_oc(si), strm->txn->req.eoh + 2);
6380 }
6381
6382 /* Executes The applet if it is not done. */
6383 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6384
6385 /* Execute the function. */
6386 switch (hlua_ctx_resume(hlua, 1)) {
6387 /* finished. */
6388 case HLUA_E_OK:
6389 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6390 break;
6391
6392 /* yield. */
6393 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006394 if (hlua->wake_time != TICK_ETERNITY)
6395 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006396 return;
6397
6398 /* finished with error. */
6399 case HLUA_E_ERRMSG:
6400 /* Display log. */
6401 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6402 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6403 lua_pop(hlua->T, 1);
6404 goto error;
6405
6406 case HLUA_E_ERR:
6407 /* Display log. */
6408 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6409 rule->arg.hlua_rule->fcn.name);
6410 goto error;
6411
6412 default:
6413 goto error;
6414 }
6415 }
6416
6417 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6418
6419 /* We must send the final chunk. */
6420 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6421 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6422
6423 /* sent last chunk at once. */
6424 ret = bi_putblk(res, "0\r\n\r\n", 5);
6425
6426 /* critical error. */
6427 if (ret == -2 || ret == -3) {
6428 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6429 rule->arg.hlua_rule->fcn.name);
6430 goto error;
6431 }
6432
6433 /* no enough space error. */
6434 if (ret == -1) {
6435 si_applet_cant_put(si);
6436 return;
6437 }
6438
6439 /* set the last chunk sent. */
6440 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6441 }
6442
6443 /* close the connection. */
6444
6445 /* status / log */
6446 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6447 strm->logs.tv_request = now;
6448
6449 /* eat the whole request */
6450 bo_skip(si_oc(si), si_ob(si)->o);
6451 res->flags |= CF_READ_NULL;
6452 si_shutr(si);
6453
6454 return;
6455 }
6456
6457error:
6458
6459 /* If we are in HTTP mode, and we are not send any
6460 * data, return a 500 server error in best effort:
6461 * if there are no room avalaible in the buffer,
6462 * just close the connection.
6463 */
6464 bi_putblk(res, error_500, strlen(error_500));
6465 if (!(strm->flags & SF_ERR_MASK))
6466 strm->flags |= SF_ERR_RESOURCE;
6467 si_shutw(si);
6468 si_shutr(si);
6469 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6470}
6471
6472static void hlua_applet_http_release(struct appctx *ctx)
6473{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006474 task_delete(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006475 task_free(ctx->ctx.hlua_apphttp.task);
6476 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006477 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006478 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006479}
6480
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006481/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6482 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006483 *
6484 * This function can fail with an abort() due to an Lua critical error.
6485 * We are in the configuration parsing process of HAProxy, this abort() is
6486 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006487 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006488static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6489 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006490{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006491 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006492 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006493
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006494 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006495 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006496 if (!rule->arg.hlua_rule) {
6497 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006498 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006499 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006500
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006501 /* Memory for arguments. */
6502 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
6503 if (!rule->arg.hlua_rule->args) {
6504 memprintf(err, "out of memory error");
6505 return ACT_RET_PRS_ERR;
6506 }
6507
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006508 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006509 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006510
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006511 /* Expect some arguments */
6512 for (i = 0; i < fcn->nargs; i++) {
6513 if (*args[i+1] == '\0') {
6514 memprintf(err, "expect %d arguments", fcn->nargs);
6515 return ACT_RET_PRS_ERR;
6516 }
6517 rule->arg.hlua_rule->args[i] = strdup(args[i + 1]);
6518 if (!rule->arg.hlua_rule->args[i]) {
6519 memprintf(err, "out of memory error");
6520 return ACT_RET_PRS_ERR;
6521 }
6522 (*cur_arg)++;
6523 }
6524 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006525
Thierry FOURNIER42148732015-09-02 17:17:33 +02006526 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006527 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006528 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006529}
6530
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006531static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6532 struct act_rule *rule, char **err)
6533{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006534 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006535
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006536 /* HTTP applets are forbidden in tcp-request rules.
6537 * HTTP applet request requires everything initilized by
6538 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6539 * The applet will be immediately initilized, but its before
6540 * the call of this analyzer.
6541 */
6542 if (rule->from != ACT_F_HTTP_REQ) {
6543 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6544 return ACT_RET_PRS_ERR;
6545 }
6546
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006547 /* Memory for the rule. */
6548 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6549 if (!rule->arg.hlua_rule) {
6550 memprintf(err, "out of memory error");
6551 return ACT_RET_PRS_ERR;
6552 }
6553
6554 /* Reference the Lua function and store the reference. */
6555 rule->arg.hlua_rule->fcn = *fcn;
6556
6557 /* TODO: later accept arguments. */
6558 rule->arg.hlua_rule->args = NULL;
6559
6560 /* Add applet pointer in the rule. */
6561 rule->applet.obj_type = OBJ_TYPE_APPLET;
6562 rule->applet.name = fcn->name;
6563 rule->applet.init = hlua_applet_http_init;
6564 rule->applet.fct = hlua_applet_http_fct;
6565 rule->applet.release = hlua_applet_http_release;
6566 rule->applet.timeout = hlua_timeout_applet;
6567
6568 return ACT_RET_PRS_OK;
6569}
6570
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006571/* This function is an LUA binding used for registering
6572 * "sample-conv" functions. It expects a converter name used
6573 * in the haproxy configuration file, and an LUA function.
6574 */
6575__LJMP static int hlua_register_action(lua_State *L)
6576{
6577 struct action_kw_list *akl;
6578 const char *name;
6579 int ref;
6580 int len;
6581 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006582 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006583
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006584 /* Initialise the number of expected arguments at 0. */
6585 nargs = 0;
6586
6587 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6588 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006589
6590 /* First argument : converter name. */
6591 name = MAY_LJMP(luaL_checkstring(L, 1));
6592
6593 /* Second argument : environment. */
6594 if (lua_type(L, 2) != LUA_TTABLE)
6595 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6596
6597 /* Third argument : lua function. */
6598 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6599
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006600 /* Fouth argument : number of mandatories arguments expected on the configuration line. */
6601 if (lua_gettop(L) >= 4)
6602 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
6603
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006604 /* browse the second argulent as an array. */
6605 lua_pushnil(L);
6606 while (lua_next(L, 2) != 0) {
6607 if (lua_type(L, -1) != LUA_TSTRING)
6608 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6609
6610 /* Check required environment. Only accepted "http" or "tcp". */
6611 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006612 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006613 if (!akl)
6614 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006615 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006616 if (!fcn)
6617 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6618
6619 /* Fill fcn. */
6620 fcn->name = strdup(name);
6621 if (!fcn->name)
6622 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6623 fcn->function_ref = ref;
6624
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006625 /* Set the expected number od arguments. */
6626 fcn->nargs = nargs;
6627
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006628 /* List head */
6629 akl->list.n = akl->list.p = NULL;
6630
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006631 /* action keyword. */
6632 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006633 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006634 if (!akl->kw[0].kw)
6635 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6636
6637 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6638
6639 akl->kw[0].match_pfx = 0;
6640 akl->kw[0].private = fcn;
6641 akl->kw[0].parse = action_register_lua;
6642
6643 /* select the action registering point. */
6644 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6645 tcp_req_cont_keywords_register(akl);
6646 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6647 tcp_res_cont_keywords_register(akl);
6648 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6649 http_req_keywords_register(akl);
6650 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6651 http_res_keywords_register(akl);
6652 else
6653 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
6654 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6655 "are expected.", lua_tostring(L, -1)));
6656
6657 /* pop the environment string. */
6658 lua_pop(L, 1);
6659 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006660 return ACT_RET_PRS_OK;
6661}
6662
6663static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6664 struct act_rule *rule, char **err)
6665{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006666 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006667
6668 /* Memory for the rule. */
6669 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6670 if (!rule->arg.hlua_rule) {
6671 memprintf(err, "out of memory error");
6672 return ACT_RET_PRS_ERR;
6673 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006674
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006675 /* Reference the Lua function and store the reference. */
6676 rule->arg.hlua_rule->fcn = *fcn;
6677
6678 /* TODO: later accept arguments. */
6679 rule->arg.hlua_rule->args = NULL;
6680
6681 /* Add applet pointer in the rule. */
6682 rule->applet.obj_type = OBJ_TYPE_APPLET;
6683 rule->applet.name = fcn->name;
6684 rule->applet.init = hlua_applet_tcp_init;
6685 rule->applet.fct = hlua_applet_tcp_fct;
6686 rule->applet.release = hlua_applet_tcp_release;
6687 rule->applet.timeout = hlua_timeout_applet;
6688
6689 return 0;
6690}
6691
6692/* This function is an LUA binding used for registering
6693 * "sample-conv" functions. It expects a converter name used
6694 * in the haproxy configuration file, and an LUA function.
6695 */
6696__LJMP static int hlua_register_service(lua_State *L)
6697{
6698 struct action_kw_list *akl;
6699 const char *name;
6700 const char *env;
6701 int ref;
6702 int len;
6703 struct hlua_function *fcn;
6704
6705 MAY_LJMP(check_args(L, 3, "register_service"));
6706
6707 /* First argument : converter name. */
6708 name = MAY_LJMP(luaL_checkstring(L, 1));
6709
6710 /* Second argument : environment. */
6711 env = MAY_LJMP(luaL_checkstring(L, 2));
6712
6713 /* Third argument : lua function. */
6714 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6715
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006716 /* Allocate and fill the sample fetch keyword struct. */
6717 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6718 if (!akl)
6719 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6720 fcn = calloc(1, sizeof(*fcn));
6721 if (!fcn)
6722 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6723
6724 /* Fill fcn. */
6725 len = strlen("<lua.>") + strlen(name) + 1;
6726 fcn->name = calloc(1, len);
6727 if (!fcn->name)
6728 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6729 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6730 fcn->function_ref = ref;
6731
6732 /* List head */
6733 akl->list.n = akl->list.p = NULL;
6734
6735 /* converter keyword. */
6736 len = strlen("lua.") + strlen(name) + 1;
6737 akl->kw[0].kw = calloc(1, len);
6738 if (!akl->kw[0].kw)
6739 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6740
6741 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6742
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01006743 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006744 if (strcmp(env, "tcp") == 0)
6745 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006746 else if (strcmp(env, "http") == 0)
6747 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006748 else
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006749 WILL_LJMP(luaL_error(L, "lua service environment '%s' is unknown. "
6750 "'tcp' or 'http' are expected."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006751
6752 akl->kw[0].match_pfx = 0;
6753 akl->kw[0].private = fcn;
6754
6755 /* End of array. */
6756 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6757
6758 /* Register this new converter */
6759 service_keywords_register(akl);
6760
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006761 return 0;
6762}
6763
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006764/* This function initialises Lua cli handler. It copies the
6765 * arguments in the Lua stack and create channel IO objects.
6766 */
6767static int hlua_cli_parse_fct(char **args, struct appctx *appctx, void *private)
6768{
6769 struct hlua *hlua;
6770 struct hlua_function *fcn;
6771 int i;
6772 const char *error;
6773
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006774 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006775 appctx->ctx.hlua_cli.fcn = private;
6776
6777 hlua = pool_alloc2(pool2_hlua);
6778 if (!hlua) {
6779 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006780 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006781 }
6782 HLUA_INIT(hlua);
6783 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006784
6785 /* Create task used by signal to wakeup applets.
6786 * We use the same wakeup fonction than the Lua applet_tcp and
6787 * applet_http. It is absolutely compatible.
6788 */
6789 appctx->ctx.hlua_cli.task = task_new();
6790 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01006791 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006792 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006793 }
6794 appctx->ctx.hlua_cli.task->nice = 0;
6795 appctx->ctx.hlua_cli.task->context = appctx;
6796 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
6797
6798 /* Initialises the Lua context */
6799 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
6800 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006801 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006802 }
6803
6804 /* The following Lua calls can fail. */
6805 if (!SET_SAFE_LJMP(hlua->T)) {
6806 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6807 error = lua_tostring(hlua->T, -1);
6808 else
6809 error = "critical error";
6810 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
6811 goto error;
6812 }
6813
6814 /* Check stack available size. */
6815 if (!lua_checkstack(hlua->T, 2)) {
6816 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6817 goto error;
6818 }
6819
6820 /* Restore the function in the stack. */
6821 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
6822
6823 /* Once the arguments parsed, the CLI is like an AppletTCP,
6824 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006825 */
6826 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
6827 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6828 goto error;
6829 }
6830 hlua->nargs = 1;
6831
6832 /* push keywords in the stack. */
6833 for (i = 0; *args[i]; i++) {
6834 /* Check stack available size. */
6835 if (!lua_checkstack(hlua->T, 1)) {
6836 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6837 goto error;
6838 }
6839 lua_pushstring(hlua->T, args[i]);
6840 hlua->nargs++;
6841 }
6842
6843 /* We must initialize the execution timeouts. */
6844 hlua->max_time = hlua_timeout_session;
6845
6846 /* At this point the execution is safe. */
6847 RESET_SAFE_LJMP(hlua->T);
6848
6849 /* It's ok */
6850 return 0;
6851
6852 /* It's not ok. */
6853error:
6854 RESET_SAFE_LJMP(hlua->T);
6855 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01006856 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006857 return 1;
6858}
6859
6860static int hlua_cli_io_handler_fct(struct appctx *appctx)
6861{
6862 struct hlua *hlua;
6863 struct stream_interface *si;
6864 struct hlua_function *fcn;
6865
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006866 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006867 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01006868 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006869
6870 /* If the stream is disconnect or closed, ldo nothing. */
6871 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6872 return 1;
6873
6874 /* Execute the function. */
6875 switch (hlua_ctx_resume(hlua, 1)) {
6876
6877 /* finished. */
6878 case HLUA_E_OK:
6879 return 1;
6880
6881 /* yield. */
6882 case HLUA_E_AGAIN:
6883 /* We want write. */
6884 if (HLUA_IS_WAKERESWR(hlua))
6885 si_applet_cant_put(si);
6886 /* Set the timeout. */
6887 if (hlua->wake_time != TICK_ETERNITY)
6888 task_schedule(hlua->task, hlua->wake_time);
6889 return 0;
6890
6891 /* finished with error. */
6892 case HLUA_E_ERRMSG:
6893 /* Display log. */
6894 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
6895 fcn->name, lua_tostring(hlua->T, -1));
6896 lua_pop(hlua->T, 1);
6897 return 1;
6898
6899 case HLUA_E_ERR:
6900 /* Display log. */
6901 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
6902 fcn->name);
6903 return 1;
6904
6905 default:
6906 return 1;
6907 }
6908
6909 return 1;
6910}
6911
6912static void hlua_cli_io_release_fct(struct appctx *appctx)
6913{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006914 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006915 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006916}
6917
6918/* This function is an LUA binding used for registering
6919 * new keywords in the cli. It expects a list of keywords
6920 * which are the "path". It is limited to 5 keywords. A
6921 * description of the command, a function to be executed
6922 * for the parsing and a function for io handlers.
6923 */
6924__LJMP static int hlua_register_cli(lua_State *L)
6925{
6926 struct cli_kw_list *cli_kws;
6927 const char *message;
6928 int ref_io;
6929 int len;
6930 struct hlua_function *fcn;
6931 int index;
6932 int i;
6933
6934 MAY_LJMP(check_args(L, 3, "register_cli"));
6935
6936 /* First argument : an array of maximum 5 keywords. */
6937 if (!lua_istable(L, 1))
6938 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
6939
6940 /* Second argument : string with contextual message. */
6941 message = MAY_LJMP(luaL_checkstring(L, 2));
6942
6943 /* Third and fourth argument : lua function. */
6944 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
6945
6946 /* Allocate and fill the sample fetch keyword struct. */
6947 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
6948 if (!cli_kws)
6949 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6950 fcn = calloc(1, sizeof(*fcn));
6951 if (!fcn)
6952 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6953
6954 /* Fill path. */
6955 index = 0;
6956 lua_pushnil(L);
6957 while(lua_next(L, 1) != 0) {
6958 if (index >= 5)
6959 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
6960 if (lua_type(L, -1) != LUA_TSTRING)
6961 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
6962 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
6963 if (!cli_kws->kw[0].str_kw[index])
6964 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6965 index++;
6966 lua_pop(L, 1);
6967 }
6968
6969 /* Copy help message. */
6970 cli_kws->kw[0].usage = strdup(message);
6971 if (!cli_kws->kw[0].usage)
6972 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6973
6974 /* Fill fcn io handler. */
6975 len = strlen("<lua.cli>") + 1;
6976 for (i = 0; i < index; i++)
6977 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
6978 fcn->name = calloc(1, len);
6979 if (!fcn->name)
6980 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6981 strncat((char *)fcn->name, "<lua.cli", len);
6982 for (i = 0; i < index; i++) {
6983 strncat((char *)fcn->name, ".", len);
6984 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
6985 }
6986 strncat((char *)fcn->name, ">", len);
6987 fcn->function_ref = ref_io;
6988
6989 /* Fill last entries. */
6990 cli_kws->kw[0].private = fcn;
6991 cli_kws->kw[0].parse = hlua_cli_parse_fct;
6992 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
6993 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
6994
6995 /* Register this new converter */
6996 cli_register_kw(cli_kws);
6997
6998 return 0;
6999}
7000
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007001static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
7002 struct proxy *defpx, const char *file, int line,
7003 char **err, unsigned int *timeout)
7004{
7005 const char *error;
7006
7007 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
7008 if (error && *error != '\0') {
7009 memprintf(err, "%s: invalid timeout", args[0]);
7010 return -1;
7011 }
7012 return 0;
7013}
7014
7015static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
7016 struct proxy *defpx, const char *file, int line,
7017 char **err)
7018{
7019 return hlua_read_timeout(args, section_type, curpx, defpx,
7020 file, line, err, &hlua_timeout_session);
7021}
7022
7023static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
7024 struct proxy *defpx, const char *file, int line,
7025 char **err)
7026{
7027 return hlua_read_timeout(args, section_type, curpx, defpx,
7028 file, line, err, &hlua_timeout_task);
7029}
7030
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007031static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
7032 struct proxy *defpx, const char *file, int line,
7033 char **err)
7034{
7035 return hlua_read_timeout(args, section_type, curpx, defpx,
7036 file, line, err, &hlua_timeout_applet);
7037}
7038
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007039static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
7040 struct proxy *defpx, const char *file, int line,
7041 char **err)
7042{
7043 char *error;
7044
7045 hlua_nb_instruction = strtoll(args[1], &error, 10);
7046 if (*error != '\0') {
7047 memprintf(err, "%s: invalid number", args[0]);
7048 return -1;
7049 }
7050 return 0;
7051}
7052
Willy Tarreau32f61e22015-03-18 17:54:59 +01007053static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
7054 struct proxy *defpx, const char *file, int line,
7055 char **err)
7056{
7057 char *error;
7058
7059 if (*(args[1]) == 0) {
7060 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
7061 return -1;
7062 }
7063 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
7064 if (*error != '\0') {
7065 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
7066 return -1;
7067 }
7068 return 0;
7069}
7070
7071
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007072/* This function is called by the main configuration key "lua-load". It loads and
7073 * execute an lua file during the parsing of the HAProxy configuration file. It is
7074 * the main lua entry point.
7075 *
7076 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
7077 * occured, otherwise it returns 0.
7078 *
7079 * In some error case, LUA set an error message in top of the stack. This function
7080 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007081 *
7082 * This function can fail with an abort() due to an Lua critical error.
7083 * We are in the configuration parsing process of HAProxy, this abort() is
7084 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007085 */
7086static int hlua_load(char **args, int section_type, struct proxy *curpx,
7087 struct proxy *defpx, const char *file, int line,
7088 char **err)
7089{
7090 int error;
7091
7092 /* Just load and compile the file. */
7093 error = luaL_loadfile(gL.T, args[1]);
7094 if (error) {
7095 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
7096 lua_pop(gL.T, 1);
7097 return -1;
7098 }
7099
7100 /* If no syntax error where detected, execute the code. */
7101 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
7102 switch (error) {
7103 case LUA_OK:
7104 break;
7105 case LUA_ERRRUN:
7106 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
7107 lua_pop(gL.T, 1);
7108 return -1;
7109 case LUA_ERRMEM:
7110 memprintf(err, "lua out of memory error\n");
7111 return -1;
7112 case LUA_ERRERR:
7113 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
7114 lua_pop(gL.T, 1);
7115 return -1;
7116 case LUA_ERRGCMM:
7117 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
7118 lua_pop(gL.T, 1);
7119 return -1;
7120 default:
7121 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
7122 lua_pop(gL.T, 1);
7123 return -1;
7124 }
7125
7126 return 0;
7127}
7128
7129/* configuration keywords declaration */
7130static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007131 { CFG_GLOBAL, "lua-load", hlua_load },
7132 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
7133 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02007134 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007135 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01007136 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007137 { 0, NULL, NULL },
7138}};
7139
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007140/* This function can fail with an abort() due to an Lua critical error.
7141 * We are in the initialisation process of HAProxy, this abort() is
7142 * tolerated.
7143 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007144int hlua_post_init()
7145{
7146 struct hlua_init_function *init;
7147 const char *msg;
7148 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007149 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007150
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007151 /* Call post initialisation function in safe environement. */
7152 if (!SET_SAFE_LJMP(gL.T)) {
7153 if (lua_type(gL.T, -1) == LUA_TSTRING)
7154 error = lua_tostring(gL.T, -1);
7155 else
7156 error = "critical error";
7157 fprintf(stderr, "Lua post-init: %s.\n", error);
7158 exit(1);
7159 }
7160 hlua_fcn_post_init(gL.T);
7161 RESET_SAFE_LJMP(gL.T);
7162
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007163 list_for_each_entry(init, &hlua_init_functions, l) {
7164 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7165 ret = hlua_ctx_resume(&gL, 0);
7166 switch (ret) {
7167 case HLUA_E_OK:
7168 lua_pop(gL.T, -1);
7169 return 1;
7170 case HLUA_E_AGAIN:
7171 Alert("lua init: yield not allowed.\n");
7172 return 0;
7173 case HLUA_E_ERRMSG:
7174 msg = lua_tostring(gL.T, -1);
7175 Alert("lua init: %s.\n", msg);
7176 return 0;
7177 case HLUA_E_ERR:
7178 default:
7179 Alert("lua init: unknown runtime error.\n");
7180 return 0;
7181 }
7182 }
7183 return 1;
7184}
7185
Willy Tarreau32f61e22015-03-18 17:54:59 +01007186/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7187 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7188 * is the previously allocated size or the kind of object in case of a new
7189 * allocation. <nsize> is the requested new size.
7190 */
7191static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7192{
7193 struct hlua_mem_allocator *zone = ud;
7194
7195 if (nsize == 0) {
7196 /* it's a free */
7197 if (ptr)
7198 zone->allocated -= osize;
7199 free(ptr);
7200 return NULL;
7201 }
7202
7203 if (!ptr) {
7204 /* it's a new allocation */
7205 if (zone->limit && zone->allocated + nsize > zone->limit)
7206 return NULL;
7207
7208 ptr = malloc(nsize);
7209 if (ptr)
7210 zone->allocated += nsize;
7211 return ptr;
7212 }
7213
7214 /* it's a realloc */
7215 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7216 return NULL;
7217
7218 ptr = realloc(ptr, nsize);
7219 if (ptr)
7220 zone->allocated += nsize - osize;
7221 return ptr;
7222}
7223
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007224/* Ithis function can fail with an abort() due to an Lua critical error.
7225 * We are in the initialisation process of HAProxy, this abort() is
7226 * tolerated.
7227 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007228void hlua_init(void)
7229{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007230 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007231 int idx;
7232 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007233 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007234 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007235 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007236#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007237 struct srv_kw *kw;
7238 int tmp_error;
7239 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007240 char *args[] = { /* SSL client configuration. */
7241 "ssl",
7242 "verify",
7243 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007244 NULL
7245 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007246#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007247
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007248 /* Initialise struct hlua and com signals pool */
7249 pool2_hlua = create_pool("hlua", sizeof(struct hlua), MEM_F_SHARED);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007250
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007251 /* Register configuration keywords. */
7252 cfg_register_keywords(&cfg_kws);
7253
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007254 /* Init main lua stack. */
7255 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01007256 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007257 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02007258 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007259 hlua_sethlua(&gL);
7260 gL.Tref = LUA_REFNIL;
7261 gL.task = NULL;
7262
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007263 /* From this point, until the end of the initialisation fucntion,
7264 * the Lua function can fail with an abort. We are in the initialisation
7265 * process of HAProxy, this abort() is tolerated.
7266 */
7267
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007268 /* Initialise lua. */
7269 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007270
Thierry Fournier75933d42016-01-21 09:30:18 +01007271 /* Set safe environment for the initialisation. */
7272 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007273 if (lua_type(gL.T, -1) == LUA_TSTRING)
7274 error_msg = lua_tostring(gL.T, -1);
7275 else
7276 error_msg = "critical error";
7277 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01007278 exit(1);
7279 }
7280
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007281 /*
7282 *
7283 * Create "core" object.
7284 *
7285 */
7286
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01007287 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007288 lua_newtable(gL.T);
7289
7290 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007291 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007292 hlua_class_const_int(gL.T, log_levels[i], i);
7293
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007294 /* Register special functions. */
7295 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007296 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007297 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007298 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007299 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007300 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007301 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007302 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01007303 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007304 hlua_class_function(gL.T, "sleep", hlua_sleep);
7305 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01007306 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
7307 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
7308 hlua_class_function(gL.T, "set_map", hlua_set_map);
7309 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007310 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007311 hlua_class_function(gL.T, "log", hlua_log);
7312 hlua_class_function(gL.T, "Debug", hlua_log_debug);
7313 hlua_class_function(gL.T, "Info", hlua_log_info);
7314 hlua_class_function(gL.T, "Warning", hlua_log_warning);
7315 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02007316 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01007317 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007318
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007319 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007320
7321 /*
7322 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007323 * Register class Map
7324 *
7325 */
7326
7327 /* This table entry is the object "Map" base. */
7328 lua_newtable(gL.T);
7329
7330 /* register pattern types. */
7331 for (i=0; i<PAT_MATCH_NUM; i++)
7332 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007333 for (i=0; i<PAT_MATCH_NUM; i++) {
7334 snprintf(trash.str, trash.size, "_%s", pat_match_names[i]);
7335 hlua_class_const_int(gL.T, trash.str, i);
7336 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007337
7338 /* register constructor. */
7339 hlua_class_function(gL.T, "new", hlua_map_new);
7340
7341 /* Create and fill the metatable. */
7342 lua_newtable(gL.T);
7343
7344 /* Create and fille the __index entry. */
7345 lua_pushstring(gL.T, "__index");
7346 lua_newtable(gL.T);
7347
7348 /* Register . */
7349 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
7350 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
7351
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007352 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007353
Thierry Fournier45e78d72016-02-19 18:34:46 +01007354 /* Register previous table in the registry with reference and named entry.
7355 * The function hlua_register_metatable() pops the stack, so we
7356 * previously create a copy of the table.
7357 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007358 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007359 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007360
7361 /* Assign the metatable to the mai Map object. */
7362 lua_setmetatable(gL.T, -2);
7363
7364 /* Set a name to the table. */
7365 lua_setglobal(gL.T, "Map");
7366
7367 /*
7368 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007369 * Register class Channel
7370 *
7371 */
7372
7373 /* Create and fill the metatable. */
7374 lua_newtable(gL.T);
7375
7376 /* Create and fille the __index entry. */
7377 lua_pushstring(gL.T, "__index");
7378 lua_newtable(gL.T);
7379
7380 /* Register . */
7381 hlua_class_function(gL.T, "get", hlua_channel_get);
7382 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7383 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7384 hlua_class_function(gL.T, "set", hlua_channel_set);
7385 hlua_class_function(gL.T, "append", hlua_channel_append);
7386 hlua_class_function(gL.T, "send", hlua_channel_send);
7387 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7388 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7389 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007390 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007391
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007392 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007393
7394 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007395 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007396
7397 /*
7398 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007399 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007400 *
7401 */
7402
7403 /* Create and fill the metatable. */
7404 lua_newtable(gL.T);
7405
7406 /* Create and fille the __index entry. */
7407 lua_pushstring(gL.T, "__index");
7408 lua_newtable(gL.T);
7409
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007410 /* Browse existing fetches and create the associated
7411 * object method.
7412 */
7413 sf = NULL;
7414 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7415
7416 /* Dont register the keywork if the arguments check function are
7417 * not safe during the runtime.
7418 */
7419 if ((sf->val_args != NULL) &&
7420 (sf->val_args != val_payload_lv) &&
7421 (sf->val_args != val_hdr))
7422 continue;
7423
7424 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7425 * by an underscore.
7426 */
7427 strncpy(trash.str, sf->kw, trash.size);
7428 trash.str[trash.size - 1] = '\0';
7429 for (p = trash.str; *p; p++)
7430 if (*p == '.' || *p == '-' || *p == '+')
7431 *p = '_';
7432
7433 /* Register the function. */
7434 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007435 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007436 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007437 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007438 }
7439
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007440 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007441
7442 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007443 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007444
7445 /*
7446 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007447 * Register class Converters
7448 *
7449 */
7450
7451 /* Create and fill the metatable. */
7452 lua_newtable(gL.T);
7453
7454 /* Create and fill the __index entry. */
7455 lua_pushstring(gL.T, "__index");
7456 lua_newtable(gL.T);
7457
7458 /* Browse existing converters and create the associated
7459 * object method.
7460 */
7461 sc = NULL;
7462 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7463 /* Dont register the keywork if the arguments check function are
7464 * not safe during the runtime.
7465 */
7466 if (sc->val_args != NULL)
7467 continue;
7468
7469 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7470 * by an underscore.
7471 */
7472 strncpy(trash.str, sc->kw, trash.size);
7473 trash.str[trash.size - 1] = '\0';
7474 for (p = trash.str; *p; p++)
7475 if (*p == '.' || *p == '-' || *p == '+')
7476 *p = '_';
7477
7478 /* Register the function. */
7479 lua_pushstring(gL.T, trash.str);
7480 lua_pushlightuserdata(gL.T, sc);
7481 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007482 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007483 }
7484
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007485 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007486
7487 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007488 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007489
7490 /*
7491 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007492 * Register class HTTP
7493 *
7494 */
7495
7496 /* Create and fill the metatable. */
7497 lua_newtable(gL.T);
7498
7499 /* Create and fille the __index entry. */
7500 lua_pushstring(gL.T, "__index");
7501 lua_newtable(gL.T);
7502
7503 /* Register Lua functions. */
7504 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7505 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7506 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7507 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7508 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7509 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7510 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7511 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7512 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7513 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7514
7515 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7516 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7517 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7518 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7519 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7520 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007521 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007522
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007523 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007524
7525 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007526 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007527
7528 /*
7529 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007530 * Register class AppletTCP
7531 *
7532 */
7533
7534 /* Create and fill the metatable. */
7535 lua_newtable(gL.T);
7536
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007537 /* Create and fille the __index entry. */
7538 lua_pushstring(gL.T, "__index");
7539 lua_newtable(gL.T);
7540
7541 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01007542 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7543 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7544 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7545 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7546 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007547 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
7548 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
7549 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007550
7551 lua_settable(gL.T, -3);
7552
7553 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007554 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007555
7556 /*
7557 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007558 * Register class AppletHTTP
7559 *
7560 */
7561
7562 /* Create and fill the metatable. */
7563 lua_newtable(gL.T);
7564
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007565 /* Create and fille the __index entry. */
7566 lua_pushstring(gL.T, "__index");
7567 lua_newtable(gL.T);
7568
7569 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007570 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7571 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007572 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
7573 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
7574 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007575 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7576 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7577 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7578 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7579 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7580 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7581
7582 lua_settable(gL.T, -3);
7583
7584 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007585 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007586
7587 /*
7588 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007589 * Register class TXN
7590 *
7591 */
7592
7593 /* Create and fill the metatable. */
7594 lua_newtable(gL.T);
7595
7596 /* Create and fille the __index entry. */
7597 lua_pushstring(gL.T, "__index");
7598 lua_newtable(gL.T);
7599
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007600 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01007601 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7602 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007603 hlua_class_function(gL.T, "set_var", hlua_set_var);
Christopher Faulet85d79c92016-11-09 16:54:56 +01007604 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007605 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007606 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007607 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
7608 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7609 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007610 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7611 hlua_class_function(gL.T, "log", hlua_txn_log);
7612 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7613 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7614 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7615 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007616
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007617 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007618
7619 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007620 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007621
7622 /*
7623 *
7624 * Register class Socket
7625 *
7626 */
7627
7628 /* Create and fill the metatable. */
7629 lua_newtable(gL.T);
7630
7631 /* Create and fille the __index entry. */
7632 lua_pushstring(gL.T, "__index");
7633 lua_newtable(gL.T);
7634
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007635#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007636 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007637#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007638 hlua_class_function(gL.T, "connect", hlua_socket_connect);
7639 hlua_class_function(gL.T, "send", hlua_socket_send);
7640 hlua_class_function(gL.T, "receive", hlua_socket_receive);
7641 hlua_class_function(gL.T, "close", hlua_socket_close);
7642 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
7643 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
7644 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
7645 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
7646
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007647 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007648
7649 /* Register the garbage collector entry. */
7650 lua_pushstring(gL.T, "__gc");
7651 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007652 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007653
7654 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007655 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007656
7657 /* Proxy and server configuration initialisation. */
7658 memset(&socket_proxy, 0, sizeof(socket_proxy));
7659 init_new_proxy(&socket_proxy);
7660 socket_proxy.parent = NULL;
7661 socket_proxy.last_change = now.tv_sec;
7662 socket_proxy.id = "LUA-SOCKET";
7663 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
7664 socket_proxy.maxconn = 0;
7665 socket_proxy.accept = NULL;
7666 socket_proxy.options2 |= PR_O2_INDEPSTR;
7667 socket_proxy.srv = NULL;
7668 socket_proxy.conn_retries = 0;
7669 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
7670
7671 /* Init TCP server: unchanged parameters */
7672 memset(&socket_tcp, 0, sizeof(socket_tcp));
7673 socket_tcp.next = NULL;
7674 socket_tcp.proxy = &socket_proxy;
7675 socket_tcp.obj_type = OBJ_TYPE_SERVER;
7676 LIST_INIT(&socket_tcp.actconns);
7677 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007678 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007679 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007680 LIST_INIT(&socket_tcp.safe_conns);
Emeric Brun52a91d32017-08-31 14:41:55 +02007681 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007682 socket_tcp.last_change = 0;
7683 socket_tcp.id = "LUA-TCP-CONN";
7684 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7685 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7686 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
7687
7688 /* XXX: Copy default parameter from default server,
7689 * but the default server is not initialized.
7690 */
7691 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
7692 socket_tcp.minconn = socket_proxy.defsrv.minconn;
7693 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
7694 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
7695 socket_tcp.onerror = socket_proxy.defsrv.onerror;
7696 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7697 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
7698 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7699 socket_tcp.uweight = socket_proxy.defsrv.iweight;
7700 socket_tcp.iweight = socket_proxy.defsrv.iweight;
7701
7702 socket_tcp.check.status = HCHK_STATUS_INI;
7703 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
7704 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
7705 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
7706 socket_tcp.check.server = &socket_tcp;
7707
7708 socket_tcp.agent.status = HCHK_STATUS_INI;
7709 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
7710 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
7711 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
7712 socket_tcp.agent.server = &socket_tcp;
7713
Willy Tarreaua261e9b2016-12-22 20:44:00 +01007714 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007715
7716#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007717 /* Init TCP server: unchanged parameters */
7718 memset(&socket_ssl, 0, sizeof(socket_ssl));
7719 socket_ssl.next = NULL;
7720 socket_ssl.proxy = &socket_proxy;
7721 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7722 LIST_INIT(&socket_ssl.actconns);
7723 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007724 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007725 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007726 LIST_INIT(&socket_ssl.safe_conns);
Emeric Brun52a91d32017-08-31 14:41:55 +02007727 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007728 socket_ssl.last_change = 0;
7729 socket_ssl.id = "LUA-SSL-CONN";
7730 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7731 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7732 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7733
7734 /* XXX: Copy default parameter from default server,
7735 * but the default server is not initialized.
7736 */
7737 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7738 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7739 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7740 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7741 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7742 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7743 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7744 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7745 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7746 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7747
7748 socket_ssl.check.status = HCHK_STATUS_INI;
7749 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7750 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7751 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7752 socket_ssl.check.server = &socket_ssl;
7753
7754 socket_ssl.agent.status = HCHK_STATUS_INI;
7755 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7756 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7757 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7758 socket_ssl.agent.server = &socket_ssl;
7759
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007760 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01007761 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007762
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007763 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007764 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7765 /*
7766 *
7767 * If the keyword is not known, we can search in the registered
7768 * server keywords. This is usefull to configure special SSL
7769 * features like client certificates and ssl_verify.
7770 *
7771 */
7772 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7773 if (tmp_error != 0) {
7774 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7775 abort(); /* This must be never arrives because the command line
7776 not editable by the user. */
7777 }
7778 idx += kw->skip;
7779 }
7780 }
7781
7782 /* Initialize SSL server. */
Willy Tarreau17d45382016-12-22 21:16:08 +01007783 if (socket_ssl.xprt->prepare_srv)
7784 socket_ssl.xprt->prepare_srv(&socket_ssl);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007785#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01007786
7787 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007788}
Willy Tarreaubb57d942016-12-21 19:04:56 +01007789
7790__attribute__((constructor))
7791static void __hlua_init(void)
7792{
7793 char *ptr = NULL;
7794 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
7795 hap_register_build_opts(ptr, 1);
7796}