blob: 0ca3ec21ee214eaac9347029f8ca799ecc4c3381 [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>
27
William Lallemand9ed62032016-11-21 17:49:11 +010028#include <types/cli.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010029#include <types/hlua.h>
30#include <types/proxy.h>
William Lallemand9ed62032016-11-21 17:49:11 +010031#include <types/stats.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010032
Thierry FOURNIER55da1652015-01-23 11:36:30 +010033#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020034#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010035#include <proto/channel.h>
William Lallemand9ed62032016-11-21 17:49:11 +010036#include <proto/cli.h>
Willy Tarreaua71f6422016-11-16 17:00:14 +010037#include <proto/connection.h>
William Lallemand9ed62032016-11-21 17:49:11 +010038#include <proto/stats.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010039#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010040#include <proto/hlua.h>
Thierry Fournierfb0b5462016-01-21 09:28:58 +010041#include <proto/hlua_fcn.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020042#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010043#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010044#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010045#include <proto/payload.h>
46#include <proto/proto_http.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010047#include <proto/raw_sock.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010048#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/ssl_sock.h>
53#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010054#include <proto/task.h>
Willy Tarreau39713102016-11-25 15:49:32 +010055#include <proto/tcp_rules.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020056#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010057
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010058/* Lua uses longjmp to perform yield or throwing errors. This
59 * macro is used only for identifying the function that can
60 * not return because a longjmp is executed.
61 * __LJMP marks a prototype of hlua file that can use longjmp.
62 * WILL_LJMP() marks an lua function that will use longjmp.
63 * MAY_LJMP() marks an lua function that may use longjmp.
64 */
65#define __LJMP
66#define WILL_LJMP(func) func
67#define MAY_LJMP(func) func
68
Thierry FOURNIERbabae282015-09-17 11:36:37 +020069/* This couple of function executes securely some Lua calls outside of
70 * the lua runtime environment. Each Lua call can return a longjmp
71 * if it encounter a memory error.
72 *
73 * Lua documentation extract:
74 *
75 * If an error happens outside any protected environment, Lua calls
76 * a panic function (see lua_atpanic) and then calls abort, thus
77 * exiting the host application. Your panic function can avoid this
78 * exit by never returning (e.g., doing a long jump to your own
79 * recovery point outside Lua).
80 *
81 * The panic function runs as if it were a message handler (see
82 * §2.3); in particular, the error message is at the top of the
83 * stack. However, there is no guarantee about stack space. To push
84 * anything on the stack, the panic function must first check the
85 * available space (see §4.2).
86 *
87 * We must check all the Lua entry point. This includes:
88 * - The include/proto/hlua.h exported functions
89 * - the task wrapper function
90 * - The action wrapper function
91 * - The converters wrapper function
92 * - The sample-fetch wrapper functions
93 *
94 * It is tolerated that the initilisation function returns an abort.
95 * Before each Lua abort, an error message is writed on stderr.
96 *
97 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
98 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
99 * because they must be exists in the program stack when the longjmp
100 * is called.
101 */
102jmp_buf safe_ljmp_env;
103static int hlua_panic_safe(lua_State *L) { return 0; }
104static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
105
106#define SET_SAFE_LJMP(__L) \
107 ({ \
108 int ret; \
109 if (setjmp(safe_ljmp_env) != 0) { \
110 lua_atpanic(__L, hlua_panic_safe); \
111 ret = 0; \
112 } else { \
113 lua_atpanic(__L, hlua_panic_ljmp); \
114 ret = 1; \
115 } \
116 ret; \
117 })
118
119/* If we are the last function catching Lua errors, we
120 * must reset the panic function.
121 */
122#define RESET_SAFE_LJMP(__L) \
123 do { \
124 lua_atpanic(__L, hlua_panic_safe); \
125 } while(0)
126
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200127/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200128#define APPLET_DONE 0x01 /* applet processing is done. */
129#define APPLET_100C 0x02 /* 100 continue expected. */
130#define APPLET_HDR_SENT 0x04 /* Response header sent. */
131#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
132#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100133#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200134
135#define HTTP_100C "HTTP/1.1 100 Continue\r\n\r\n"
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200136
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100137/* The main Lua execution context. */
138struct hlua gL;
139
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100140/* This is the memory pool containing all the signal structs. These
141 * struct are used to store each requiered signal between two tasks.
142 */
143struct pool_head *pool2_hlua_com;
144
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100145/* Used for Socket connection. */
146static struct proxy socket_proxy;
147static struct server socket_tcp;
148#ifdef USE_OPENSSL
149static struct server socket_ssl;
150#endif
151
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100152/* List head of the function called at the initialisation time. */
153struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
154
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100155/* The following variables contains the reference of the different
156 * Lua classes. These references are useful for identify metadata
157 * associated with an object.
158 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100159static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100160static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100161static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100162static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100163static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100164static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200165static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200166static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200167static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100168
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100169/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200170 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100171 * short timeout. Lua linked with tasks doesn't have a timeout
172 * because a task may remain alive during all the haproxy execution.
173 */
174static unsigned int hlua_timeout_session = 4000; /* session timeout. */
175static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200176static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100177
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100178/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
179 * it is used for preventing infinite loops.
180 *
181 * I test the scheer with an infinite loop containing one incrementation
182 * and one test. I run this loop between 10 seconds, I raise a ceil of
183 * 710M loops from one interrupt each 9000 instructions, so I fix the value
184 * to one interrupt each 10 000 instructions.
185 *
186 * configured | Number of
187 * instructions | loops executed
188 * between two | in milions
189 * forced yields |
190 * ---------------+---------------
191 * 10 | 160
192 * 500 | 670
193 * 1000 | 680
194 * 5000 | 700
195 * 7000 | 700
196 * 8000 | 700
197 * 9000 | 710 <- ceil
198 * 10000 | 710
199 * 100000 | 710
200 * 1000000 | 710
201 *
202 */
203static unsigned int hlua_nb_instruction = 10000;
204
Willy Tarreau32f61e22015-03-18 17:54:59 +0100205/* Descriptor for the memory allocation state. If limit is not null, it will
206 * be enforced on any memory allocation.
207 */
208struct hlua_mem_allocator {
209 size_t allocated;
210 size_t limit;
211};
212
213static struct hlua_mem_allocator hlua_global_allocator;
214
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200215static const char error_500[] =
216 "HTTP/1.0 500 Server Error\r\n"
217 "Cache-Control: no-cache\r\n"
218 "Connection: close\r\n"
219 "Content-Type: text/html\r\n"
220 "\r\n"
221 "<html><body><h1>500 Server Error</h1>\nAn internal server error occured.\n</body></html>\n";
222
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100223/* These functions converts types between HAProxy internal args or
224 * sample and LUA types. Another function permits to check if the
225 * LUA stack contains arguments according with an required ARG_T
226 * format.
227 */
228static int hlua_arg2lua(lua_State *L, const struct arg *arg);
229static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100230__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100231 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100232static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100233static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100234static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
235
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200236__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
237
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200238#define SEND_ERR(__be, __fmt, __args...) \
239 do { \
240 send_log(__be, LOG_ERR, __fmt, ## __args); \
241 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
242 Alert(__fmt, ## __args); \
243 } while (0)
244
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100245/* Used to check an Lua function type in the stack. It creates and
246 * returns a reference of the function. This function throws an
247 * error if the rgument is not a "function".
248 */
249__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
250{
251 if (!lua_isfunction(L, argno)) {
252 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
253 WILL_LJMP(luaL_argerror(L, argno, msg));
254 }
255 lua_pushvalue(L, argno);
256 return luaL_ref(L, LUA_REGISTRYINDEX);
257}
258
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200259/* Return the string that is of the top of the stack. */
260const char *hlua_get_top_error_string(lua_State *L)
261{
262 if (lua_gettop(L) < 1)
263 return "unknown error";
264 if (lua_type(L, -1) != LUA_TSTRING)
265 return "unknown error";
266 return lua_tostring(L, -1);
267}
268
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100269/* This function check the number of arguments available in the
270 * stack. If the number of arguments available is not the same
271 * then <nb> an error is throwed.
272 */
273__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
274{
275 if (lua_gettop(L) == nb)
276 return;
277 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
278}
279
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100280/* This fucntion push an error string prefixed by the file name
281 * and the line number where the error is encountered.
282 */
283static int hlua_pusherror(lua_State *L, const char *fmt, ...)
284{
285 va_list argp;
286 va_start(argp, fmt);
287 luaL_where(L, 1);
288 lua_pushvfstring(L, fmt, argp);
289 va_end(argp);
290 lua_concat(L, 2);
291 return 1;
292}
293
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100294/* This function register a new signal. "lua" is the current lua
295 * execution context. It contains a pointer to the associated task.
296 * "link" is a list head attached to an other task that must be wake
297 * the lua task if an event occurs. This is useful with external
298 * events like TCP I/O or sleep functions. This funcion allocate
299 * memory for the signal.
300 */
301static int hlua_com_new(struct hlua *lua, struct list *link)
302{
303 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
304 if (!com)
305 return 0;
306 LIST_ADDQ(&lua->com, &com->purge_me);
307 LIST_ADDQ(link, &com->wake_me);
308 com->task = lua->task;
309 return 1;
310}
311
312/* This function purge all the pending signals when the LUA execution
313 * is finished. This prevent than a coprocess try to wake a deleted
314 * task. This function remove the memory associated to the signal.
315 */
316static void hlua_com_purge(struct hlua *lua)
317{
318 struct hlua_com *com, *back;
319
320 /* Delete all pending communication signals. */
321 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
322 LIST_DEL(&com->purge_me);
323 LIST_DEL(&com->wake_me);
324 pool_free2(pool2_hlua_com, com);
325 }
326}
327
328/* This function sends signals. It wakes all the tasks attached
329 * to a list head, and remove the signal, and free the used
330 * memory.
331 */
332static void hlua_com_wake(struct list *wake)
333{
334 struct hlua_com *com, *back;
335
336 /* Wake task and delete all pending communication signals. */
337 list_for_each_entry_safe(com, back, wake, wake_me) {
338 LIST_DEL(&com->purge_me);
339 LIST_DEL(&com->wake_me);
340 task_wakeup(com->task, TASK_WOKEN_MSG);
341 pool_free2(pool2_hlua_com, com);
342 }
343}
344
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100345/* This functions is used with sample fetch and converters. It
346 * converts the HAProxy configuration argument in a lua stack
347 * values.
348 *
349 * It takes an array of "arg", and each entry of the array is
350 * converted and pushed in the LUA stack.
351 */
352static int hlua_arg2lua(lua_State *L, const struct arg *arg)
353{
354 switch (arg->type) {
355 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100356 case ARGT_TIME:
357 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100358 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100359 break;
360
361 case ARGT_STR:
362 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
363 break;
364
365 case ARGT_IPV4:
366 case ARGT_IPV6:
367 case ARGT_MSK4:
368 case ARGT_MSK6:
369 case ARGT_FE:
370 case ARGT_BE:
371 case ARGT_TAB:
372 case ARGT_SRV:
373 case ARGT_USR:
374 case ARGT_MAP:
375 default:
376 lua_pushnil(L);
377 break;
378 }
379 return 1;
380}
381
382/* This function take one entrie in an LUA stack at the index "ud",
383 * and try to convert it in an HAProxy argument entry. This is useful
384 * with sample fetch wrappers. The input arguments are gived to the
385 * lua wrapper and converted as arg list by thi function.
386 */
387static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
388{
389 switch (lua_type(L, ud)) {
390
391 case LUA_TNUMBER:
392 case LUA_TBOOLEAN:
393 arg->type = ARGT_SINT;
394 arg->data.sint = lua_tointeger(L, ud);
395 break;
396
397 case LUA_TSTRING:
398 arg->type = ARGT_STR;
399 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
400 break;
401
402 case LUA_TUSERDATA:
403 case LUA_TNIL:
404 case LUA_TTABLE:
405 case LUA_TFUNCTION:
406 case LUA_TTHREAD:
407 case LUA_TLIGHTUSERDATA:
408 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200409 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100410 break;
411 }
412 return 1;
413}
414
415/* the following functions are used to convert a struct sample
416 * in Lua type. This useful to convert the return of the
417 * fetchs or converters.
418 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100419static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100420{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200421 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100422 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100423 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200424 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100425 break;
426
427 case SMP_T_BIN:
428 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200429 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100430 break;
431
432 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200433 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100434 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
435 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
436 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
437 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
438 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
439 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
440 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
441 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
442 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200443 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100444 break;
445 default:
446 lua_pushnil(L);
447 break;
448 }
449 break;
450
451 case SMP_T_IPV4:
452 case SMP_T_IPV6:
453 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200454 if (sample_casts[smp->data.type][SMP_T_STR] &&
455 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200456 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100457 else
458 lua_pushnil(L);
459 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100460 default:
461 lua_pushnil(L);
462 break;
463 }
464 return 1;
465}
466
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100467/* the following functions are used to convert a struct sample
468 * in Lua strings. This is useful to convert the return of the
469 * fetchs or converters.
470 */
471static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
472{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200473 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100474
475 case SMP_T_BIN:
476 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200477 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100478 break;
479
480 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200481 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100482 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
483 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
484 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
485 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
486 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
487 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
488 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
489 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
490 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200491 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100492 break;
493 default:
494 lua_pushstring(L, "");
495 break;
496 }
497 break;
498
499 case SMP_T_SINT:
500 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100501 case SMP_T_IPV4:
502 case SMP_T_IPV6:
503 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200504 if (sample_casts[smp->data.type][SMP_T_STR] &&
505 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200506 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100507 else
508 lua_pushstring(L, "");
509 break;
510 default:
511 lua_pushstring(L, "");
512 break;
513 }
514 return 1;
515}
516
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100517/* the following functions are used to convert an Lua type in a
518 * struct sample. This is useful to provide data from a converter
519 * to the LUA code.
520 */
521static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
522{
523 switch (lua_type(L, ud)) {
524
525 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200526 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200527 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100528 break;
529
530
531 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200532 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200533 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100534 break;
535
536 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200537 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100538 smp->flags |= SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200539 smp->data.u.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100540 break;
541
542 case LUA_TUSERDATA:
543 case LUA_TNIL:
544 case LUA_TTABLE:
545 case LUA_TFUNCTION:
546 case LUA_TTHREAD:
547 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200548 case LUA_TNONE:
549 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200550 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200551 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100552 break;
553 }
554 return 1;
555}
556
557/* This function check the "argp" builded by another conversion function
558 * is in accord with the expected argp defined by the "mask". The fucntion
559 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100560 *
561 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
562 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100563 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100564__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100565 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100566{
567 int min_arg;
568 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100569 struct proxy *px;
570 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100571
572 idx = 0;
573 min_arg = ARGM(mask);
574 mask >>= ARGM_BITS;
575
576 while (1) {
577
578 /* Check oversize. */
579 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100580 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100581 }
582
583 /* Check for mandatory arguments. */
584 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100585 if (idx < min_arg) {
586
587 /* If miss other argument than the first one, we return an error. */
588 if (idx > 0)
589 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
590
591 /* If first argument have a certain type, some default values
592 * may be used. See the function smp_resolve_args().
593 */
594 switch (mask & ARGT_MASK) {
595
596 case ARGT_FE:
597 if (!(p->cap & PR_CAP_FE))
598 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
599 argp[idx].data.prx = p;
600 argp[idx].type = ARGT_FE;
601 argp[idx+1].type = ARGT_STOP;
602 break;
603
604 case ARGT_BE:
605 if (!(p->cap & PR_CAP_BE))
606 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
607 argp[idx].data.prx = p;
608 argp[idx].type = ARGT_BE;
609 argp[idx+1].type = ARGT_STOP;
610 break;
611
612 case ARGT_TAB:
613 argp[idx].data.prx = p;
614 argp[idx].type = ARGT_TAB;
615 argp[idx+1].type = ARGT_STOP;
616 break;
617
618 default:
619 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
620 break;
621 }
622 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100623 return 0;
624 }
625
626 /* Check for exceed the number of requiered argument. */
627 if ((mask & ARGT_MASK) == ARGT_STOP &&
628 argp[idx].type != ARGT_STOP) {
629 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
630 }
631
632 if ((mask & ARGT_MASK) == ARGT_STOP &&
633 argp[idx].type == ARGT_STOP) {
634 return 0;
635 }
636
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100637 /* Convert some argument types. */
638 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100639 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100640 if (argp[idx].type != ARGT_SINT)
641 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
642 argp[idx].type = ARGT_SINT;
643 break;
644
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100645 case ARGT_TIME:
646 if (argp[idx].type != ARGT_SINT)
647 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200648 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100649 break;
650
651 case ARGT_SIZE:
652 if (argp[idx].type != ARGT_SINT)
653 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200654 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100655 break;
656
657 case ARGT_FE:
658 if (argp[idx].type != ARGT_STR)
659 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
660 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
661 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200662 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100663 if (!argp[idx].data.prx)
664 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
665 argp[idx].type = ARGT_FE;
666 break;
667
668 case ARGT_BE:
669 if (argp[idx].type != ARGT_STR)
670 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
671 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
672 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200673 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100674 if (!argp[idx].data.prx)
675 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
676 argp[idx].type = ARGT_BE;
677 break;
678
679 case ARGT_TAB:
680 if (argp[idx].type != ARGT_STR)
681 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
682 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
683 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200684 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100685 if (!argp[idx].data.prx)
686 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
687 argp[idx].type = ARGT_TAB;
688 break;
689
690 case ARGT_SRV:
691 if (argp[idx].type != ARGT_STR)
692 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
693 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
694 trash.str[argp[idx].data.str.len] = 0;
695 sname = strrchr(trash.str, '/');
696 if (sname) {
697 *sname++ = '\0';
698 pname = trash.str;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200699 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100700 if (!px)
701 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
702 }
703 else {
704 sname = trash.str;
705 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100706 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100707 argp[idx].data.srv = findserver(px, sname);
708 if (!argp[idx].data.srv)
709 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
710 argp[idx].type = ARGT_SRV;
711 break;
712
713 case ARGT_IPV4:
714 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
715 trash.str[argp[idx].data.str.len] = 0;
716 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
717 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
718 argp[idx].type = ARGT_IPV4;
719 break;
720
721 case ARGT_MSK4:
722 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
723 trash.str[argp[idx].data.str.len] = 0;
724 if (!str2mask(trash.str, &argp[idx].data.ipv4))
725 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
726 argp[idx].type = ARGT_MSK4;
727 break;
728
729 case ARGT_IPV6:
730 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
731 trash.str[argp[idx].data.str.len] = 0;
732 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
733 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
734 argp[idx].type = ARGT_IPV6;
735 break;
736
737 case ARGT_MSK6:
738 case ARGT_MAP:
739 case ARGT_REG:
740 case ARGT_USR:
741 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100742 break;
743 }
744
745 /* Check for type of argument. */
746 if ((mask & ARGT_MASK) != argp[idx].type) {
747 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
748 arg_type_names[(mask & ARGT_MASK)],
749 arg_type_names[argp[idx].type & ARGT_MASK]);
750 WILL_LJMP(luaL_argerror(L, first + idx, msg));
751 }
752
753 /* Next argument. */
754 mask >>= ARGT_BITS;
755 idx++;
756 }
757}
758
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100759/*
760 * The following functions are used to make correspondance between the the
761 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100762 *
763 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100764 * - hlua_sethlua : create the association between hlua context and lua_state.
765 */
766static inline struct hlua *hlua_gethlua(lua_State *L)
767{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100768 struct hlua **hlua = lua_getextraspace(L);
769 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100770}
771static inline void hlua_sethlua(struct hlua *hlua)
772{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100773 struct hlua **hlua_store = lua_getextraspace(hlua->T);
774 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100775}
776
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100777/* This function is used to send logs. It try to send on screen (stderr)
778 * and on the default syslog server.
779 */
780static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
781{
782 struct tm tm;
783 char *p;
784
785 /* Cleanup the log message. */
786 p = trash.str;
787 for (; *msg != '\0'; msg++, p++) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200788 if (p >= trash.str + trash.size - 1) {
789 /* Break the message if exceed the buffer size. */
790 *(p-4) = ' ';
791 *(p-3) = '.';
792 *(p-2) = '.';
793 *(p-1) = '.';
794 break;
795 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100796 if (isprint(*msg))
797 *p = *msg;
798 else
799 *p = '.';
800 }
801 *p = '\0';
802
Thierry FOURNIER5554e292015-09-09 11:21:37 +0200803 send_log(px, level, "%s\n", trash.str);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100804 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200805 get_localtime(date.tv_sec, &tm);
806 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100807 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
808 (int)getpid(), trash.str);
809 fflush(stderr);
810 }
811}
812
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100813/* This function just ensure that the yield will be always
814 * returned with a timeout and permit to set some flags
815 */
816__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100817 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100818{
819 struct hlua *hlua = hlua_gethlua(L);
820
821 /* Set the wake timeout. If timeout is required, we set
822 * the expiration time.
823 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200824 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100825
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100826 hlua->flags |= flags;
827
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100828 /* Process the yield. */
829 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
830}
831
Willy Tarreau87b09662015-04-03 00:22:06 +0200832/* This function initialises the Lua environment stored in the stream.
833 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100834 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200835 *
836 * This function is particular. it initialises a new Lua thread. If the
837 * initialisation fails (example: out of memory error), the lua function
838 * throws an error (longjmp).
839 *
840 * This function manipulates two Lua stack: the main and the thread. Only
841 * the main stack can fail. The thread is not manipulated. This function
842 * MUST NOT manipulate the created thread stack state, because is not
843 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100844 */
845int hlua_ctx_init(struct hlua *lua, struct task *task)
846{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200847 if (!SET_SAFE_LJMP(gL.T)) {
848 lua->Tref = LUA_REFNIL;
849 return 0;
850 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100851 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100852 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100853 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100854 lua->T = lua_newthread(gL.T);
855 if (!lua->T) {
856 lua->Tref = LUA_REFNIL;
857 return 0;
858 }
859 hlua_sethlua(lua);
860 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
861 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200862 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100863 return 1;
864}
865
Willy Tarreau87b09662015-04-03 00:22:06 +0200866/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100867 * is destroyed. The destroy also the memory context. The struct "lua"
868 * is not freed.
869 */
870void hlua_ctx_destroy(struct hlua *lua)
871{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100872 if (!lua->T)
873 return;
874
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100875 /* Purge all the pending signals. */
876 hlua_com_purge(lua);
877
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100878 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
879 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200880
881 /* Forces a garbage collecting process. If the Lua program is finished
882 * without error, we run the GC on the thread pointer. Its freed all
883 * the unused memory.
884 * If the thread is finnish with an error or is currently yielded,
885 * it seems that the GC applied on the thread doesn't clean anything,
886 * so e run the GC on the main thread.
887 * NOTE: maybe this action locks all the Lua threads untiml the en of
888 * the garbage collection.
889 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200890 if (lua->flags & HLUA_MUST_GC) {
891 lua_gc(lua->T, LUA_GCCOLLECT, 0);
892 if (lua_status(lua->T) != LUA_OK)
893 lua_gc(gL.T, LUA_GCCOLLECT, 0);
894 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200895
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200896 lua->T = NULL;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100897}
898
899/* This function is used to restore the Lua context when a coroutine
900 * fails. This function copy the common memory between old coroutine
901 * and the new coroutine. The old coroutine is destroyed, and its
902 * replaced by the new coroutine.
903 * If the flag "keep_msg" is set, the last entry of the old is assumed
904 * as string error message and it is copied in the new stack.
905 */
906static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
907{
908 lua_State *T;
909 int new_ref;
910
911 /* Renew the main LUA stack doesn't have sense. */
912 if (lua == &gL)
913 return 0;
914
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100915 /* New Lua coroutine. */
916 T = lua_newthread(gL.T);
917 if (!T)
918 return 0;
919
920 /* Copy last error message. */
921 if (keep_msg)
922 lua_xmove(lua->T, T, 1);
923
924 /* Copy data between the coroutines. */
925 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
926 lua_xmove(lua->T, T, 1);
927 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
928
929 /* Destroy old data. */
930 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
931
932 /* The thread is garbage collected by Lua. */
933 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
934
935 /* Fill the struct with the new coroutine values. */
936 lua->Mref = new_ref;
937 lua->T = T;
938 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
939
940 /* Set context. */
941 hlua_sethlua(lua);
942
943 return 1;
944}
945
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100946void hlua_hook(lua_State *L, lua_Debug *ar)
947{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100948 struct hlua *hlua = hlua_gethlua(L);
949
950 /* Lua cannot yield when its returning from a function,
951 * so, we can fix the interrupt hook to 1 instruction,
952 * expecting that the function is finnished.
953 */
954 if (lua_gethookmask(L) & LUA_MASKRET) {
955 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
956 return;
957 }
958
959 /* restore the interrupt condition. */
960 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
961
962 /* If we interrupt the Lua processing in yieldable state, we yield.
963 * If the state is not yieldable, trying yield causes an error.
964 */
965 if (lua_isyieldable(L))
966 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
967
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +0100968 /* If we cannot yield, update the clock and check the timeout. */
969 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200970 hlua->run_time += now_ms - hlua->start_time;
971 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100972 lua_pushfstring(L, "execution timeout");
973 WILL_LJMP(lua_error(L));
974 }
975
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200976 /* Update the start time. */
977 hlua->start_time = now_ms;
978
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100979 /* Try to interrupt the process at the end of the current
980 * unyieldable function.
981 */
982 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100983}
984
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100985/* This function start or resumes the Lua stack execution. If the flag
986 * "yield_allowed" if no set and the LUA stack execution returns a yield
987 * The function return an error.
988 *
989 * The function can returns 4 values:
990 * - HLUA_E_OK : The execution is terminated without any errors.
991 * - HLUA_E_AGAIN : The execution must continue at the next associated
992 * task wakeup.
993 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
994 * the top of the stack.
995 * - HLUA_E_ERR : An error has occured without error message.
996 *
997 * If an error occured, the stack is renewed and it is ready to run new
998 * LUA code.
999 */
1000static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1001{
1002 int ret;
1003 const char *msg;
1004
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001005 /* Initialise run time counter. */
1006 if (!HLUA_IS_RUNNING(lua))
1007 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001008
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001009resume_execution:
1010
1011 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1012 * instructions. it is used for preventing infinite loops.
1013 */
1014 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1015
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001016 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001017 HLUA_SET_RUN(lua);
1018 HLUA_CLR_CTRLYIELD(lua);
1019 HLUA_CLR_WAKERESWR(lua);
1020 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001021
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001022 /* Update the start time. */
1023 lua->start_time = now_ms;
1024
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001025 /* Call the function. */
1026 ret = lua_resume(lua->T, gL.T, lua->nargs);
1027 switch (ret) {
1028
1029 case LUA_OK:
1030 ret = HLUA_E_OK;
1031 break;
1032
1033 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001034 /* Check if the execution timeout is expired. It it is the case, we
1035 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001036 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001037 tv_update_date(0, 1);
1038 lua->run_time += now_ms - lua->start_time;
1039 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001040 lua_settop(lua->T, 0); /* Empty the stack. */
1041 if (!lua_checkstack(lua->T, 1)) {
1042 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001043 break;
1044 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001045 lua_pushfstring(lua->T, "execution timeout");
1046 ret = HLUA_E_ERRMSG;
1047 break;
1048 }
1049 /* Process the forced yield. if the general yield is not allowed or
1050 * if no task were associated this the current Lua execution
1051 * coroutine, we resume the execution. Else we want to return in the
1052 * scheduler and we want to be waked up again, to continue the
1053 * current Lua execution. So we schedule our own task.
1054 */
1055 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001056 if (!yield_allowed || !lua->task)
1057 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001058 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001059 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001060 if (!yield_allowed) {
1061 lua_settop(lua->T, 0); /* Empty the stack. */
1062 if (!lua_checkstack(lua->T, 1)) {
1063 ret = HLUA_E_ERR;
1064 break;
1065 }
1066 lua_pushfstring(lua->T, "yield not allowed");
1067 ret = HLUA_E_ERRMSG;
1068 break;
1069 }
1070 ret = HLUA_E_AGAIN;
1071 break;
1072
1073 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001074
1075 /* Special exit case. The traditionnal exit is returned as an error
1076 * because the errors ares the only one mean to return immediately
1077 * from and lua execution.
1078 */
1079 if (lua->flags & HLUA_EXIT) {
1080 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001081 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001082 break;
1083 }
1084
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001085 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001086 if (!lua_checkstack(lua->T, 1)) {
1087 ret = HLUA_E_ERR;
1088 break;
1089 }
1090 msg = lua_tostring(lua->T, -1);
1091 lua_settop(lua->T, 0); /* Empty the stack. */
1092 lua_pop(lua->T, 1);
1093 if (msg)
1094 lua_pushfstring(lua->T, "runtime error: %s", msg);
1095 else
1096 lua_pushfstring(lua->T, "unknown runtime error");
1097 ret = HLUA_E_ERRMSG;
1098 break;
1099
1100 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001101 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001102 lua_settop(lua->T, 0); /* Empty the stack. */
1103 if (!lua_checkstack(lua->T, 1)) {
1104 ret = HLUA_E_ERR;
1105 break;
1106 }
1107 lua_pushfstring(lua->T, "out of memory error");
1108 ret = HLUA_E_ERRMSG;
1109 break;
1110
1111 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001112 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001113 if (!lua_checkstack(lua->T, 1)) {
1114 ret = HLUA_E_ERR;
1115 break;
1116 }
1117 msg = lua_tostring(lua->T, -1);
1118 lua_settop(lua->T, 0); /* Empty the stack. */
1119 lua_pop(lua->T, 1);
1120 if (msg)
1121 lua_pushfstring(lua->T, "message handler error: %s", msg);
1122 else
1123 lua_pushfstring(lua->T, "message handler error");
1124 ret = HLUA_E_ERRMSG;
1125 break;
1126
1127 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001128 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001129 lua_settop(lua->T, 0); /* Empty the stack. */
1130 if (!lua_checkstack(lua->T, 1)) {
1131 ret = HLUA_E_ERR;
1132 break;
1133 }
1134 lua_pushfstring(lua->T, "unknonwn error");
1135 ret = HLUA_E_ERRMSG;
1136 break;
1137 }
1138
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001139 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001140 if (lua->flags & HLUA_MUST_GC &&
1141 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001142 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1143
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001144 switch (ret) {
1145 case HLUA_E_AGAIN:
1146 break;
1147
1148 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001149 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001150 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001151 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001152 break;
1153
1154 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001155 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001156 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001157 hlua_ctx_renew(lua, 0);
1158 break;
1159
1160 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001161 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001162 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001163 break;
1164 }
1165
1166 return ret;
1167}
1168
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001169/* This function exit the current code. */
1170__LJMP static int hlua_done(lua_State *L)
1171{
1172 struct hlua *hlua = hlua_gethlua(L);
1173
1174 hlua->flags |= HLUA_EXIT;
1175 WILL_LJMP(lua_error(L));
1176
1177 return 0;
1178}
1179
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001180/* This function is an LUA binding. It provides a function
1181 * for deleting ACL from a referenced ACL file.
1182 */
1183__LJMP static int hlua_del_acl(lua_State *L)
1184{
1185 const char *name;
1186 const char *key;
1187 struct pat_ref *ref;
1188
1189 MAY_LJMP(check_args(L, 2, "del_acl"));
1190
1191 name = MAY_LJMP(luaL_checkstring(L, 1));
1192 key = MAY_LJMP(luaL_checkstring(L, 2));
1193
1194 ref = pat_ref_lookup(name);
1195 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001196 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001197
1198 pat_ref_delete(ref, key);
1199 return 0;
1200}
1201
1202/* This function is an LUA binding. It provides a function
1203 * for deleting map entry from a referenced map file.
1204 */
1205static int hlua_del_map(lua_State *L)
1206{
1207 const char *name;
1208 const char *key;
1209 struct pat_ref *ref;
1210
1211 MAY_LJMP(check_args(L, 2, "del_map"));
1212
1213 name = MAY_LJMP(luaL_checkstring(L, 1));
1214 key = MAY_LJMP(luaL_checkstring(L, 2));
1215
1216 ref = pat_ref_lookup(name);
1217 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001218 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001219
1220 pat_ref_delete(ref, key);
1221 return 0;
1222}
1223
1224/* This function is an LUA binding. It provides a function
1225 * for adding ACL pattern from a referenced ACL file.
1226 */
1227static int hlua_add_acl(lua_State *L)
1228{
1229 const char *name;
1230 const char *key;
1231 struct pat_ref *ref;
1232
1233 MAY_LJMP(check_args(L, 2, "add_acl"));
1234
1235 name = MAY_LJMP(luaL_checkstring(L, 1));
1236 key = MAY_LJMP(luaL_checkstring(L, 2));
1237
1238 ref = pat_ref_lookup(name);
1239 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001240 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001241
1242 if (pat_ref_find_elt(ref, key) == NULL)
1243 pat_ref_add(ref, key, NULL, NULL);
1244 return 0;
1245}
1246
1247/* This function is an LUA binding. It provides a function
1248 * for setting map pattern and sample from a referenced map
1249 * file.
1250 */
1251static int hlua_set_map(lua_State *L)
1252{
1253 const char *name;
1254 const char *key;
1255 const char *value;
1256 struct pat_ref *ref;
1257
1258 MAY_LJMP(check_args(L, 3, "set_map"));
1259
1260 name = MAY_LJMP(luaL_checkstring(L, 1));
1261 key = MAY_LJMP(luaL_checkstring(L, 2));
1262 value = MAY_LJMP(luaL_checkstring(L, 3));
1263
1264 ref = pat_ref_lookup(name);
1265 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001266 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001267
1268 if (pat_ref_find_elt(ref, key) != NULL)
1269 pat_ref_set(ref, key, value, NULL);
1270 else
1271 pat_ref_add(ref, key, value, NULL);
1272 return 0;
1273}
1274
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001275/* A class is a lot of memory that contain data. This data can be a table,
1276 * an integer or user data. This data is associated with a metatable. This
1277 * metatable have an original version registred in the global context with
1278 * the name of the object (_G[<name>] = <metable> ).
1279 *
1280 * A metable is a table that modify the standard behavior of a standard
1281 * access to the associated data. The entries of this new metatable are
1282 * defined as is:
1283 *
1284 * http://lua-users.org/wiki/MetatableEvents
1285 *
1286 * __index
1287 *
1288 * we access an absent field in a table, the result is nil. This is
1289 * true, but it is not the whole truth. Actually, such access triggers
1290 * the interpreter to look for an __index metamethod: If there is no
1291 * such method, as usually happens, then the access results in nil;
1292 * otherwise, the metamethod will provide the result.
1293 *
1294 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1295 * the key does not appear in the table, but the metatable has an __index
1296 * property:
1297 *
1298 * - if the value is a function, the function is called, passing in the
1299 * table and the key; the return value of that function is returned as
1300 * the result.
1301 *
1302 * - if the value is another table, the value of the key in that table is
1303 * asked for and returned (and if it doesn't exist in that table, but that
1304 * table's metatable has an __index property, then it continues on up)
1305 *
1306 * - Use "rawget(myTable,key)" to skip this metamethod.
1307 *
1308 * http://www.lua.org/pil/13.4.1.html
1309 *
1310 * __newindex
1311 *
1312 * Like __index, but control property assignment.
1313 *
1314 * __mode - Control weak references. A string value with one or both
1315 * of the characters 'k' and 'v' which specifies that the the
1316 * keys and/or values in the table are weak references.
1317 *
1318 * __call - Treat a table like a function. When a table is followed by
1319 * parenthesis such as "myTable( 'foo' )" and the metatable has
1320 * a __call key pointing to a function, that function is invoked
1321 * (passing any specified arguments) and the return value is
1322 * returned.
1323 *
1324 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1325 * called, if the metatable for myTable has a __metatable
1326 * key, the value of that key is returned instead of the
1327 * actual metatable.
1328 *
1329 * __tostring - Control string representation. When the builtin
1330 * "tostring( myTable )" function is called, if the metatable
1331 * for myTable has a __tostring property set to a function,
1332 * that function is invoked (passing myTable to it) and the
1333 * return value is used as the string representation.
1334 *
1335 * __len - Control table length. When the table length is requested using
1336 * the length operator ( '#' ), if the metatable for myTable has
1337 * a __len key pointing to a function, that function is invoked
1338 * (passing myTable to it) and the return value used as the value
1339 * of "#myTable".
1340 *
1341 * __gc - Userdata finalizer code. When userdata is set to be garbage
1342 * collected, if the metatable has a __gc field pointing to a
1343 * function, that function is first invoked, passing the userdata
1344 * to it. The __gc metamethod is not called for tables.
1345 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1346 *
1347 * Special metamethods for redefining standard operators:
1348 * http://www.lua.org/pil/13.1.html
1349 *
1350 * __add "+"
1351 * __sub "-"
1352 * __mul "*"
1353 * __div "/"
1354 * __unm "!"
1355 * __pow "^"
1356 * __concat ".."
1357 *
1358 * Special methods for redfining standar relations
1359 * http://www.lua.org/pil/13.2.html
1360 *
1361 * __eq "=="
1362 * __lt "<"
1363 * __le "<="
1364 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001365
1366/*
1367 *
1368 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001369 * Class Map
1370 *
1371 *
1372 */
1373
1374/* Returns a struct hlua_map if the stack entry "ud" is
1375 * a class session, otherwise it throws an error.
1376 */
1377__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1378{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001379 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001380}
1381
1382/* This function is the map constructor. It don't need
1383 * the class Map object. It creates and return a new Map
1384 * object. It must be called only during "body" or "init"
1385 * context because it process some filesystem accesses.
1386 */
1387__LJMP static int hlua_map_new(struct lua_State *L)
1388{
1389 const char *fn;
1390 int match = PAT_MATCH_STR;
1391 struct sample_conv conv;
1392 const char *file = "";
1393 int line = 0;
1394 lua_Debug ar;
1395 char *err = NULL;
1396 struct arg args[2];
1397
1398 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1399 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1400
1401 fn = MAY_LJMP(luaL_checkstring(L, 1));
1402
1403 if (lua_gettop(L) >= 2) {
1404 match = MAY_LJMP(luaL_checkinteger(L, 2));
1405 if (match < 0 || match >= PAT_MATCH_NUM)
1406 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1407 }
1408
1409 /* Get Lua filename and line number. */
1410 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1411 lua_getinfo(L, "Sl", &ar); /* get info about it */
1412 if (ar.currentline > 0) { /* is there info? */
1413 file = ar.short_src;
1414 line = ar.currentline;
1415 }
1416 }
1417
1418 /* fill fake sample_conv struct. */
1419 conv.kw = ""; /* unused. */
1420 conv.process = NULL; /* unused. */
1421 conv.arg_mask = 0; /* unused. */
1422 conv.val_args = NULL; /* unused. */
1423 conv.out_type = SMP_T_STR;
1424 conv.private = (void *)(long)match;
1425 switch (match) {
1426 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1427 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1428 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1429 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1430 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1431 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1432 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001433 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001434 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1435 default:
1436 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1437 }
1438
1439 /* fill fake args. */
1440 args[0].type = ARGT_STR;
1441 args[0].data.str.str = (char *)fn;
1442 args[1].type = ARGT_STOP;
1443
1444 /* load the map. */
1445 if (!sample_load_map(args, &conv, file, line, &err)) {
1446 /* error case: we cant use luaL_error because we must
1447 * free the err variable.
1448 */
1449 luaL_where(L, 1);
1450 lua_pushfstring(L, "'new': %s.", err);
1451 lua_concat(L, 2);
1452 free(err);
1453 WILL_LJMP(lua_error(L));
1454 }
1455
1456 /* create the lua object. */
1457 lua_newtable(L);
1458 lua_pushlightuserdata(L, args[0].data.map);
1459 lua_rawseti(L, -2, 0);
1460
1461 /* Pop a class Map metatable and affect it to the userdata. */
1462 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1463 lua_setmetatable(L, -2);
1464
1465
1466 return 1;
1467}
1468
1469__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1470{
1471 struct map_descriptor *desc;
1472 struct pattern *pat;
1473 struct sample smp;
1474
1475 MAY_LJMP(check_args(L, 2, "lookup"));
1476 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001477 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001478 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001479 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001480 }
1481 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001482 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001483 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001484 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 +02001485 }
1486
1487 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001488 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001489 if (str)
1490 lua_pushstring(L, "");
1491 else
1492 lua_pushnil(L);
1493 return 1;
1494 }
1495
1496 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001497 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001498 return 1;
1499}
1500
1501__LJMP static int hlua_map_lookup(struct lua_State *L)
1502{
1503 return _hlua_map_lookup(L, 0);
1504}
1505
1506__LJMP static int hlua_map_slookup(struct lua_State *L)
1507{
1508 return _hlua_map_lookup(L, 1);
1509}
1510
1511/*
1512 *
1513 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001514 * Class Socket
1515 *
1516 *
1517 */
1518
1519__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1520{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001521 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001522}
1523
1524/* This function is the handler called for each I/O on the established
1525 * connection. It is used for notify space avalaible to send or data
1526 * received.
1527 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001528static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001529{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001530 struct stream_interface *si = appctx->owner;
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001531 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001532
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001533 /* If the connection object is not avalaible, close all the
1534 * streams and wakeup everithing waiting for.
1535 */
1536 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001537 si_shutw(si);
1538 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001539 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001540 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1541 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001542 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001543 }
1544
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001545 /* If we cant write, wakeup the pending write signals. */
1546 if (channel_output_closed(si_ic(si)))
1547 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1548
1549 /* If we cant read, wakeup the pending read signals. */
1550 if (channel_input_closed(si_oc(si)))
1551 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1552
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001553 /* if the connection is not estabkished, inform the stream that we want
1554 * to be notified whenever the connection completes.
1555 */
1556 if (!(c->flags & CO_FL_CONNECTED)) {
1557 si_applet_cant_get(si);
1558 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001559 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001560 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001561
1562 /* This function is called after the connect. */
1563 appctx->ctx.hlua.connected = 1;
1564
1565 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001566 if (channel_may_recv(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001567 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1568
1569 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001570 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001571 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1572}
1573
Willy Tarreau87b09662015-04-03 00:22:06 +02001574/* This function is called when the "struct stream" is destroyed.
1575 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001576 * Wake all the pending signals.
1577 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001578static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001579{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001580 /* Remove my link in the original object. */
1581 if (appctx->ctx.hlua.socket)
1582 appctx->ctx.hlua.socket->s = NULL;
1583
1584 /* Wake all the task waiting for me. */
1585 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1586 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1587}
1588
1589/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001590 * uses this object. If the stream does not exists, just quit.
1591 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001592 * pending signal can rest in the read and write lists. destroy
1593 * it.
1594 */
1595__LJMP static int hlua_socket_gc(lua_State *L)
1596{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001597 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001598 struct appctx *appctx;
1599
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001600 MAY_LJMP(check_args(L, 1, "__gc"));
1601
1602 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001603 if (!socket->s)
1604 return 0;
1605
Willy Tarreau87b09662015-04-03 00:22:06 +02001606 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001607 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaue7dff022015-04-03 01:14:29 +02001608 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001609 socket->s = NULL;
1610 appctx->ctx.hlua.socket = NULL;
1611
1612 return 0;
1613}
1614
1615/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001616 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001617 */
1618__LJMP static int hlua_socket_close(lua_State *L)
1619{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001620 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001621 struct appctx *appctx;
1622
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001623 MAY_LJMP(check_args(L, 1, "close"));
1624
1625 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001626 if (!socket->s)
1627 return 0;
1628
Willy Tarreau87b09662015-04-03 00:22:06 +02001629 /* Close the stream and remove the associated stop task. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02001630 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001631 appctx = objt_appctx(socket->s->si[0].end);
1632 appctx->ctx.hlua.socket = NULL;
1633 socket->s = NULL;
1634
1635 return 0;
1636}
1637
1638/* This Lua function assumes that the stack contain three parameters.
1639 * 1 - USERDATA containing a struct socket
1640 * 2 - INTEGER with values of the macro defined below
1641 * If the integer is -1, we must read at most one line.
1642 * If the integer is -2, we ust read all the data until the
1643 * end of the stream.
1644 * If the integer is positive value, we must read a number of
1645 * bytes corresponding to this value.
1646 */
1647#define HLSR_READ_LINE (-1)
1648#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001649__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001650{
1651 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1652 int wanted = lua_tointeger(L, 2);
1653 struct hlua *hlua = hlua_gethlua(L);
1654 struct appctx *appctx;
1655 int len;
1656 int nblk;
1657 char *blk1;
1658 int len1;
1659 char *blk2;
1660 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001661 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001662 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001663
1664 /* Check if this lua stack is schedulable. */
1665 if (!hlua || !hlua->task)
1666 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1667 "'frontend', 'backend' or 'task'"));
1668
1669 /* check for connection closed. If some data where read, return it. */
1670 if (!socket->s)
1671 goto connection_closed;
1672
Willy Tarreau94aa6172015-03-13 14:19:06 +01001673 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001674 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001675 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001676 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001677 if (nblk < 0) /* Connection close. */
1678 goto connection_closed;
1679 if (nblk == 0) /* No data avalaible. */
1680 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001681
1682 /* remove final \r\n. */
1683 if (nblk == 1) {
1684 if (blk1[len1-1] == '\n') {
1685 len1--;
1686 skip_at_end++;
1687 if (blk1[len1-1] == '\r') {
1688 len1--;
1689 skip_at_end++;
1690 }
1691 }
1692 }
1693 else {
1694 if (blk2[len2-1] == '\n') {
1695 len2--;
1696 skip_at_end++;
1697 if (blk2[len2-1] == '\r') {
1698 len2--;
1699 skip_at_end++;
1700 }
1701 }
1702 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001703 }
1704
1705 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001706 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001707 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001708 if (nblk < 0) /* Connection close. */
1709 goto connection_closed;
1710 if (nblk == 0) /* No data avalaible. */
1711 goto connection_empty;
1712 }
1713
1714 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001715 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001716 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001717 if (nblk < 0) /* Connection close. */
1718 goto connection_closed;
1719 if (nblk == 0) /* No data avalaible. */
1720 goto connection_empty;
1721
1722 if (len1 > wanted) {
1723 nblk = 1;
1724 len1 = wanted;
1725 } if (nblk == 2 && len1 + len2 > wanted)
1726 len2 = wanted - len1;
1727 }
1728
1729 len = len1;
1730
1731 luaL_addlstring(&socket->b, blk1, len1);
1732 if (nblk == 2) {
1733 len += len2;
1734 luaL_addlstring(&socket->b, blk2, len2);
1735 }
1736
1737 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001738 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001739
1740 /* Don't wait anything. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001741 stream_int_notify(&socket->s->si[0]);
1742 stream_int_update_applet(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001743
1744 /* If the pattern reclaim to read all the data
1745 * in the connection, got out.
1746 */
1747 if (wanted == HLSR_READ_ALL)
1748 goto connection_empty;
1749 else if (wanted >= 0 && len < wanted)
1750 goto connection_empty;
1751
1752 /* Return result. */
1753 luaL_pushresult(&socket->b);
1754 return 1;
1755
1756connection_closed:
1757
1758 /* If the buffer containds data. */
1759 if (socket->b.n > 0) {
1760 luaL_pushresult(&socket->b);
1761 return 1;
1762 }
1763 lua_pushnil(L);
1764 lua_pushstring(L, "connection closed.");
1765 return 2;
1766
1767connection_empty:
1768
1769 appctx = objt_appctx(socket->s->si[0].end);
1770 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1771 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001772 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001773 return 0;
1774}
1775
1776/* This Lus function gets two parameters. The first one can be string
1777 * or a number. If the string is "*l", the user require one line. If
1778 * the string is "*a", the user require all the content of the stream.
1779 * If the value is a number, the user require a number of bytes equal
1780 * to the value. The default value is "*l" (a line).
1781 *
1782 * This paraeter with a variable type is converted in integer. This
1783 * integer takes this values:
1784 * -1 : read a line
1785 * -2 : read all the stream
1786 * >0 : amount if bytes.
1787 *
1788 * The second parameter is optinal. It contains a string that must be
1789 * concatenated with the read data.
1790 */
1791__LJMP static int hlua_socket_receive(struct lua_State *L)
1792{
1793 int wanted = HLSR_READ_LINE;
1794 const char *pattern;
1795 int type;
1796 char *error;
1797 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001798 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001799
1800 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1801 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1802
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001803 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001804
1805 /* check for pattern. */
1806 if (lua_gettop(L) >= 2) {
1807 type = lua_type(L, 2);
1808 if (type == LUA_TSTRING) {
1809 pattern = lua_tostring(L, 2);
1810 if (strcmp(pattern, "*a") == 0)
1811 wanted = HLSR_READ_ALL;
1812 else if (strcmp(pattern, "*l") == 0)
1813 wanted = HLSR_READ_LINE;
1814 else {
1815 wanted = strtoll(pattern, &error, 10);
1816 if (*error != '\0')
1817 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1818 }
1819 }
1820 else if (type == LUA_TNUMBER) {
1821 wanted = lua_tointeger(L, 2);
1822 if (wanted < 0)
1823 WILL_LJMP(luaL_error(L, "Unsupported size."));
1824 }
1825 }
1826
1827 /* Set pattern. */
1828 lua_pushinteger(L, wanted);
1829 lua_replace(L, 2);
1830
1831 /* init bufffer, and fiil it wih prefix. */
1832 luaL_buffinit(L, &socket->b);
1833
1834 /* Check prefix. */
1835 if (lua_gettop(L) >= 3) {
1836 if (lua_type(L, 3) != LUA_TSTRING)
1837 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1838 pattern = lua_tolstring(L, 3, &len);
1839 luaL_addlstring(&socket->b, pattern, len);
1840 }
1841
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001842 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001843}
1844
1845/* Write the Lua input string in the output buffer.
1846 * This fucntion returns a yield if no space are available.
1847 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001848static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001849{
1850 struct hlua_socket *socket;
1851 struct hlua *hlua = hlua_gethlua(L);
1852 struct appctx *appctx;
1853 size_t buf_len;
1854 const char *buf;
1855 int len;
1856 int send_len;
1857 int sent;
1858
1859 /* Check if this lua stack is schedulable. */
1860 if (!hlua || !hlua->task)
1861 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1862 "'frontend', 'backend' or 'task'"));
1863
1864 /* Get object */
1865 socket = MAY_LJMP(hlua_checksocket(L, 1));
1866 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001867 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001868
1869 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001870 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001871 lua_pushinteger(L, -1);
1872 return 1;
1873 }
1874
1875 /* Update the input buffer data. */
1876 buf += sent;
1877 send_len = buf_len - sent;
1878
1879 /* All the data are sent. */
1880 if (sent >= buf_len)
1881 return 1; /* Implicitly return the length sent. */
1882
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001883 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1884 * the request buffer if its not required.
1885 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001886 if (socket->s->req.buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02001887 if (!stream_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001888 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001889 goto hlua_socket_write_yield_return;
1890 }
1891 }
1892
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001893 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001894 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001895 if (len <= 0)
1896 goto hlua_socket_write_yield_return;
1897
1898 /* send data */
1899 if (len < send_len)
1900 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001901 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001902
1903 /* "Not enough space" (-1), "Buffer too little to contain
1904 * the data" (-2) are not expected because the available length
1905 * is tested.
1906 * Other unknown error are also not expected.
1907 */
1908 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001909 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001910 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001911
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001912 MAY_LJMP(hlua_socket_close(L));
1913 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001914 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001915 return 1;
1916 }
1917
1918 /* update buffers. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001919 stream_int_notify(&socket->s->si[0]);
1920 stream_int_update_applet(&socket->s->si[0]);
1921
Willy Tarreau94aa6172015-03-13 14:19:06 +01001922 socket->s->req.rex = TICK_ETERNITY;
1923 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001924
1925 /* Update length sent. */
1926 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001927 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001928
1929 /* All the data buffer is sent ? */
1930 if (sent + len >= buf_len)
1931 return 1;
1932
1933hlua_socket_write_yield_return:
1934 appctx = objt_appctx(socket->s->si[0].end);
1935 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1936 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001937 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001938 return 0;
1939}
1940
1941/* This function initiate the send of data. It just check the input
1942 * parameters and push an integer in the Lua stack that contain the
1943 * amount of data writed in the buffer. This is used by the function
1944 * "hlua_socket_write_yield" that can yield.
1945 *
1946 * The Lua function gets between 3 and 4 parameters. The first one is
1947 * the associated object. The second is a string buffer. The third is
1948 * a facultative integer that represents where is the buffer position
1949 * of the start of the data that can send. The first byte is the
1950 * position "1". The default value is "1". The fourth argument is a
1951 * facultative integer that represents where is the buffer position
1952 * of the end of the data that can send. The default is the last byte.
1953 */
1954static int hlua_socket_send(struct lua_State *L)
1955{
1956 int i;
1957 int j;
1958 const char *buf;
1959 size_t buf_len;
1960
1961 /* Check number of arguments. */
1962 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1963 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1964
1965 /* Get the string. */
1966 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1967
1968 /* Get and check j. */
1969 if (lua_gettop(L) == 4) {
1970 j = MAY_LJMP(luaL_checkinteger(L, 4));
1971 if (j < 0)
1972 j = buf_len + j + 1;
1973 if (j > buf_len)
1974 j = buf_len + 1;
1975 lua_pop(L, 1);
1976 }
1977 else
1978 j = buf_len;
1979
1980 /* Get and check i. */
1981 if (lua_gettop(L) == 3) {
1982 i = MAY_LJMP(luaL_checkinteger(L, 3));
1983 if (i < 0)
1984 i = buf_len + i + 1;
1985 if (i > buf_len)
1986 i = buf_len + 1;
1987 lua_pop(L, 1);
1988 } else
1989 i = 1;
1990
1991 /* Check bth i and j. */
1992 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001993 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001994 return 1;
1995 }
1996 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001997 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001998 return 1;
1999 }
2000 if (i == 0)
2001 i = 1;
2002 if (j == 0)
2003 j = 1;
2004
2005 /* Pop the string. */
2006 lua_pop(L, 1);
2007
2008 /* Update the buffer length. */
2009 buf += i - 1;
2010 buf_len = j - i + 1;
2011 lua_pushlstring(L, buf, buf_len);
2012
2013 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002014 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002015
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002016 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002017}
2018
Willy Tarreau22b0a682015-06-17 19:43:49 +02002019#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002020__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2021{
2022 static char buffer[SOCKET_INFO_MAX_LEN];
2023 int ret;
2024 int len;
2025 char *p;
2026
2027 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2028 if (ret <= 0) {
2029 lua_pushnil(L);
2030 return 1;
2031 }
2032
2033 if (ret == AF_UNIX) {
2034 lua_pushstring(L, buffer+1);
2035 return 1;
2036 }
2037 else if (ret == AF_INET6) {
2038 buffer[0] = '[';
2039 len = strlen(buffer);
2040 buffer[len] = ']';
2041 len++;
2042 buffer[len] = ':';
2043 len++;
2044 p = buffer;
2045 }
2046 else if (ret == AF_INET) {
2047 p = buffer + 1;
2048 len = strlen(p);
2049 p[len] = ':';
2050 len++;
2051 }
2052 else {
2053 lua_pushnil(L);
2054 return 1;
2055 }
2056
2057 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2058 lua_pushnil(L);
2059 return 1;
2060 }
2061
2062 lua_pushstring(L, p);
2063 return 1;
2064}
2065
2066/* Returns information about the peer of the connection. */
2067__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2068{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002069 struct hlua_socket *socket;
2070 struct connection *conn;
2071
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002072 MAY_LJMP(check_args(L, 1, "getpeername"));
2073
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002074 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002075
2076 /* Check if the tcp object is avalaible. */
2077 if (!socket->s) {
2078 lua_pushnil(L);
2079 return 1;
2080 }
2081
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002082 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002083 if (!conn) {
2084 lua_pushnil(L);
2085 return 1;
2086 }
2087
Willy Tarreaua71f6422016-11-16 17:00:14 +01002088 conn_get_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002089 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
Willy Tarreaua71f6422016-11-16 17:00:14 +01002090 lua_pushnil(L);
2091 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002092 }
2093
2094 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2095}
2096
2097/* Returns information about my connection side. */
2098static int hlua_socket_getsockname(struct lua_State *L)
2099{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002100 struct hlua_socket *socket;
2101 struct connection *conn;
2102
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002103 MAY_LJMP(check_args(L, 1, "getsockname"));
2104
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002105 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002106
2107 /* Check if the tcp object is avalaible. */
2108 if (!socket->s) {
2109 lua_pushnil(L);
2110 return 1;
2111 }
2112
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002113 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002114 if (!conn) {
2115 lua_pushnil(L);
2116 return 1;
2117 }
2118
Willy Tarreaua71f6422016-11-16 17:00:14 +01002119 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002120 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Willy Tarreaua71f6422016-11-16 17:00:14 +01002121 lua_pushnil(L);
2122 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002123 }
2124
2125 return hlua_socket_info(L, &conn->addr.from);
2126}
2127
2128/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002129static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002130 .obj_type = OBJ_TYPE_APPLET,
2131 .name = "<LUA_TCP>",
2132 .fct = hlua_socket_handler,
2133 .release = hlua_socket_release,
2134};
2135
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002136__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002137{
2138 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2139 struct hlua *hlua = hlua_gethlua(L);
2140 struct appctx *appctx;
2141
2142 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002143 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002144 lua_pushnil(L);
2145 lua_pushstring(L, "Can't connect");
2146 return 2;
2147 }
2148
2149 appctx = objt_appctx(socket->s->si[0].end);
2150
2151 /* Check for connection established. */
2152 if (appctx->ctx.hlua.connected) {
2153 lua_pushinteger(L, 1);
2154 return 1;
2155 }
2156
2157 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2158 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002159 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002160 return 0;
2161}
2162
2163/* This function fail or initite the connection. */
2164__LJMP static int hlua_socket_connect(struct lua_State *L)
2165{
2166 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002167 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002168 const char *ip;
2169 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002170 struct hlua *hlua;
2171 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002172 int low, high;
2173 struct sockaddr_storage *addr;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002174
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002175 if (lua_gettop(L) < 2)
2176 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002177
2178 /* Get args. */
2179 socket = MAY_LJMP(hlua_checksocket(L, 1));
2180 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002181 if (lua_gettop(L) >= 3)
2182 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002183
Willy Tarreau973a5422015-08-05 21:47:23 +02002184 conn = si_alloc_conn(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002185 if (!conn)
2186 WILL_LJMP(luaL_error(L, "connect: internal error"));
2187
Willy Tarreau3adac082015-09-26 17:51:09 +02002188 /* needed for the connection not to be closed */
2189 conn->target = socket->s->target;
2190
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002191 /* Parse ip address. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002192 addr = str2sa_range(ip, &low, &high, NULL, NULL, NULL, 0);
2193 if (!addr)
2194 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
2195 if (low != high)
2196 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
2197 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002198
2199 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002200 if (low == 0) {
2201 if (conn->addr.to.ss_family == AF_INET) {
2202 if (port == -1)
2203 WILL_LJMP(luaL_error(L, "connect: port missing"));
2204 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2205 } else if (conn->addr.to.ss_family == AF_INET6) {
2206 if (port == -1)
2207 WILL_LJMP(luaL_error(L, "connect: port missing"));
2208 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2209 }
2210 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002211
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002212 hlua = hlua_gethlua(L);
2213 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002214
2215 /* inform the stream that we want to be notified whenever the
2216 * connection completes.
2217 */
2218 si_applet_cant_get(&socket->s->si[0]);
2219 si_applet_cant_put(&socket->s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002220 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002221
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002222 hlua->flags |= HLUA_MUST_GC;
2223
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002224 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2225 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002226 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002227
2228 return 0;
2229}
2230
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002231#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002232__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2233{
2234 struct hlua_socket *socket;
2235
2236 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2237 socket = MAY_LJMP(hlua_checksocket(L, 1));
2238 socket->s->target = &socket_ssl.obj_type;
2239 return MAY_LJMP(hlua_socket_connect(L));
2240}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002241#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002242
2243__LJMP static int hlua_socket_setoption(struct lua_State *L)
2244{
2245 return 0;
2246}
2247
2248__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2249{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002250 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002251 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002252
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002253 MAY_LJMP(check_args(L, 2, "settimeout"));
2254
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002255 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002256 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002257
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002258 socket->s->req.rto = tmout;
2259 socket->s->req.wto = tmout;
2260 socket->s->res.rto = tmout;
2261 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002262
2263 return 0;
2264}
2265
2266__LJMP static int hlua_socket_new(lua_State *L)
2267{
2268 struct hlua_socket *socket;
2269 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002270 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002271 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002272 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002273
2274 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002275 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002276 hlua_pusherror(L, "socket: full stack");
2277 goto out_fail_conf;
2278 }
2279
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002280 /* Create the object: obj[0] = userdata. */
2281 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002282 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002283 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002284 memset(socket, 0, sizeof(*socket));
2285
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002286 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002287 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002288 hlua_pusherror(L, "socket: uninitialized pools.");
2289 goto out_fail_conf;
2290 }
2291
Willy Tarreau87b09662015-04-03 00:22:06 +02002292 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002293 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2294 lua_setmetatable(L, -2);
2295
Willy Tarreaud420a972015-04-06 00:39:18 +02002296 /* Create the applet context */
2297 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002298 if (!appctx) {
2299 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002300 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002301 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002302
Willy Tarreaud420a972015-04-06 00:39:18 +02002303 appctx->ctx.hlua.socket = socket;
2304 appctx->ctx.hlua.connected = 0;
2305 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2306 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002307
Willy Tarreaud420a972015-04-06 00:39:18 +02002308 /* Now create a session, task and stream for this applet */
2309 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2310 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002311 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002312 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002313 }
2314
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002315 task = task_new();
2316 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002317 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002318 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002319 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002320 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002321
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002322 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002323 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002324 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002325 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002326 }
2327
Willy Tarreaud420a972015-04-06 00:39:18 +02002328 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002329 socket->s = strm;
2330 strm->hlua.T = NULL;
2331 strm->hlua.Tref = LUA_REFNIL;
2332 strm->hlua.Mref = LUA_REFNIL;
2333 strm->hlua.nargs = 0;
2334 strm->hlua.flags = 0;
2335 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002336
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002337 /* Configure "right" stream interface. this "si" is used to connect
2338 * and retrieve data from the server. The connection is initialized
2339 * with the "struct server".
2340 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002341 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002342
2343 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002344 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2345 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002346
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002347 /* Update statistics counters. */
2348 socket_proxy.feconn++; /* beconn will be increased later */
2349 jobs++;
2350 totalconn++;
2351
2352 /* Return yield waiting for connection. */
2353 return 1;
2354
Willy Tarreaud420a972015-04-06 00:39:18 +02002355 out_fail_stream:
2356 task_free(task);
2357 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002358 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002359 out_fail_sess:
2360 appctx_free(appctx);
2361 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002362 WILL_LJMP(lua_error(L));
2363 return 0;
2364}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002365
2366/*
2367 *
2368 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002369 * Class Channel
2370 *
2371 *
2372 */
2373
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002374/* The state between the channel data and the HTTP parser state can be
2375 * unconsistent, so reset the parser and call it again. Warning, this
2376 * action not revalidate the request and not send a 400 if the modified
2377 * resuest is not valid.
2378 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002379 * This function never fails. The direction is set using dir, which equals
2380 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002381 */
2382static void hlua_resynchonize_proto(struct stream *stream, int dir)
2383{
2384 /* Protocol HTTP. */
2385 if (stream->be->mode == PR_MODE_HTTP) {
2386
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002387 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002388 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002389 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002390 http_txn_reset_res(stream->txn);
2391
2392 if (stream->txn->hdr_idx.v)
2393 hdr_idx_init(&stream->txn->hdr_idx);
2394
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002395 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002396 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002397 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002398 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2399 }
2400}
2401
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002402/* Check the protocole integrity after the Lua manipulations. Close the stream
2403 * and returns 0 if fails, otherwise returns 1. The direction is set using dir,
2404 * which equals either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002405 */
2406static int hlua_check_proto(struct stream *stream, int dir)
2407{
2408 const struct chunk msg = { .len = 0 };
2409
Willy Tarreau9af89f72015-09-26 11:50:08 +02002410 /* Protocol HTTP. The message parsing state must match the request or
2411 * response state. The problem that may happen is that Lua modifies
2412 * the request or response message *after* it was parsed, and corrupted
2413 * it so that it could not be processed anymore. We just need to verify
2414 * if the parser is still expected to run or not.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002415 */
2416 if (stream->be->mode == PR_MODE_HTTP) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002417 if (dir == SMP_OPT_DIR_REQ &&
Willy Tarreau9af89f72015-09-26 11:50:08 +02002418 !(stream->req.analysers & AN_REQ_WAIT_HTTP) &&
Thierry FOURNIER / OZON.IO8dc73162016-11-18 19:06:21 +01002419 stream->txn->req.msg_state < HTTP_MSG_ERROR) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002420 stream_int_retnclose(&stream->si[0], &msg);
2421 return 0;
2422 }
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002423 else if (dir == SMP_OPT_DIR_RES &&
Willy Tarreau9af89f72015-09-26 11:50:08 +02002424 !(stream->res.analysers & AN_RES_WAIT_HTTP) &&
Thierry FOURNIER / OZON.IO8dc73162016-11-18 19:06:21 +01002425 stream->txn->rsp.msg_state < HTTP_MSG_ERROR) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002426 stream_int_retnclose(&stream->si[0], &msg);
2427 return 0;
2428 }
2429 }
2430 return 1;
2431}
2432
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002433/* Returns the struct hlua_channel join to the class channel in the
2434 * stack entry "ud" or throws an argument error.
2435 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002436__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002437{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002438 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002439}
2440
Willy Tarreau47860ed2015-03-10 14:07:50 +01002441/* Pushes the channel onto the top of the stack. If the stask does not have a
2442 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002443 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002444static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002445{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002446 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002447 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002448 return 0;
2449
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002450 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002451 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002452 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002453
2454 /* Pop a class sesison metatable and affect it to the userdata. */
2455 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2456 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002457 return 1;
2458}
2459
2460/* Duplicate all the data present in the input channel and put it
2461 * in a string LUA variables. Returns -1 and push a nil value in
2462 * the stack if the channel is closed and all the data are consumed,
2463 * returns 0 if no data are available, otherwise it returns the length
2464 * of the builded string.
2465 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002466static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002467{
2468 char *blk1;
2469 char *blk2;
2470 int len1;
2471 int len2;
2472 int ret;
2473 luaL_Buffer b;
2474
Willy Tarreau47860ed2015-03-10 14:07:50 +01002475 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002476 if (unlikely(ret == 0))
2477 return 0;
2478
2479 if (unlikely(ret < 0)) {
2480 lua_pushnil(L);
2481 return -1;
2482 }
2483
2484 luaL_buffinit(L, &b);
2485 luaL_addlstring(&b, blk1, len1);
2486 if (unlikely(ret == 2))
2487 luaL_addlstring(&b, blk2, len2);
2488 luaL_pushresult(&b);
2489
2490 if (unlikely(ret == 2))
2491 return len1 + len2;
2492 return len1;
2493}
2494
2495/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2496 * a yield. This function keep the data in the buffer.
2497 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002498__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002499{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002500 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002501
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002502 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2503
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002504 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002505 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002506 return 1;
2507}
2508
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002509/* Check arguments for the function "hlua_channel_dup_yield". */
2510__LJMP static int hlua_channel_dup(lua_State *L)
2511{
2512 MAY_LJMP(check_args(L, 1, "dup"));
2513 MAY_LJMP(hlua_checkchannel(L, 1));
2514 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2515}
2516
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002517/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2518 * a yield. This function consumes the data in the buffer. It returns
2519 * a string containing the data or a nil pointer if no data are available
2520 * and the channel is closed.
2521 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002522__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002523{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002524 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002525 int ret;
2526
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002527 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002528
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002529 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002530 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002531 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002532
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002533 if (unlikely(ret == -1))
2534 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002535
Willy Tarreau47860ed2015-03-10 14:07:50 +01002536 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002537 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002538 return 1;
2539}
2540
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002541/* Check arguments for the fucntion "hlua_channel_get_yield". */
2542__LJMP static int hlua_channel_get(lua_State *L)
2543{
2544 MAY_LJMP(check_args(L, 1, "get"));
2545 MAY_LJMP(hlua_checkchannel(L, 1));
2546 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2547}
2548
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002549/* This functions consumes and returns one line. If the channel is closed,
2550 * and the last data does not contains a final '\n', the data are returned
2551 * without the final '\n'. When no more data are avalaible, it returns nil
2552 * value.
2553 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002554__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002555{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002556 char *blk1;
2557 char *blk2;
2558 int len1;
2559 int len2;
2560 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002561 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002562 int ret;
2563 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002564
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002565 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2566
Willy Tarreau47860ed2015-03-10 14:07:50 +01002567 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002568 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002569 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002570
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002571 if (ret == -1) {
2572 lua_pushnil(L);
2573 return 1;
2574 }
2575
2576 luaL_buffinit(L, &b);
2577 luaL_addlstring(&b, blk1, len1);
2578 len = len1;
2579 if (unlikely(ret == 2)) {
2580 luaL_addlstring(&b, blk2, len2);
2581 len += len2;
2582 }
2583 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002584 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002585 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002586 return 1;
2587}
2588
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002589/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2590__LJMP static int hlua_channel_getline(lua_State *L)
2591{
2592 MAY_LJMP(check_args(L, 1, "getline"));
2593 MAY_LJMP(hlua_checkchannel(L, 1));
2594 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2595}
2596
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002597/* This function takes a string as input, and append it at the
2598 * input side of channel. If the data is too big, but a space
2599 * is probably available after sending some data, the function
2600 * yield. If the data is bigger than the buffer, or if the
2601 * channel is closed, it returns -1. otherwise, it returns the
2602 * amount of data writed.
2603 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002604__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002605{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002606 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002607 size_t len;
2608 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2609 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2610 int ret;
2611 int max;
2612
Willy Tarreau47860ed2015-03-10 14:07:50 +01002613 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002614 if (max > len - l)
2615 max = len - l;
2616
Willy Tarreau47860ed2015-03-10 14:07:50 +01002617 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002618 if (ret == -2 || ret == -3) {
2619 lua_pushinteger(L, -1);
2620 return 1;
2621 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002622 if (ret == -1) {
2623 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002624 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002625 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002626 l += ret;
2627 lua_pop(L, 1);
2628 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002629 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002630
Willy Tarreau47860ed2015-03-10 14:07:50 +01002631 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2632 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002633 /* There are no space avalaible, and the output buffer is empty.
2634 * in this case, we cannot add more data, so we cannot yield,
2635 * we return the amount of copyied data.
2636 */
2637 return 1;
2638 }
2639 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002640 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002641 return 1;
2642}
2643
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002644/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002645 * of the writed string, or -1 if the channel is closed or if the
2646 * buffer size is too little for the data.
2647 */
2648__LJMP static int hlua_channel_append(lua_State *L)
2649{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002650 size_t len;
2651
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002652 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002653 MAY_LJMP(hlua_checkchannel(L, 1));
2654 MAY_LJMP(luaL_checklstring(L, 2, &len));
2655 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002656 lua_pushinteger(L, 0);
2657
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002658 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002659}
2660
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002661/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002662 * his process by cleaning the buffer. The result is a replacement
2663 * of the current data. It returns the length of the writed string,
2664 * or -1 if the channel is closed or if the buffer size is too
2665 * little for the data.
2666 */
2667__LJMP static int hlua_channel_set(lua_State *L)
2668{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002669 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002670
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002671 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002672 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002673 lua_pushinteger(L, 0);
2674
Willy Tarreau47860ed2015-03-10 14:07:50 +01002675 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002676
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002677 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002678}
2679
2680/* Append data in the output side of the buffer. This data is immediatly
2681 * sent. The fcuntion returns the ammount of data writed. If the buffer
2682 * cannot contains the data, the function yield. The function returns -1
2683 * if the channel is closed.
2684 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002685__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002686{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002687 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002688 size_t len;
2689 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2690 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2691 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002692 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002693
Willy Tarreau47860ed2015-03-10 14:07:50 +01002694 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002695 lua_pushinteger(L, -1);
2696 return 1;
2697 }
2698
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002699 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2700 * the request buffer if its not required.
2701 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002702 if (chn->buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02002703 if (!stream_alloc_recv_buffer(chn)) {
Willy Tarreau47860ed2015-03-10 14:07:50 +01002704 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002705 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002706 }
2707 }
2708
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002709 /* the writed data will be immediatly sent, so we can check
2710 * the avalaible space without taking in account the reserve.
2711 * The reserve is guaranted for the processing of incoming
2712 * data, because the buffer will be flushed.
2713 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002714 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002715
2716 /* If there are no space avalaible, and the output buffer is empty.
2717 * in this case, we cannot add more data, so we cannot yield,
2718 * we return the amount of copyied data.
2719 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002720 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002721 return 1;
2722
2723 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002724 if (max > len - l)
2725 max = len - l;
2726
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002727 /* The buffer avalaible size may be not contiguous. This test
2728 * detects a non contiguous buffer and realign it.
2729 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002730 if (bi_space_for_replace(chn->buf) < max)
2731 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002732
2733 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002734 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002735
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002736 /* buffer replace considers that the input part is filled.
2737 * so, I must forward these new data in the output part.
2738 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002739 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002740
2741 l += max;
2742 lua_pop(L, 1);
2743 lua_pushinteger(L, l);
2744
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002745 /* If there are no space avalaible, and the output buffer is empty.
2746 * in this case, we cannot add more data, so we cannot yield,
2747 * we return the amount of copyied data.
2748 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002749 max = chn->buf->size - buffer_len(chn->buf);
2750 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002751 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002752
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002753 if (l < len) {
2754 /* If we are waiting for space in the response buffer, we
2755 * must set the flag WAKERESWR. This flag required the task
2756 * wake up if any activity is detected on the response buffer.
2757 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002758 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002759 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002760 else
2761 HLUA_SET_WAKEREQWR(hlua);
2762 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002763 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002764
2765 return 1;
2766}
2767
2768/* Just a wraper of "_hlua_channel_send". This wrapper permits
2769 * yield the LUA process, and resume it without checking the
2770 * input arguments.
2771 */
2772__LJMP static int hlua_channel_send(lua_State *L)
2773{
2774 MAY_LJMP(check_args(L, 2, "send"));
2775 lua_pushinteger(L, 0);
2776
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002777 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002778}
2779
2780/* This function forward and amount of butes. The data pass from
2781 * the input side of the buffer to the output side, and can be
2782 * forwarded. This function never fails.
2783 *
2784 * The Lua function takes an amount of bytes to be forwarded in
2785 * imput. It returns the number of bytes forwarded.
2786 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002787__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002788{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002789 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002790 int len;
2791 int l;
2792 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002793 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002794
2795 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2796 len = MAY_LJMP(luaL_checkinteger(L, 2));
2797 l = MAY_LJMP(luaL_checkinteger(L, -1));
2798
2799 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002800 if (max > chn->buf->i)
2801 max = chn->buf->i;
2802 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002803 l += max;
2804
2805 lua_pop(L, 1);
2806 lua_pushinteger(L, l);
2807
2808 /* Check if it miss bytes to forward. */
2809 if (l < len) {
2810 /* The the input channel or the output channel are closed, we
2811 * must return the amount of data forwarded.
2812 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002813 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002814 return 1;
2815
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002816 /* If we are waiting for space data in the response buffer, we
2817 * must set the flag WAKERESWR. This flag required the task
2818 * wake up if any activity is detected on the response buffer.
2819 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002820 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002821 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002822 else
2823 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002824
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002825 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002826 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002827 }
2828
2829 return 1;
2830}
2831
2832/* Just check the input and prepare the stack for the previous
2833 * function "hlua_channel_forward_yield"
2834 */
2835__LJMP static int hlua_channel_forward(lua_State *L)
2836{
2837 MAY_LJMP(check_args(L, 2, "forward"));
2838 MAY_LJMP(hlua_checkchannel(L, 1));
2839 MAY_LJMP(luaL_checkinteger(L, 2));
2840
2841 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002842 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002843}
2844
2845/* Just returns the number of bytes available in the input
2846 * side of the buffer. This function never fails.
2847 */
2848__LJMP static int hlua_channel_get_in_len(lua_State *L)
2849{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002850 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002851
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002852 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002853 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002854 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002855 return 1;
2856}
2857
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01002858/* Returns true if the channel is full. */
2859__LJMP static int hlua_channel_is_full(lua_State *L)
2860{
2861 struct channel *chn;
2862 int rem;
2863
2864 MAY_LJMP(check_args(L, 1, "is_full"));
2865 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2866
2867 rem = chn->buf->size;
2868 rem -= chn->buf->o; /* Output size */
2869 rem -= chn->buf->i; /* Input size */
2870 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
2871
2872 lua_pushboolean(L, rem <= 0);
2873 return 1;
2874}
2875
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002876/* Just returns the number of bytes available in the output
2877 * side of the buffer. This function never fails.
2878 */
2879__LJMP static int hlua_channel_get_out_len(lua_State *L)
2880{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002881 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002882
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002883 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002884 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002885 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002886 return 1;
2887}
2888
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002889/*
2890 *
2891 *
2892 * Class Fetches
2893 *
2894 *
2895 */
2896
2897/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002898 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002899 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002900__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002901{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002902 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002903}
2904
2905/* This function creates and push in the stack a fetch object according
2906 * with a current TXN.
2907 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002908static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002909{
Willy Tarreau7073c472015-04-06 11:15:40 +02002910 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002911
2912 /* Check stack size. */
2913 if (!lua_checkstack(L, 3))
2914 return 0;
2915
2916 /* Create the object: obj[0] = userdata.
2917 * Note that the base of the Fetches object is the
2918 * transaction object.
2919 */
2920 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002921 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002922 lua_rawseti(L, -2, 0);
2923
Willy Tarreau7073c472015-04-06 11:15:40 +02002924 hsmp->s = txn->s;
2925 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01002926 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002927 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002928
2929 /* Pop a class sesison metatable and affect it to the userdata. */
2930 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2931 lua_setmetatable(L, -2);
2932
2933 return 1;
2934}
2935
2936/* This function is an LUA binding. It is called with each sample-fetch.
2937 * It uses closure argument to store the associated sample-fetch. It
2938 * returns only one argument or throws an error. An error is thrown
2939 * only if an error is encountered during the argument parsing. If
2940 * the "sample-fetch" function fails, nil is returned.
2941 */
2942__LJMP static int hlua_run_sample_fetch(lua_State *L)
2943{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002944 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002945 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002946 struct arg args[ARGM_NBARGS + 1];
2947 int i;
2948 struct sample smp;
2949
2950 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002951 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002952
2953 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002954 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002955
Thierry FOURNIERca988662015-12-20 18:43:03 +01002956 /* Check execution authorization. */
2957 if (f->use & SMP_USE_HTTP_ANY &&
2958 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
2959 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
2960 "is not available in Lua services", f->kw);
2961 WILL_LJMP(lua_error(L));
2962 }
2963
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002964 /* Get extra arguments. */
2965 for (i = 0; i < lua_gettop(L) - 1; i++) {
2966 if (i >= ARGM_NBARGS)
2967 break;
2968 hlua_lua2arg(L, i + 2, &args[i]);
2969 }
2970 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01002971 args[i].data.str.str = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002972
2973 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002974 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002975
2976 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002977 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002978 lua_pushfstring(L, "error in arguments");
2979 WILL_LJMP(lua_error(L));
2980 }
2981
2982 /* Initialise the sample. */
2983 memset(&smp, 0, sizeof(smp));
2984
2985 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01002986 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02002987 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002988 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002989 lua_pushstring(L, "");
2990 else
2991 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002992 return 1;
2993 }
2994
2995 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002996 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002997 hlua_smp2lua_str(L, &smp);
2998 else
2999 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003000 return 1;
3001}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003002
3003/*
3004 *
3005 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003006 * Class Converters
3007 *
3008 *
3009 */
3010
3011/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003012 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003013 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003014__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003015{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003016 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003017}
3018
3019/* This function creates and push in the stack a Converters object
3020 * according with a current TXN.
3021 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003022static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003023{
Willy Tarreau7073c472015-04-06 11:15:40 +02003024 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003025
3026 /* Check stack size. */
3027 if (!lua_checkstack(L, 3))
3028 return 0;
3029
3030 /* Create the object: obj[0] = userdata.
3031 * Note that the base of the Converters object is the
3032 * same than the TXN object.
3033 */
3034 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003035 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003036 lua_rawseti(L, -2, 0);
3037
Willy Tarreau7073c472015-04-06 11:15:40 +02003038 hsmp->s = txn->s;
3039 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003040 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003041 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003042
Willy Tarreau87b09662015-04-03 00:22:06 +02003043 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003044 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3045 lua_setmetatable(L, -2);
3046
3047 return 1;
3048}
3049
3050/* This function is an LUA binding. It is called with each converter.
3051 * It uses closure argument to store the associated converter. It
3052 * returns only one argument or throws an error. An error is thrown
3053 * only if an error is encountered during the argument parsing. If
3054 * the converter function function fails, nil is returned.
3055 */
3056__LJMP static int hlua_run_sample_conv(lua_State *L)
3057{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003058 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003059 struct sample_conv *conv;
3060 struct arg args[ARGM_NBARGS + 1];
3061 int i;
3062 struct sample smp;
3063
3064 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003065 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003066
3067 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003068 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003069
3070 /* Get extra arguments. */
3071 for (i = 0; i < lua_gettop(L) - 2; i++) {
3072 if (i >= ARGM_NBARGS)
3073 break;
3074 hlua_lua2arg(L, i + 3, &args[i]);
3075 }
3076 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003077 args[i].data.str.str = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003078
3079 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003080 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003081
3082 /* Run the special args checker. */
3083 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3084 hlua_pusherror(L, "error in arguments");
3085 WILL_LJMP(lua_error(L));
3086 }
3087
3088 /* Initialise the sample. */
3089 if (!hlua_lua2smp(L, 2, &smp)) {
3090 hlua_pusherror(L, "error in the input argument");
3091 WILL_LJMP(lua_error(L));
3092 }
3093
Willy Tarreau1777ea62016-03-10 16:15:46 +01003094 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3095
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003096 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003097 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003098 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003099 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003100 WILL_LJMP(lua_error(L));
3101 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003102 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3103 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003104 hlua_pusherror(L, "error during the input argument casting");
3105 WILL_LJMP(lua_error(L));
3106 }
3107
3108 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003109 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003110 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003111 lua_pushstring(L, "");
3112 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003113 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003114 return 1;
3115 }
3116
3117 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003118 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003119 hlua_smp2lua_str(L, &smp);
3120 else
3121 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003122 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003123}
3124
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003125/*
3126 *
3127 *
3128 * Class AppletTCP
3129 *
3130 *
3131 */
3132
3133/* Returns a struct hlua_txn if the stack entry "ud" is
3134 * a class stream, otherwise it throws an error.
3135 */
3136__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3137{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003138 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003139}
3140
3141/* This function creates and push in the stack an Applet object
3142 * according with a current TXN.
3143 */
3144static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3145{
3146 struct hlua_appctx *appctx;
3147 struct stream_interface *si = ctx->owner;
3148 struct stream *s = si_strm(si);
3149 struct proxy *p = s->be;
3150
3151 /* Check stack size. */
3152 if (!lua_checkstack(L, 3))
3153 return 0;
3154
3155 /* Create the object: obj[0] = userdata.
3156 * Note that the base of the Converters object is the
3157 * same than the TXN object.
3158 */
3159 lua_newtable(L);
3160 appctx = lua_newuserdata(L, sizeof(*appctx));
3161 lua_rawseti(L, -2, 0);
3162 appctx->appctx = ctx;
3163 appctx->htxn.s = s;
3164 appctx->htxn.p = p;
3165
3166 /* Create the "f" field that contains a list of fetches. */
3167 lua_pushstring(L, "f");
3168 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3169 return 0;
3170 lua_settable(L, -3);
3171
3172 /* Create the "sf" field that contains a list of stringsafe fetches. */
3173 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003174 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003175 return 0;
3176 lua_settable(L, -3);
3177
3178 /* Create the "c" field that contains a list of converters. */
3179 lua_pushstring(L, "c");
3180 if (!hlua_converters_new(L, &appctx->htxn, 0))
3181 return 0;
3182 lua_settable(L, -3);
3183
3184 /* Create the "sc" field that contains a list of stringsafe converters. */
3185 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003186 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003187 return 0;
3188 lua_settable(L, -3);
3189
3190 /* Pop a class stream metatable and affect it to the table. */
3191 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3192 lua_setmetatable(L, -2);
3193
3194 return 1;
3195}
3196
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003197__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3198{
3199 struct hlua_appctx *appctx;
3200 struct stream *s;
3201 const char *name;
3202 size_t len;
3203 struct sample smp;
3204
3205 MAY_LJMP(check_args(L, 3, "set_var"));
3206
3207 /* It is useles to retrieve the stream, but this function
3208 * runs only in a stream context.
3209 */
3210 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3211 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3212 s = appctx->htxn.s;
3213
3214 /* Converts the third argument in a sample. */
3215 hlua_lua2smp(L, 3, &smp);
3216
3217 /* Store the sample in a variable. */
3218 smp_set_owner(&smp, s->be, s->sess, s, 0);
3219 vars_set_by_name(name, len, &smp);
3220 return 0;
3221}
3222
3223__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3224{
3225 struct hlua_appctx *appctx;
3226 struct stream *s;
3227 const char *name;
3228 size_t len;
3229 struct sample smp;
3230
3231 MAY_LJMP(check_args(L, 2, "unset_var"));
3232
3233 /* It is useles to retrieve the stream, but this function
3234 * runs only in a stream context.
3235 */
3236 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3237 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3238 s = appctx->htxn.s;
3239
3240 /* Unset the variable. */
3241 smp_set_owner(&smp, s->be, s->sess, s, 0);
3242 vars_unset_by_name(name, len, &smp);
3243 return 0;
3244}
3245
3246__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3247{
3248 struct hlua_appctx *appctx;
3249 struct stream *s;
3250 const char *name;
3251 size_t len;
3252 struct sample smp;
3253
3254 MAY_LJMP(check_args(L, 2, "get_var"));
3255
3256 /* It is useles to retrieve the stream, but this function
3257 * runs only in a stream context.
3258 */
3259 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3260 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3261 s = appctx->htxn.s;
3262
3263 smp_set_owner(&smp, s->be, s->sess, s, 0);
3264 if (!vars_get_by_name(name, len, &smp)) {
3265 lua_pushnil(L);
3266 return 1;
3267 }
3268
3269 return hlua_smp2lua(L, &smp);
3270}
3271
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003272__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3273{
3274 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3275 struct stream *s = appctx->htxn.s;
3276 struct hlua *hlua = &s->hlua;
3277
3278 MAY_LJMP(check_args(L, 2, "set_priv"));
3279
3280 /* Remove previous value. */
3281 if (hlua->Mref != -1)
3282 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3283
3284 /* Get and store new value. */
3285 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3286 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3287
3288 return 0;
3289}
3290
3291__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3292{
3293 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3294 struct stream *s = appctx->htxn.s;
3295 struct hlua *hlua = &s->hlua;
3296
3297 /* Push configuration index in the stack. */
3298 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3299
3300 return 1;
3301}
3302
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003303/* If expected data not yet available, it returns a yield. This function
3304 * consumes the data in the buffer. It returns a string containing the
3305 * data. This string can be empty.
3306 */
3307__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3308{
3309 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3310 struct stream_interface *si = appctx->appctx->owner;
3311 int ret;
3312 char *blk1;
3313 int len1;
3314 char *blk2;
3315 int len2;
3316
3317 /* Read the maximum amount of data avalaible. */
3318 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3319
3320 /* Data not yet avalaible. return yield. */
3321 if (ret == 0) {
3322 si_applet_cant_get(si);
3323 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3324 }
3325
3326 /* End of data: commit the total strings and return. */
3327 if (ret < 0) {
3328 luaL_pushresult(&appctx->b);
3329 return 1;
3330 }
3331
3332 /* Ensure that the block 2 length is usable. */
3333 if (ret == 1)
3334 len2 = 0;
3335
3336 /* dont check the max length read and dont check. */
3337 luaL_addlstring(&appctx->b, blk1, len1);
3338 luaL_addlstring(&appctx->b, blk2, len2);
3339
3340 /* Consume input channel output buffer data. */
3341 bo_skip(si_oc(si), len1 + len2);
3342 luaL_pushresult(&appctx->b);
3343 return 1;
3344}
3345
3346/* Check arguments for the fucntion "hlua_channel_get_yield". */
3347__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3348{
3349 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3350
3351 /* Initialise the string catenation. */
3352 luaL_buffinit(L, &appctx->b);
3353
3354 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3355}
3356
3357/* If expected data not yet available, it returns a yield. This function
3358 * consumes the data in the buffer. It returns a string containing the
3359 * data. This string can be empty.
3360 */
3361__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3362{
3363 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3364 struct stream_interface *si = appctx->appctx->owner;
3365 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3366 int ret;
3367 char *blk1;
3368 int len1;
3369 char *blk2;
3370 int len2;
3371
3372 /* Read the maximum amount of data avalaible. */
3373 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3374
3375 /* Data not yet avalaible. return yield. */
3376 if (ret == 0) {
3377 si_applet_cant_get(si);
3378 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3379 }
3380
3381 /* End of data: commit the total strings and return. */
3382 if (ret < 0) {
3383 luaL_pushresult(&appctx->b);
3384 return 1;
3385 }
3386
3387 /* Ensure that the block 2 length is usable. */
3388 if (ret == 1)
3389 len2 = 0;
3390
3391 if (len == -1) {
3392
3393 /* If len == -1, catenate all the data avalaile and
3394 * yield because we want to get all the data until
3395 * the end of data stream.
3396 */
3397 luaL_addlstring(&appctx->b, blk1, len1);
3398 luaL_addlstring(&appctx->b, blk2, len2);
3399 bo_skip(si_oc(si), len1 + len2);
3400 si_applet_cant_get(si);
3401 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3402
3403 } else {
3404
3405 /* Copy the fisrt block caping to the length required. */
3406 if (len1 > len)
3407 len1 = len;
3408 luaL_addlstring(&appctx->b, blk1, len1);
3409 len -= len1;
3410
3411 /* Copy the second block. */
3412 if (len2 > len)
3413 len2 = len;
3414 luaL_addlstring(&appctx->b, blk2, len2);
3415 len -= len2;
3416
3417 /* Consume input channel output buffer data. */
3418 bo_skip(si_oc(si), len1 + len2);
3419
3420 /* If we are no other data avalaible, yield waiting for new data. */
3421 if (len > 0) {
3422 lua_pushinteger(L, len);
3423 lua_replace(L, 2);
3424 si_applet_cant_get(si);
3425 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3426 }
3427
3428 /* return the result. */
3429 luaL_pushresult(&appctx->b);
3430 return 1;
3431 }
3432
3433 /* we never executes this */
3434 hlua_pusherror(L, "Lua: internal error");
3435 WILL_LJMP(lua_error(L));
3436 return 0;
3437}
3438
3439/* Check arguments for the fucntion "hlua_channel_get_yield". */
3440__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3441{
3442 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3443 int len = -1;
3444
3445 if (lua_gettop(L) > 2)
3446 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3447 if (lua_gettop(L) >= 2) {
3448 len = MAY_LJMP(luaL_checkinteger(L, 2));
3449 lua_pop(L, 1);
3450 }
3451
3452 /* Confirm or set the required length */
3453 lua_pushinteger(L, len);
3454
3455 /* Initialise the string catenation. */
3456 luaL_buffinit(L, &appctx->b);
3457
3458 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3459}
3460
3461/* Append data in the output side of the buffer. This data is immediatly
3462 * sent. The fcuntion returns the ammount of data writed. If the buffer
3463 * cannot contains the data, the function yield. The function returns -1
3464 * if the channel is closed.
3465 */
3466__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3467{
3468 size_t len;
3469 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3470 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3471 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3472 struct stream_interface *si = appctx->appctx->owner;
3473 struct channel *chn = si_ic(si);
3474 int max;
3475
3476 /* Get the max amount of data which can write as input in the channel. */
3477 max = channel_recv_max(chn);
3478 if (max > (len - l))
3479 max = len - l;
3480
3481 /* Copy data. */
3482 bi_putblk(chn, str + l, max);
3483
3484 /* update counters. */
3485 l += max;
3486 lua_pop(L, 1);
3487 lua_pushinteger(L, l);
3488
3489 /* If some data is not send, declares the situation to the
3490 * applet, and returns a yield.
3491 */
3492 if (l < len) {
3493 si_applet_cant_put(si);
3494 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3495 }
3496
3497 return 1;
3498}
3499
3500/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3501 * yield the LUA process, and resume it without checking the
3502 * input arguments.
3503 */
3504__LJMP static int hlua_applet_tcp_send(lua_State *L)
3505{
3506 MAY_LJMP(check_args(L, 2, "send"));
3507 lua_pushinteger(L, 0);
3508
3509 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3510}
3511
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003512/*
3513 *
3514 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003515 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003516 *
3517 *
3518 */
3519
3520/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003521 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003522 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003523__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003524{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003525 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003526}
3527
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003528/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003529 * according with a current TXN.
3530 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003531static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003532{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003533 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003534 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003535 struct stream_interface *si = ctx->owner;
3536 struct stream *s = si_strm(si);
3537 struct proxy *px = s->be;
3538 struct http_txn *txn = s->txn;
3539 const char *path;
3540 const char *end;
3541 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003542
3543 /* Check stack size. */
3544 if (!lua_checkstack(L, 3))
3545 return 0;
3546
3547 /* Create the object: obj[0] = userdata.
3548 * Note that the base of the Converters object is the
3549 * same than the TXN object.
3550 */
3551 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003552 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003553 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003554 appctx->appctx = ctx;
3555 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
3556 appctx->htxn.s = s;
3557 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003558
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003559 /* Create the "f" field that contains a list of fetches. */
3560 lua_pushstring(L, "f");
3561 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3562 return 0;
3563 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003564
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003565 /* Create the "sf" field that contains a list of stringsafe fetches. */
3566 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003567 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003568 return 0;
3569 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003570
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003571 /* Create the "c" field that contains a list of converters. */
3572 lua_pushstring(L, "c");
3573 if (!hlua_converters_new(L, &appctx->htxn, 0))
3574 return 0;
3575 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003576
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003577 /* Create the "sc" field that contains a list of stringsafe converters. */
3578 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003579 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003580 return 0;
3581 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003582
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003583 /* Stores the request method. */
3584 lua_pushstring(L, "method");
3585 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3586 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003587
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003588 /* Stores the http version. */
3589 lua_pushstring(L, "version");
3590 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3591 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003592
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003593 /* creates an array of headers. hlua_http_get_headers() crates and push
3594 * the array on the top of the stack.
3595 */
3596 lua_pushstring(L, "headers");
3597 htxn.s = s;
3598 htxn.p = px;
3599 htxn.dir = SMP_OPT_DIR_REQ;
3600 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3601 return 0;
3602 lua_settable(L, -3);
3603
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003604 /* Get path and qs */
3605 path = http_get_path(txn);
3606 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3607 p = path;
3608 while (p < end && *p != '?')
3609 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003610
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003611 /* Stores the request path. */
3612 lua_pushstring(L, "path");
3613 lua_pushlstring(L, path, p - path);
3614 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003615
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003616 /* Stores the query string. */
3617 lua_pushstring(L, "qs");
3618 if (*p == '?')
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003619 p++;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003620 lua_pushlstring(L, p, end - p);
3621 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003622
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003623 /* Stores the request path. */
3624 lua_pushstring(L, "length");
3625 lua_pushinteger(L, txn->req.body_len);
3626 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003627
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003628 /* Create an array of HTTP request headers. */
3629 lua_pushstring(L, "headers");
3630 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3631 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003632
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003633 /* Create an empty array of HTTP request headers. */
3634 lua_pushstring(L, "response");
3635 lua_newtable(L);
3636 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003637
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003638 /* Pop a class stream metatable and affect it to the table. */
3639 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3640 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003641
3642 return 1;
3643}
3644
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003645__LJMP static int hlua_applet_http_set_var(lua_State *L)
3646{
3647 struct hlua_appctx *appctx;
3648 struct stream *s;
3649 const char *name;
3650 size_t len;
3651 struct sample smp;
3652
3653 MAY_LJMP(check_args(L, 3, "set_var"));
3654
3655 /* It is useles to retrieve the stream, but this function
3656 * runs only in a stream context.
3657 */
3658 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3659 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3660 s = appctx->htxn.s;
3661
3662 /* Converts the third argument in a sample. */
3663 hlua_lua2smp(L, 3, &smp);
3664
3665 /* Store the sample in a variable. */
3666 smp_set_owner(&smp, s->be, s->sess, s, 0);
3667 vars_set_by_name(name, len, &smp);
3668 return 0;
3669}
3670
3671__LJMP static int hlua_applet_http_unset_var(lua_State *L)
3672{
3673 struct hlua_appctx *appctx;
3674 struct stream *s;
3675 const char *name;
3676 size_t len;
3677 struct sample smp;
3678
3679 MAY_LJMP(check_args(L, 2, "unset_var"));
3680
3681 /* It is useles to retrieve the stream, but this function
3682 * runs only in a stream context.
3683 */
3684 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3685 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3686 s = appctx->htxn.s;
3687
3688 /* Unset the variable. */
3689 smp_set_owner(&smp, s->be, s->sess, s, 0);
3690 vars_unset_by_name(name, len, &smp);
3691 return 0;
3692}
3693
3694__LJMP static int hlua_applet_http_get_var(lua_State *L)
3695{
3696 struct hlua_appctx *appctx;
3697 struct stream *s;
3698 const char *name;
3699 size_t len;
3700 struct sample smp;
3701
3702 MAY_LJMP(check_args(L, 2, "get_var"));
3703
3704 /* It is useles to retrieve the stream, but this function
3705 * runs only in a stream context.
3706 */
3707 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3708 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3709 s = appctx->htxn.s;
3710
3711 smp_set_owner(&smp, s->be, s->sess, s, 0);
3712 if (!vars_get_by_name(name, len, &smp)) {
3713 lua_pushnil(L);
3714 return 1;
3715 }
3716
3717 return hlua_smp2lua(L, &smp);
3718}
3719
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003720__LJMP static int hlua_applet_http_set_priv(lua_State *L)
3721{
3722 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3723 struct stream *s = appctx->htxn.s;
3724 struct hlua *hlua = &s->hlua;
3725
3726 MAY_LJMP(check_args(L, 2, "set_priv"));
3727
3728 /* Remove previous value. */
3729 if (hlua->Mref != -1)
3730 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3731
3732 /* Get and store new value. */
3733 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3734 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3735
3736 return 0;
3737}
3738
3739__LJMP static int hlua_applet_http_get_priv(lua_State *L)
3740{
3741 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3742 struct stream *s = appctx->htxn.s;
3743 struct hlua *hlua = &s->hlua;
3744
3745 /* Push configuration index in the stack. */
3746 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3747
3748 return 1;
3749}
3750
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003751/* If expected data not yet available, it returns a yield. This function
3752 * consumes the data in the buffer. It returns a string containing the
3753 * data. This string can be empty.
3754 */
3755__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003756{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003757 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3758 struct stream_interface *si = appctx->appctx->owner;
3759 struct channel *chn = si_ic(si);
3760 int ret;
3761 char *blk1;
3762 int len1;
3763 char *blk2;
3764 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003765
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003766 /* Maybe we cant send a 100-continue ? */
3767 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3768 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3769 /* if ret == -2 or -3 the channel closed or the message si too
3770 * big for the buffers. We cant send anything. So, we ignoring
3771 * the error, considers that the 100-continue is sent, and try
3772 * to receive.
3773 * If ret is -1, we dont have room in the buffer, so we yield.
3774 */
3775 if (ret == -1) {
3776 si_applet_cant_put(si);
3777 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3778 }
3779 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3780 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003781
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003782 /* Check for the end of the data. */
3783 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
3784 luaL_pushresult(&appctx->b);
3785 return 1;
3786 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003787
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003788 /* Read the maximum amount of data avalaible. */
3789 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003790
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003791 /* Data not yet avalaible. return yield. */
3792 if (ret == 0) {
3793 si_applet_cant_get(si);
3794 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3795 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003796
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003797 /* End of data: commit the total strings and return. */
3798 if (ret < 0) {
3799 luaL_pushresult(&appctx->b);
3800 return 1;
3801 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003802
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003803 /* Ensure that the block 2 length is usable. */
3804 if (ret == 1)
3805 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003806
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003807 /* Copy the fisrt block caping to the length required. */
3808 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3809 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3810 luaL_addlstring(&appctx->b, blk1, len1);
3811 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003812
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003813 /* Copy the second block. */
3814 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3815 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3816 luaL_addlstring(&appctx->b, blk2, len2);
3817 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003818
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003819 /* Consume input channel output buffer data. */
3820 bo_skip(si_oc(si), len1 + len2);
3821 luaL_pushresult(&appctx->b);
3822 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003823}
3824
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003825/* Check arguments for the fucntion "hlua_channel_get_yield". */
3826__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003827{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003828 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003829
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003830 /* Initialise the string catenation. */
3831 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003832
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003833 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003834}
3835
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003836/* If expected data not yet available, it returns a yield. This function
3837 * consumes the data in the buffer. It returns a string containing the
3838 * data. This string can be empty.
3839 */
3840__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003841{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003842 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3843 struct stream_interface *si = appctx->appctx->owner;
3844 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3845 struct channel *chn = si_ic(si);
3846 int ret;
3847 char *blk1;
3848 int len1;
3849 char *blk2;
3850 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003851
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003852 /* Maybe we cant send a 100-continue ? */
3853 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3854 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3855 /* if ret == -2 or -3 the channel closed or the message si too
3856 * big for the buffers. We cant send anything. So, we ignoring
3857 * the error, considers that the 100-continue is sent, and try
3858 * to receive.
3859 * If ret is -1, we dont have room in the buffer, so we yield.
3860 */
3861 if (ret == -1) {
3862 si_applet_cant_put(si);
3863 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3864 }
3865 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3866 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003867
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003868 /* Read the maximum amount of data avalaible. */
3869 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003870
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003871 /* Data not yet avalaible. return yield. */
3872 if (ret == 0) {
3873 si_applet_cant_get(si);
3874 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3875 }
3876
3877 /* End of data: commit the total strings and return. */
3878 if (ret < 0) {
3879 luaL_pushresult(&appctx->b);
3880 return 1;
3881 }
3882
3883 /* Ensure that the block 2 length is usable. */
3884 if (ret == 1)
3885 len2 = 0;
3886
3887 /* Copy the fisrt block caping to the length required. */
3888 if (len1 > len)
3889 len1 = len;
3890 luaL_addlstring(&appctx->b, blk1, len1);
3891 len -= len1;
3892
3893 /* Copy the second block. */
3894 if (len2 > len)
3895 len2 = len;
3896 luaL_addlstring(&appctx->b, blk2, len2);
3897 len -= len2;
3898
3899 /* Consume input channel output buffer data. */
3900 bo_skip(si_oc(si), len1 + len2);
3901 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
3902 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
3903
3904 /* If we are no other data avalaible, yield waiting for new data. */
3905 if (len > 0) {
3906 lua_pushinteger(L, len);
3907 lua_replace(L, 2);
3908 si_applet_cant_get(si);
3909 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3910 }
3911
3912 /* return the result. */
3913 luaL_pushresult(&appctx->b);
3914 return 1;
3915}
3916
3917/* Check arguments for the fucntion "hlua_channel_get_yield". */
3918__LJMP static int hlua_applet_http_recv(lua_State *L)
3919{
3920 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3921 int len = -1;
3922
3923 /* Check arguments. */
3924 if (lua_gettop(L) > 2)
3925 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3926 if (lua_gettop(L) >= 2) {
3927 len = MAY_LJMP(luaL_checkinteger(L, 2));
3928 lua_pop(L, 1);
3929 }
3930
3931 /* Check the required length */
3932 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3933 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3934 lua_pushinteger(L, len);
3935
3936 /* Initialise the string catenation. */
3937 luaL_buffinit(L, &appctx->b);
3938
3939 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
3940}
3941
3942/* Append data in the output side of the buffer. This data is immediatly
3943 * sent. The fcuntion returns the ammount of data writed. If the buffer
3944 * cannot contains the data, the function yield. The function returns -1
3945 * if the channel is closed.
3946 */
3947__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
3948{
3949 size_t len;
3950 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3951 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3952 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3953 struct stream_interface *si = appctx->appctx->owner;
3954 struct channel *chn = si_ic(si);
3955 int max;
3956
3957 /* Get the max amount of data which can write as input in the channel. */
3958 max = channel_recv_max(chn);
3959 if (max > (len - l))
3960 max = len - l;
3961
3962 /* Copy data. */
3963 bi_putblk(chn, str + l, max);
3964
3965 /* update counters. */
3966 l += max;
3967 lua_pop(L, 1);
3968 lua_pushinteger(L, l);
3969
3970 /* If some data is not send, declares the situation to the
3971 * applet, and returns a yield.
3972 */
3973 if (l < len) {
3974 si_applet_cant_put(si);
3975 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
3976 }
3977
3978 return 1;
3979}
3980
3981/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
3982 * yield the LUA process, and resume it without checking the
3983 * input arguments.
3984 */
3985__LJMP static int hlua_applet_http_send(lua_State *L)
3986{
3987 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3988 size_t len;
3989 char hex[10];
3990
3991 MAY_LJMP(luaL_checklstring(L, 2, &len));
3992
3993 /* If transfer encoding chunked is selected, we surround the data
3994 * by chunk data.
3995 */
3996 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
3997 snprintf(hex, 9, "%x", (unsigned int)len);
3998 lua_pushfstring(L, "%s\r\n", hex);
3999 lua_insert(L, 2); /* swap the last 2 entries. */
4000 lua_pushstring(L, "\r\n");
4001 lua_concat(L, 3);
4002 }
4003
4004 /* This interger is used for followinf the amount of data sent. */
4005 lua_pushinteger(L, 0);
4006
4007 /* We want to send some data. Headers must be sent. */
4008 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4009 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4010 WILL_LJMP(lua_error(L));
4011 }
4012
4013 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4014}
4015
4016__LJMP static int hlua_applet_http_addheader(lua_State *L)
4017{
4018 const char *name;
4019 int ret;
4020
4021 MAY_LJMP(hlua_checkapplet_http(L, 1));
4022 name = MAY_LJMP(luaL_checkstring(L, 2));
4023 MAY_LJMP(luaL_checkstring(L, 3));
4024
4025 /* Push in the stack the "response" entry. */
4026 ret = lua_getfield(L, 1, "response");
4027 if (ret != LUA_TTABLE) {
4028 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4029 "is expected as an array. %s found", lua_typename(L, ret));
4030 WILL_LJMP(lua_error(L));
4031 }
4032
4033 /* check if the header is already registered if it is not
4034 * the case, register it.
4035 */
4036 ret = lua_getfield(L, -1, name);
4037 if (ret == LUA_TNIL) {
4038
4039 /* Entry not found. */
4040 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4041
4042 /* Insert the new header name in the array in the top of the stack.
4043 * It left the new array in the top of the stack.
4044 */
4045 lua_newtable(L);
4046 lua_pushvalue(L, 2);
4047 lua_pushvalue(L, -2);
4048 lua_settable(L, -4);
4049
4050 } else if (ret != LUA_TTABLE) {
4051
4052 /* corruption error. */
4053 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4054 "is expected as an array. %s found", name, lua_typename(L, ret));
4055 WILL_LJMP(lua_error(L));
4056 }
4057
4058 /* Now the top od thestack is an array of values. We push
4059 * the header value as new entry.
4060 */
4061 lua_pushvalue(L, 3);
4062 ret = lua_rawlen(L, -2);
4063 lua_rawseti(L, -2, ret + 1);
4064 lua_pushboolean(L, 1);
4065 return 1;
4066}
4067
4068__LJMP static int hlua_applet_http_status(lua_State *L)
4069{
4070 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4071 int status = MAY_LJMP(luaL_checkinteger(L, 2));
4072
4073 if (status < 100 || status > 599) {
4074 lua_pushboolean(L, 0);
4075 return 1;
4076 }
4077
4078 appctx->appctx->ctx.hlua_apphttp.status = status;
4079 lua_pushboolean(L, 1);
4080 return 1;
4081}
4082
4083/* We will build the status line and the headers of the HTTP response.
4084 * We will try send at once if its not possible, we give back the hand
4085 * waiting for more room.
4086 */
4087__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4088{
4089 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4090 struct stream_interface *si = appctx->appctx->owner;
4091 struct channel *chn = si_ic(si);
4092 int ret;
4093 size_t len;
4094 const char *msg;
4095
4096 /* Get the message as the first argument on the stack. */
4097 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4098
4099 /* Send the message at once. */
4100 ret = bi_putblk(chn, msg, len);
4101
4102 /* if ret == -2 or -3 the channel closed or the message si too
4103 * big for the buffers.
4104 */
4105 if (ret == -2 || ret == -3) {
4106 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4107 WILL_LJMP(lua_error(L));
4108 }
4109
4110 /* If ret is -1, we dont have room in the buffer, so we yield. */
4111 if (ret == -1) {
4112 si_applet_cant_put(si);
4113 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
4114 }
4115
4116 /* Headers sent, set the flag. */
4117 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4118 return 0;
4119}
4120
4121__LJMP static int hlua_applet_http_start_response(lua_State *L)
4122{
4123 struct chunk *tmp = get_trash_chunk();
4124 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004125 const char *name;
4126 const char *value;
4127 int id;
4128 int hdr_connection = 0;
4129 int hdr_contentlength = -1;
4130 int hdr_chunked = 0;
4131
4132 /* Use the same http version than the request. */
4133 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004134 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004135 appctx->appctx->ctx.hlua_apphttp.status,
4136 get_reason(appctx->appctx->ctx.hlua_apphttp.status));
4137
4138 /* Get the array associated to the field "response" in the object AppletHTTP. */
4139 lua_pushvalue(L, 0);
4140 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4141 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4142 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4143 WILL_LJMP(lua_error(L));
4144 }
4145
4146 /* Browse the list of headers. */
4147 lua_pushnil(L);
4148 while(lua_next(L, -2) != 0) {
4149
4150 /* We expect a string as -2. */
4151 if (lua_type(L, -2) != LUA_TSTRING) {
4152 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4153 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4154 lua_typename(L, lua_type(L, -2)));
4155 WILL_LJMP(lua_error(L));
4156 }
4157 name = lua_tostring(L, -2);
4158
4159 /* We expect an array as -1. */
4160 if (lua_type(L, -1) != LUA_TTABLE) {
4161 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4162 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4163 name,
4164 lua_typename(L, lua_type(L, -1)));
4165 WILL_LJMP(lua_error(L));
4166 }
4167
4168 /* Browse the table who is on the top of the stack. */
4169 lua_pushnil(L);
4170 while(lua_next(L, -2) != 0) {
4171
4172 /* We expect a number as -2. */
4173 if (lua_type(L, -2) != LUA_TNUMBER) {
4174 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4175 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4176 name,
4177 lua_typename(L, lua_type(L, -2)));
4178 WILL_LJMP(lua_error(L));
4179 }
4180 id = lua_tointeger(L, -2);
4181
4182 /* We expect a string as -2. */
4183 if (lua_type(L, -1) != LUA_TSTRING) {
4184 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4185 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4186 name, id,
4187 lua_typename(L, lua_type(L, -1)));
4188 WILL_LJMP(lua_error(L));
4189 }
4190 value = lua_tostring(L, -1);
4191
4192 /* Catenate a new header. */
4193 chunk_appendf(tmp, "%s: %s\r\n", name, value);
4194
4195 /* Protocol checks. */
4196
4197 /* Check if the header conneciton is present. */
4198 if (strcasecmp("connection", name) == 0)
4199 hdr_connection = 1;
4200
4201 /* Copy the header content length. The length conversion
4202 * is done without control. If it contains a ad value, this
4203 * is not our problem.
4204 */
4205 if (strcasecmp("content-length", name) == 0)
4206 hdr_contentlength = atoi(value);
4207
4208 /* Check if the client annouces a transfer-encoding chunked it self. */
4209 if (strcasecmp("transfer-encoding", name) == 0 &&
4210 strcasecmp("chunked", value) == 0)
4211 hdr_chunked = 1;
4212
4213 /* Remove the array from the stack, and get next element with a remaining string. */
4214 lua_pop(L, 1);
4215 }
4216
4217 /* Remove the array from the stack, and get next element with a remaining string. */
4218 lua_pop(L, 1);
4219 }
4220
4221 /* If the http protocol version is 1.1, we expect an header "connection" set
4222 * to "close" to be HAProxy/keeplive compliant. Otherwise, we expect nothing.
4223 * If the header conneciton is present, don't change it, if it is not present,
4224 * we must set.
4225 *
4226 * we set a "connection: close" header for ensuring that the keepalive will be
4227 * respected by haproxy. HAProcy considers that the application cloe the connection
4228 * and it keep the connection from the client open.
4229 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004230 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 && !hdr_connection)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004231 chunk_appendf(tmp, "Connection: close\r\n");
4232
4233 /* If we dont have a content-length set, we must announce a transfer enconding
4234 * chunked. This is required by haproxy for the keepalive compliance.
4235 * If the applet annouce a transfer-encoding chunked itslef, don't
4236 * do anything.
4237 */
4238 if (hdr_contentlength == -1 && hdr_chunked == 0) {
4239 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4240 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4241 }
4242
4243 /* Finalize headers. */
4244 chunk_appendf(tmp, "\r\n");
4245
4246 /* Remove the last entry and the array of headers */
4247 lua_pop(L, 2);
4248
4249 /* Push the headers block. */
4250 lua_pushlstring(L, tmp->str, tmp->len);
4251
4252 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4253}
4254
4255/*
4256 *
4257 *
4258 * Class HTTP
4259 *
4260 *
4261 */
4262
4263/* Returns a struct hlua_txn if the stack entry "ud" is
4264 * a class stream, otherwise it throws an error.
4265 */
4266__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4267{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004268 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004269}
4270
4271/* This function creates and push in the stack a HTTP object
4272 * according with a current TXN.
4273 */
4274static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4275{
4276 struct hlua_txn *htxn;
4277
4278 /* Check stack size. */
4279 if (!lua_checkstack(L, 3))
4280 return 0;
4281
4282 /* Create the object: obj[0] = userdata.
4283 * Note that the base of the Converters object is the
4284 * same than the TXN object.
4285 */
4286 lua_newtable(L);
4287 htxn = lua_newuserdata(L, sizeof(*htxn));
4288 lua_rawseti(L, -2, 0);
4289
4290 htxn->s = txn->s;
4291 htxn->p = txn->p;
4292
4293 /* Pop a class stream metatable and affect it to the table. */
4294 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4295 lua_setmetatable(L, -2);
4296
4297 return 1;
4298}
4299
4300/* This function creates ans returns an array of HTTP headers.
4301 * This function does not fails. It is used as wrapper with the
4302 * 2 following functions.
4303 */
4304__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4305{
4306 const char *cur_ptr, *cur_next, *p;
4307 int old_idx, cur_idx;
4308 struct hdr_idx_elem *cur_hdr;
4309 const char *hn, *hv;
4310 int hnl, hvl;
4311 int type;
4312 const char *in;
4313 char *out;
4314 int len;
4315
4316 /* Create the table. */
4317 lua_newtable(L);
4318
4319 if (!htxn->s->txn)
4320 return 1;
4321
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004322 /* Check if a valid response is parsed */
4323 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4324 return 1;
4325
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004326 /* Build array of headers. */
4327 old_idx = 0;
4328 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4329
4330 while (1) {
4331 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4332 if (!cur_idx)
4333 break;
4334 old_idx = cur_idx;
4335
4336 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4337 cur_ptr = cur_next;
4338 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4339
4340 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4341 * and the next header starts at cur_next. We'll check
4342 * this header in the list as well as against the default
4343 * rule.
4344 */
4345
4346 /* look for ': *'. */
4347 hn = cur_ptr;
4348 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4349 if (p >= cur_ptr+cur_hdr->len)
4350 continue;
4351 hnl = p - hn;
4352 p++;
4353 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4354 p++;
4355 if (p >= cur_ptr+cur_hdr->len)
4356 continue;
4357 hv = p;
4358 hvl = cur_ptr+cur_hdr->len-p;
4359
4360 /* Lowercase the key. Don't check the size of trash, it have
4361 * the size of one buffer and the input data contains in one
4362 * buffer.
4363 */
4364 out = trash.str;
4365 for (in=hn; in<hn+hnl; in++, out++)
4366 *out = tolower(*in);
4367 *out = '\0';
4368
4369 /* Check for existing entry:
4370 * assume that the table is on the top of the stack, and
4371 * push the key in the stack, the function lua_gettable()
4372 * perform the lookup.
4373 */
4374 lua_pushlstring(L, trash.str, hnl);
4375 lua_gettable(L, -2);
4376 type = lua_type(L, -1);
4377
4378 switch (type) {
4379 case LUA_TNIL:
4380 /* Table not found, create it. */
4381 lua_pop(L, 1); /* remove the nil value. */
4382 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4383 lua_newtable(L); /* create and push empty table. */
4384 lua_pushlstring(L, hv, hvl); /* push header value. */
4385 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4386 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4387 break;
4388
4389 case LUA_TTABLE:
4390 /* Entry found: push the value in the table. */
4391 len = lua_rawlen(L, -1);
4392 lua_pushlstring(L, hv, hvl); /* push header value. */
4393 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4394 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4395 break;
4396
4397 default:
4398 /* Other cases are errors. */
4399 hlua_pusherror(L, "internal error during the parsing of headers.");
4400 WILL_LJMP(lua_error(L));
4401 }
4402 }
4403
4404 return 1;
4405}
4406
4407__LJMP static int hlua_http_req_get_headers(lua_State *L)
4408{
4409 struct hlua_txn *htxn;
4410
4411 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4412 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4413
4414 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4415}
4416
4417__LJMP static int hlua_http_res_get_headers(lua_State *L)
4418{
4419 struct hlua_txn *htxn;
4420
4421 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4422 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4423
4424 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4425}
4426
4427/* This function replace full header, or just a value in
4428 * the request or in the response. It is a wrapper fir the
4429 * 4 following functions.
4430 */
4431__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4432 struct http_msg *msg, int action)
4433{
4434 size_t name_len;
4435 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4436 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4437 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4438 struct my_regex re;
4439
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004440 /* Check if a valid response is parsed */
4441 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4442 return 0;
4443
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004444 if (!regex_comp(reg, &re, 1, 1, NULL))
4445 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4446
4447 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4448 regex_free(&re);
4449 return 0;
4450}
4451
4452__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4453{
4454 struct hlua_txn *htxn;
4455
4456 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4457 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4458
4459 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4460}
4461
4462__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4463{
4464 struct hlua_txn *htxn;
4465
4466 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4467 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4468
4469 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4470}
4471
4472__LJMP static int hlua_http_req_rep_val(lua_State *L)
4473{
4474 struct hlua_txn *htxn;
4475
4476 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4477 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4478
4479 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4480}
4481
4482__LJMP static int hlua_http_res_rep_val(lua_State *L)
4483{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004484 struct hlua_txn *htxn;
4485
4486 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4487 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4488
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004489 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004490}
4491
4492/* This function deletes all the occurences of an header.
4493 * It is a wrapper for the 2 following functions.
4494 */
4495__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4496{
4497 size_t len;
4498 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4499 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004500 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004501
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004502 /* Check if a valid response is parsed */
4503 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4504 return 0;
4505
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004506 ctx.idx = 0;
4507 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4508 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4509 return 0;
4510}
4511
4512__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4513{
4514 struct hlua_txn *htxn;
4515
4516 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4517 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4518
Willy Tarreaueee5b512015-04-03 23:46:31 +02004519 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004520}
4521
4522__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4523{
4524 struct hlua_txn *htxn;
4525
4526 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4527 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4528
Willy Tarreaueee5b512015-04-03 23:46:31 +02004529 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004530}
4531
4532/* This function adds an header. It is a wrapper used by
4533 * the 2 following functions.
4534 */
4535__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4536{
4537 size_t name_len;
4538 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4539 size_t value_len;
4540 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4541 char *p;
4542
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004543 /* Check if a valid message is parsed */
4544 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4545 return 0;
4546
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004547 /* Check length. */
4548 trash.len = value_len + name_len + 2;
4549 if (trash.len > trash.size)
4550 return 0;
4551
4552 /* Creates the header string. */
4553 p = trash.str;
4554 memcpy(p, name, name_len);
4555 p += name_len;
4556 *p = ':';
4557 p++;
4558 *p = ' ';
4559 p++;
4560 memcpy(p, value, value_len);
4561
Willy Tarreaueee5b512015-04-03 23:46:31 +02004562 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004563 trash.str, trash.len) != 0);
4564
4565 return 0;
4566}
4567
4568__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4569{
4570 struct hlua_txn *htxn;
4571
4572 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4573 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4574
Willy Tarreaueee5b512015-04-03 23:46:31 +02004575 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004576}
4577
4578__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4579{
4580 struct hlua_txn *htxn;
4581
4582 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4583 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4584
Willy Tarreaueee5b512015-04-03 23:46:31 +02004585 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004586}
4587
4588static int hlua_http_req_set_hdr(lua_State *L)
4589{
4590 struct hlua_txn *htxn;
4591
4592 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4593 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4594
Willy Tarreaueee5b512015-04-03 23:46:31 +02004595 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4596 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004597}
4598
4599static int hlua_http_res_set_hdr(lua_State *L)
4600{
4601 struct hlua_txn *htxn;
4602
4603 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4604 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4605
Willy Tarreaueee5b512015-04-03 23:46:31 +02004606 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4607 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004608}
4609
4610/* This function set the method. */
4611static int hlua_http_req_set_meth(lua_State *L)
4612{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004613 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004614 size_t name_len;
4615 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004616
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004617 /* Check if a valid request is parsed */
4618 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4619 lua_pushboolean(L, 0);
4620 return 1;
4621 }
4622
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004623 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004624 return 1;
4625}
4626
4627/* This function set the method. */
4628static int hlua_http_req_set_path(lua_State *L)
4629{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004630 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004631 size_t name_len;
4632 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004633
4634 /* Check if a valid request is parsed */
4635 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4636 lua_pushboolean(L, 0);
4637 return 1;
4638 }
4639
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004640 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004641 return 1;
4642}
4643
4644/* This function set the query-string. */
4645static int hlua_http_req_set_query(lua_State *L)
4646{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004647 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004648 size_t name_len;
4649 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004650
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004651 /* Check if a valid request is parsed */
4652 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4653 lua_pushboolean(L, 0);
4654 return 1;
4655 }
4656
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004657 /* Check length. */
4658 if (name_len > trash.size - 1) {
4659 lua_pushboolean(L, 0);
4660 return 1;
4661 }
4662
4663 /* Add the mark question as prefix. */
4664 chunk_reset(&trash);
4665 trash.str[trash.len++] = '?';
4666 memcpy(trash.str + trash.len, name, name_len);
4667 trash.len += name_len;
4668
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004669 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004670 return 1;
4671}
4672
4673/* This function set the uri. */
4674static int hlua_http_req_set_uri(lua_State *L)
4675{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004676 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004677 size_t name_len;
4678 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004679
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004680 /* Check if a valid request is parsed */
4681 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4682 lua_pushboolean(L, 0);
4683 return 1;
4684 }
4685
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004686 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004687 return 1;
4688}
4689
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004690/* This function set the response code. */
4691static int hlua_http_res_set_status(lua_State *L)
4692{
4693 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4694 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
4695
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004696 /* Check if a valid response is parsed */
4697 if (unlikely(htxn->s->txn->rsp.msg_state < HTTP_MSG_BODY))
4698 return 0;
4699
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004700 http_set_status(code, htxn->s);
4701 return 0;
4702}
4703
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004704/*
4705 *
4706 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004707 * Class TXN
4708 *
4709 *
4710 */
4711
4712/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004713 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004714 */
4715__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
4716{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004717 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004718}
4719
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004720__LJMP static int hlua_set_var(lua_State *L)
4721{
4722 struct hlua_txn *htxn;
4723 const char *name;
4724 size_t len;
4725 struct sample smp;
4726
4727 MAY_LJMP(check_args(L, 3, "set_var"));
4728
4729 /* It is useles to retrieve the stream, but this function
4730 * runs only in a stream context.
4731 */
4732 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4733 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4734
4735 /* Converts the third argument in a sample. */
4736 hlua_lua2smp(L, 3, &smp);
4737
4738 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01004739 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004740 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004741 return 0;
4742}
4743
Christopher Faulet85d79c92016-11-09 16:54:56 +01004744__LJMP static int hlua_unset_var(lua_State *L)
4745{
4746 struct hlua_txn *htxn;
4747 const char *name;
4748 size_t len;
4749 struct sample smp;
4750
4751 MAY_LJMP(check_args(L, 2, "unset_var"));
4752
4753 /* It is useles to retrieve the stream, but this function
4754 * runs only in a stream context.
4755 */
4756 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4757 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4758
4759 /* Unset the variable. */
4760 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
4761 vars_unset_by_name(name, len, &smp);
4762 return 0;
4763}
4764
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004765__LJMP static int hlua_get_var(lua_State *L)
4766{
4767 struct hlua_txn *htxn;
4768 const char *name;
4769 size_t len;
4770 struct sample smp;
4771
4772 MAY_LJMP(check_args(L, 2, "get_var"));
4773
4774 /* It is useles to retrieve the stream, but this function
4775 * runs only in a stream context.
4776 */
4777 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4778 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4779
Willy Tarreau7560dd42016-03-10 16:28:58 +01004780 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004781 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004782 lua_pushnil(L);
4783 return 1;
4784 }
4785
4786 return hlua_smp2lua(L, &smp);
4787}
4788
Willy Tarreau59551662015-03-10 14:23:13 +01004789__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004790{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004791 struct hlua *hlua;
4792
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004793 MAY_LJMP(check_args(L, 2, "set_priv"));
4794
Willy Tarreau87b09662015-04-03 00:22:06 +02004795 /* It is useles to retrieve the stream, but this function
4796 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004797 */
4798 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004799 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004800
4801 /* Remove previous value. */
4802 if (hlua->Mref != -1)
4803 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
4804
4805 /* Get and store new value. */
4806 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4807 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4808
4809 return 0;
4810}
4811
Willy Tarreau59551662015-03-10 14:23:13 +01004812__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004813{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004814 struct hlua *hlua;
4815
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004816 MAY_LJMP(check_args(L, 1, "get_priv"));
4817
Willy Tarreau87b09662015-04-03 00:22:06 +02004818 /* It is useles to retrieve the stream, but this function
4819 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004820 */
4821 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004822 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004823
4824 /* Push configuration index in the stack. */
4825 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4826
4827 return 1;
4828}
4829
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004830/* Create stack entry containing a class TXN. This function
4831 * return 0 if the stack does not contains free slots,
4832 * otherwise it returns 1.
4833 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004834static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004835{
Willy Tarreaude491382015-04-06 11:04:28 +02004836 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004837
4838 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004839 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004840 return 0;
4841
4842 /* NOTE: The allocation never fails. The failure
4843 * throw an error, and the function never returns.
4844 * if the throw is not avalaible, the process is aborted.
4845 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004846 /* Create the object: obj[0] = userdata. */
4847 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02004848 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004849 lua_rawseti(L, -2, 0);
4850
Willy Tarreaude491382015-04-06 11:04:28 +02004851 htxn->s = s;
4852 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004853 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004854 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004855
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004856 /* Create the "f" field that contains a list of fetches. */
4857 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004858 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004859 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004860 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004861
4862 /* Create the "sf" field that contains a list of stringsafe fetches. */
4863 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004864 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004865 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004866 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004867
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004868 /* Create the "c" field that contains a list of converters. */
4869 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02004870 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004871 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004872 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004873
4874 /* Create the "sc" field that contains a list of stringsafe converters. */
4875 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004876 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004877 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004878 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004879
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004880 /* Create the "req" field that contains the request channel object. */
4881 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004882 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004883 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004884 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004885
4886 /* Create the "res" field that contains the response channel object. */
4887 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004888 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004889 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004890 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004891
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004892 /* Creates the HTTP object is the current proxy allows http. */
4893 lua_pushstring(L, "http");
4894 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02004895 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004896 return 0;
4897 }
4898 else
4899 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004900 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004901
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004902 /* Pop a class sesison metatable and affect it to the userdata. */
4903 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
4904 lua_setmetatable(L, -2);
4905
4906 return 1;
4907}
4908
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004909__LJMP static int hlua_txn_deflog(lua_State *L)
4910{
4911 const char *msg;
4912 struct hlua_txn *htxn;
4913
4914 MAY_LJMP(check_args(L, 2, "deflog"));
4915 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4916 msg = MAY_LJMP(luaL_checkstring(L, 2));
4917
4918 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
4919 return 0;
4920}
4921
4922__LJMP static int hlua_txn_log(lua_State *L)
4923{
4924 int level;
4925 const char *msg;
4926 struct hlua_txn *htxn;
4927
4928 MAY_LJMP(check_args(L, 3, "log"));
4929 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4930 level = MAY_LJMP(luaL_checkinteger(L, 2));
4931 msg = MAY_LJMP(luaL_checkstring(L, 3));
4932
4933 if (level < 0 || level >= NB_LOG_LEVELS)
4934 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
4935
4936 hlua_sendlog(htxn->s->be, level, msg);
4937 return 0;
4938}
4939
4940__LJMP static int hlua_txn_log_debug(lua_State *L)
4941{
4942 const char *msg;
4943 struct hlua_txn *htxn;
4944
4945 MAY_LJMP(check_args(L, 2, "Debug"));
4946 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4947 msg = MAY_LJMP(luaL_checkstring(L, 2));
4948 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
4949 return 0;
4950}
4951
4952__LJMP static int hlua_txn_log_info(lua_State *L)
4953{
4954 const char *msg;
4955 struct hlua_txn *htxn;
4956
4957 MAY_LJMP(check_args(L, 2, "Info"));
4958 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4959 msg = MAY_LJMP(luaL_checkstring(L, 2));
4960 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
4961 return 0;
4962}
4963
4964__LJMP static int hlua_txn_log_warning(lua_State *L)
4965{
4966 const char *msg;
4967 struct hlua_txn *htxn;
4968
4969 MAY_LJMP(check_args(L, 2, "Warning"));
4970 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4971 msg = MAY_LJMP(luaL_checkstring(L, 2));
4972 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
4973 return 0;
4974}
4975
4976__LJMP static int hlua_txn_log_alert(lua_State *L)
4977{
4978 const char *msg;
4979 struct hlua_txn *htxn;
4980
4981 MAY_LJMP(check_args(L, 2, "Alert"));
4982 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4983 msg = MAY_LJMP(luaL_checkstring(L, 2));
4984 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
4985 return 0;
4986}
4987
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004988__LJMP static int hlua_txn_set_loglevel(lua_State *L)
4989{
4990 struct hlua_txn *htxn;
4991 int ll;
4992
4993 MAY_LJMP(check_args(L, 2, "set_loglevel"));
4994 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4995 ll = MAY_LJMP(luaL_checkinteger(L, 2));
4996
4997 if (ll < 0 || ll > 7)
4998 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
4999
5000 htxn->s->logs.level = ll;
5001 return 0;
5002}
5003
5004__LJMP static int hlua_txn_set_tos(lua_State *L)
5005{
5006 struct hlua_txn *htxn;
5007 struct connection *cli_conn;
5008 int tos;
5009
5010 MAY_LJMP(check_args(L, 2, "set_tos"));
5011 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5012 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5013
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005014 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Vincent Bernat6e615892016-05-18 16:17:44 +02005015 inet_set_tos(cli_conn->t.sock.fd, &cli_conn->addr.from, tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005016
5017 return 0;
5018}
5019
5020__LJMP static int hlua_txn_set_mark(lua_State *L)
5021{
5022#ifdef SO_MARK
5023 struct hlua_txn *htxn;
5024 struct connection *cli_conn;
5025 int mark;
5026
5027 MAY_LJMP(check_args(L, 2, "set_mark"));
5028 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5029 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5030
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005031 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02005032 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005033#endif
5034 return 0;
5035}
5036
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005037/* This function is an Lua binding that send pending data
5038 * to the client, and close the stream interface.
5039 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005040__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005041{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005042 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005043 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01005044 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005045
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005046 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005047 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005048 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005049
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005050 /* If the flags NOTERM is set, we cannot terminate the http
5051 * session, so we just end the execution of the current
5052 * lua code.
5053 */
5054 if (htxn->flags & HLUA_TXN_NOTERM) {
5055 WILL_LJMP(hlua_done(L));
5056 return 0;
5057 }
5058
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005059 ic = &htxn->s->req;
5060 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005061
Willy Tarreau630ef452015-08-28 10:06:15 +02005062 if (htxn->s->txn) {
5063 /* HTTP mode, let's stay in sync with the stream */
5064 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
5065 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
5066 htxn->s->txn->req.sov = 0;
5067 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
5068 oc->analysers = AN_RES_HTTP_XFER_BODY;
5069 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
5070 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
5071
Willy Tarreau630ef452015-08-28 10:06:15 +02005072 /* Note that if we want to support keep-alive, we need
5073 * to bypass the close/shutr_now calls below, but that
5074 * may only be done if the HTTP request was already
5075 * processed and the connection header is known (ie
5076 * not during TCP rules).
5077 */
5078 }
5079
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005080 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01005081 channel_abort(ic);
5082 channel_auto_close(ic);
5083 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005084
5085 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01005086 channel_auto_read(oc);
5087 channel_auto_close(oc);
5088 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005089
Willy Tarreau0458b082015-08-28 09:40:04 +02005090 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005091
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005092 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005093 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005094 return 0;
5095}
5096
5097__LJMP static int hlua_log(lua_State *L)
5098{
5099 int level;
5100 const char *msg;
5101
5102 MAY_LJMP(check_args(L, 2, "log"));
5103 level = MAY_LJMP(luaL_checkinteger(L, 1));
5104 msg = MAY_LJMP(luaL_checkstring(L, 2));
5105
5106 if (level < 0 || level >= NB_LOG_LEVELS)
5107 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5108
5109 hlua_sendlog(NULL, level, msg);
5110 return 0;
5111}
5112
5113__LJMP static int hlua_log_debug(lua_State *L)
5114{
5115 const char *msg;
5116
5117 MAY_LJMP(check_args(L, 1, "debug"));
5118 msg = MAY_LJMP(luaL_checkstring(L, 1));
5119 hlua_sendlog(NULL, LOG_DEBUG, msg);
5120 return 0;
5121}
5122
5123__LJMP static int hlua_log_info(lua_State *L)
5124{
5125 const char *msg;
5126
5127 MAY_LJMP(check_args(L, 1, "info"));
5128 msg = MAY_LJMP(luaL_checkstring(L, 1));
5129 hlua_sendlog(NULL, LOG_INFO, msg);
5130 return 0;
5131}
5132
5133__LJMP static int hlua_log_warning(lua_State *L)
5134{
5135 const char *msg;
5136
5137 MAY_LJMP(check_args(L, 1, "warning"));
5138 msg = MAY_LJMP(luaL_checkstring(L, 1));
5139 hlua_sendlog(NULL, LOG_WARNING, msg);
5140 return 0;
5141}
5142
5143__LJMP static int hlua_log_alert(lua_State *L)
5144{
5145 const char *msg;
5146
5147 MAY_LJMP(check_args(L, 1, "alert"));
5148 msg = MAY_LJMP(luaL_checkstring(L, 1));
5149 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005150 return 0;
5151}
5152
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005153__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005154{
5155 int wakeup_ms = lua_tointeger(L, -1);
5156 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005157 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005158 return 0;
5159}
5160
5161__LJMP static int hlua_sleep(lua_State *L)
5162{
5163 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005164 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005165
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005166 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005167
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005168 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005169 wakeup_ms = tick_add(now_ms, delay);
5170 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005171
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005172 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5173 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005174}
5175
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005176__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005177{
5178 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005179 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005180
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005181 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005182
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005183 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005184 wakeup_ms = tick_add(now_ms, delay);
5185 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005186
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005187 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5188 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005189}
5190
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005191/* This functionis an LUA binding. it permits to give back
5192 * the hand at the HAProxy scheduler. It is used when the
5193 * LUA processing consumes a lot of time.
5194 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005195__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005196{
5197 return 0;
5198}
5199
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005200__LJMP static int hlua_yield(lua_State *L)
5201{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005202 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
5203 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005204}
5205
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005206/* This function change the nice of the currently executed
5207 * task. It is used set low or high priority at the current
5208 * task.
5209 */
Willy Tarreau59551662015-03-10 14:23:13 +01005210__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005211{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005212 struct hlua *hlua;
5213 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005214
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005215 MAY_LJMP(check_args(L, 1, "set_nice"));
5216 hlua = hlua_gethlua(L);
5217 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005218
5219 /* If he task is not set, I'm in a start mode. */
5220 if (!hlua || !hlua->task)
5221 return 0;
5222
5223 if (nice < -1024)
5224 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005225 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005226 nice = 1024;
5227
5228 hlua->task->nice = nice;
5229 return 0;
5230}
5231
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005232/* This function is used as a calback of a task. It is called by the
5233 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5234 * return an E_AGAIN signal, the emmiter of this signal must set a
5235 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005236 *
5237 * Task wrapper are longjmp safe because the only one Lua code
5238 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005239 */
5240static struct task *hlua_process_task(struct task *task)
5241{
5242 struct hlua *hlua = task->context;
5243 enum hlua_exec status;
5244
5245 /* We need to remove the task from the wait queue before executing
5246 * the Lua code because we don't know if it needs to wait for
5247 * another timer or not in the case of E_AGAIN.
5248 */
5249 task_delete(task);
5250
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005251 /* If it is the first call to the task, we must initialize the
5252 * execution timeouts.
5253 */
5254 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005255 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005256
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005257 /* Execute the Lua code. */
5258 status = hlua_ctx_resume(hlua, 1);
5259
5260 switch (status) {
5261 /* finished or yield */
5262 case HLUA_E_OK:
5263 hlua_ctx_destroy(hlua);
5264 task_delete(task);
5265 task_free(task);
5266 break;
5267
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005268 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
5269 if (hlua->wake_time != TICK_ETERNITY)
5270 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005271 break;
5272
5273 /* finished with error. */
5274 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005275 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005276 hlua_ctx_destroy(hlua);
5277 task_delete(task);
5278 task_free(task);
5279 break;
5280
5281 case HLUA_E_ERR:
5282 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005283 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005284 hlua_ctx_destroy(hlua);
5285 task_delete(task);
5286 task_free(task);
5287 break;
5288 }
5289 return NULL;
5290}
5291
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005292/* This function is an LUA binding that register LUA function to be
5293 * executed after the HAProxy configuration parsing and before the
5294 * HAProxy scheduler starts. This function expect only one LUA
5295 * argument that is a function. This function returns nothing, but
5296 * throws if an error is encountered.
5297 */
5298__LJMP static int hlua_register_init(lua_State *L)
5299{
5300 struct hlua_init_function *init;
5301 int ref;
5302
5303 MAY_LJMP(check_args(L, 1, "register_init"));
5304
5305 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5306
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005307 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005308 if (!init)
5309 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5310
5311 init->function_ref = ref;
5312 LIST_ADDQ(&hlua_init_functions, &init->l);
5313 return 0;
5314}
5315
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005316/* This functio is an LUA binding. It permits to register a task
5317 * executed in parallel of the main HAroxy activity. The task is
5318 * created and it is set in the HAProxy scheduler. It can be called
5319 * from the "init" section, "post init" or during the runtime.
5320 *
5321 * Lua prototype:
5322 *
5323 * <none> core.register_task(<function>)
5324 */
5325static int hlua_register_task(lua_State *L)
5326{
5327 struct hlua *hlua;
5328 struct task *task;
5329 int ref;
5330
5331 MAY_LJMP(check_args(L, 1, "register_task"));
5332
5333 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5334
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005335 hlua = calloc(1, sizeof(*hlua));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005336 if (!hlua)
5337 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5338
5339 task = task_new();
5340 task->context = hlua;
5341 task->process = hlua_process_task;
5342
5343 if (!hlua_ctx_init(hlua, task))
5344 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5345
5346 /* Restore the function in the stack. */
5347 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5348 hlua->nargs = 0;
5349
5350 /* Schedule task. */
5351 task_schedule(task, now_ms);
5352
5353 return 0;
5354}
5355
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005356/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5357 * doesn't allow "yield" functions because the HAProxy engine cannot
5358 * resume converters.
5359 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005360static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005361{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005362 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005363 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005364 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005365
Willy Tarreaube508f12016-03-10 11:47:01 +01005366 if (!stream)
5367 return 0;
5368
Willy Tarreau87b09662015-04-03 00:22:06 +02005369 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005370 * Lua context can be not initialized. This behavior
5371 * permits to save performances because a systematic
5372 * Lua initialization cause 5% performances loss.
5373 */
Willy Tarreau87b09662015-04-03 00:22:06 +02005374 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005375 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005376 return 0;
5377 }
5378
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005379 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005380 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005381
5382 /* The following Lua calls can fail. */
5383 if (!SET_SAFE_LJMP(stream->hlua.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005384 if (lua_type(stream->hlua.T, -1) == LUA_TSTRING)
5385 error = lua_tostring(stream->hlua.T, -1);
5386 else
5387 error = "critical error";
5388 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005389 return 0;
5390 }
5391
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005392 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005393 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005394 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005395 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005396 return 0;
5397 }
5398
5399 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005400 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005401
5402 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005403 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005404 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005405 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005406 return 0;
5407 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005408 hlua_smp2lua(stream->hlua.T, smp);
Thierry Fournier4a53bfd2016-05-27 16:35:01 +02005409 stream->hlua.nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005410
5411 /* push keywords in the stack. */
5412 if (arg_p) {
5413 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02005414 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005415 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005416 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005417 return 0;
5418 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005419 hlua_arg2lua(stream->hlua.T, arg_p);
5420 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005421 }
5422 }
5423
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005424 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005425 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005426
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005427 /* At this point the execution is safe. */
5428 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005429 }
5430
5431 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005432 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005433 /* finished. */
5434 case HLUA_E_OK:
5435 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005436 hlua_lua2smp(stream->hlua.T, -1, smp);
5437 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005438 return 1;
5439
5440 /* yield. */
5441 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005442 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005443 return 0;
5444
5445 /* finished with error. */
5446 case HLUA_E_ERRMSG:
5447 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005448 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
5449 fcn->name, lua_tostring(stream->hlua.T, -1));
Willy Tarreau87b09662015-04-03 00:22:06 +02005450 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005451 return 0;
5452
5453 case HLUA_E_ERR:
5454 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005455 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005456
5457 default:
5458 return 0;
5459 }
5460}
5461
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005462/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5463 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005464 * resume sample-fetches. This function will be called by the sample
5465 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005466 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005467static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5468 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005469{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005470 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005471 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005472 const char *error;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005473
Willy Tarreaube508f12016-03-10 11:47:01 +01005474 if (!stream)
5475 return 0;
5476
Willy Tarreau87b09662015-04-03 00:22:06 +02005477 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005478 * Lua context can be not initialized. This behavior
5479 * permits to save performances because a systematic
5480 * Lua initialization cause 5% performances loss.
5481 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005482 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005483 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005484 return 0;
5485 }
5486
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005487 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005488 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005489
5490 /* The following Lua calls can fail. */
5491 if (!SET_SAFE_LJMP(stream->hlua.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005492 if (lua_type(stream->hlua.T, -1) == LUA_TSTRING)
5493 error = lua_tostring(stream->hlua.T, -1);
5494 else
5495 error = "critical error";
5496 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005497 return 0;
5498 }
5499
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005500 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005501 if (!lua_checkstack(stream->hlua.T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005502 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005503 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005504 return 0;
5505 }
5506
5507 /* Restore the function in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005508 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005509
5510 /* push arguments in the stack. */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005511 if (!hlua_txn_new(stream->hlua.T, stream, smp->px, smp->opt & SMP_OPT_DIR,
5512 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005513 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005514 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005515 return 0;
5516 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005517 stream->hlua.nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005518
5519 /* push keywords in the stack. */
5520 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5521 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005522 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005523 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005524 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005525 return 0;
5526 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005527 hlua_arg2lua(stream->hlua.T, arg_p);
5528 stream->hlua.nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005529 }
5530
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005531 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005532 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005533
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005534 /* At this point the execution is safe. */
5535 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005536 }
5537
5538 /* Execute the function. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005539 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005540 /* finished. */
5541 case HLUA_E_OK:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005542 if (!hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005543 return 0;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005544 /* Convert the returned value in sample. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005545 hlua_lua2smp(stream->hlua.T, -1, smp);
5546 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005547
5548 /* Set the end of execution flag. */
5549 smp->flags &= ~SMP_F_MAY_CHANGE;
5550 return 1;
5551
5552 /* yield. */
5553 case HLUA_E_AGAIN:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005554 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005555 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005556 return 0;
5557
5558 /* finished with error. */
5559 case HLUA_E_ERRMSG:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005560 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005561 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005562 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
5563 fcn->name, lua_tostring(stream->hlua.T, -1));
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005564 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005565 return 0;
5566
5567 case HLUA_E_ERR:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005568 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005569 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005570 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005571
5572 default:
5573 return 0;
5574 }
5575}
5576
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005577/* This function is an LUA binding used for registering
5578 * "sample-conv" functions. It expects a converter name used
5579 * in the haproxy configuration file, and an LUA function.
5580 */
5581__LJMP static int hlua_register_converters(lua_State *L)
5582{
5583 struct sample_conv_kw_list *sck;
5584 const char *name;
5585 int ref;
5586 int len;
5587 struct hlua_function *fcn;
5588
5589 MAY_LJMP(check_args(L, 2, "register_converters"));
5590
5591 /* First argument : converter name. */
5592 name = MAY_LJMP(luaL_checkstring(L, 1));
5593
5594 /* Second argument : lua function. */
5595 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5596
5597 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005598 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005599 if (!sck)
5600 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005601 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005602 if (!fcn)
5603 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5604
5605 /* Fill fcn. */
5606 fcn->name = strdup(name);
5607 if (!fcn->name)
5608 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5609 fcn->function_ref = ref;
5610
5611 /* List head */
5612 sck->list.n = sck->list.p = NULL;
5613
5614 /* converter keyword. */
5615 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005616 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005617 if (!sck->kw[0].kw)
5618 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5619
5620 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5621 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005622 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 +01005623 sck->kw[0].val_args = NULL;
5624 sck->kw[0].in_type = SMP_T_STR;
5625 sck->kw[0].out_type = SMP_T_STR;
5626 sck->kw[0].private = fcn;
5627
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005628 /* Register this new converter */
5629 sample_register_convs(sck);
5630
5631 return 0;
5632}
5633
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005634/* This fucntion is an LUA binding used for registering
5635 * "sample-fetch" functions. It expects a converter name used
5636 * in the haproxy configuration file, and an LUA function.
5637 */
5638__LJMP static int hlua_register_fetches(lua_State *L)
5639{
5640 const char *name;
5641 int ref;
5642 int len;
5643 struct sample_fetch_kw_list *sfk;
5644 struct hlua_function *fcn;
5645
5646 MAY_LJMP(check_args(L, 2, "register_fetches"));
5647
5648 /* First argument : sample-fetch name. */
5649 name = MAY_LJMP(luaL_checkstring(L, 1));
5650
5651 /* Second argument : lua function. */
5652 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5653
5654 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005655 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005656 if (!sfk)
5657 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005658 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005659 if (!fcn)
5660 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5661
5662 /* Fill fcn. */
5663 fcn->name = strdup(name);
5664 if (!fcn->name)
5665 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5666 fcn->function_ref = ref;
5667
5668 /* List head */
5669 sfk->list.n = sfk->list.p = NULL;
5670
5671 /* sample-fetch keyword. */
5672 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005673 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005674 if (!sfk->kw[0].kw)
5675 return luaL_error(L, "lua out of memory error.");
5676
5677 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
5678 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005679 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 +01005680 sfk->kw[0].val_args = NULL;
5681 sfk->kw[0].out_type = SMP_T_STR;
5682 sfk->kw[0].use = SMP_USE_HTTP_ANY;
5683 sfk->kw[0].val = 0;
5684 sfk->kw[0].private = fcn;
5685
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005686 /* Register this new fetch. */
5687 sample_register_fetches(sfk);
5688
5689 return 0;
5690}
5691
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005692/* This function is a wrapper to execute each LUA function declared
5693 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005694 * return ACT_RET_CONT if the processing is finished (with or without
5695 * error) and return ACT_RET_YIELD if the function must be called again
5696 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005697 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005698static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02005699 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005700{
5701 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005702 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005703 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005704 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005705
5706 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01005707 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
5708 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
5709 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
5710 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005711 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005712 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005713 return ACT_RET_CONT;
5714 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005715
Willy Tarreau87b09662015-04-03 00:22:06 +02005716 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005717 * Lua context can be not initialized. This behavior
5718 * permits to save performances because a systematic
5719 * Lua initialization cause 5% performances loss.
5720 */
5721 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005722 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005723 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005724 return ACT_RET_CONT;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005725 }
5726
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005727 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01005728 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005729
5730 /* The following Lua calls can fail. */
5731 if (!SET_SAFE_LJMP(s->hlua.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005732 if (lua_type(s->hlua.T, -1) == LUA_TSTRING)
5733 error = lua_tostring(s->hlua.T, -1);
5734 else
5735 error = "critical error";
5736 SEND_ERR(px, "Lua function '%s': %s.\n",
5737 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005738 return ACT_RET_CONT;
5739 }
5740
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005741 /* Check stack available size. */
5742 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005743 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005744 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005745 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005746 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005747 }
5748
5749 /* Restore the function in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005750 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005751
Willy Tarreau87b09662015-04-03 00:22:06 +02005752 /* Create and and push object stream in the stack. */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005753 if (!hlua_txn_new(s->hlua.T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005754 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005755 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005756 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005757 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005758 }
5759 s->hlua.nargs = 1;
5760
5761 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005762 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005763 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005764 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005765 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005766 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005767 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005768 }
5769 lua_pushstring(s->hlua.T, *arg);
5770 s->hlua.nargs++;
5771 }
5772
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005773 /* Now the execution is safe. */
5774 RESET_SAFE_LJMP(s->hlua.T);
5775
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005776 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005777 s->hlua.max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005778 }
5779
5780 /* Execute the function. */
Willy Tarreau528192d2015-09-27 10:48:01 +02005781 switch (hlua_ctx_resume(&s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005782 /* finished. */
5783 case HLUA_E_OK:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005784 if (!hlua_check_proto(s, dir))
5785 return ACT_RET_ERR;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005786 if (s->hlua.flags & HLUA_STOP)
5787 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005788 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005789
5790 /* yield. */
5791 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005792 /* Set timeout in the required channel. */
5793 if (s->hlua.wake_time != TICK_ETERNITY) {
5794 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005795 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005796 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005797 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005798 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005799 /* Some actions can be wake up when a "write" event
5800 * is detected on a response channel. This is useful
5801 * only for actions targetted on the requests.
5802 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01005803 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005804 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01005805 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005806 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005807 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01005808 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005809 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005810 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005811
5812 /* finished with error. */
5813 case HLUA_E_ERRMSG:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005814 if (!hlua_check_proto(s, dir))
5815 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005816 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005817 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005818 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005819 lua_pop(s->hlua.T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005820 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005821
5822 case HLUA_E_ERR:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005823 if (!hlua_check_proto(s, dir))
5824 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005825 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005826 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005827 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005828
5829 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005830 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005831 }
5832}
5833
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005834struct task *hlua_applet_wakeup(struct task *t)
5835{
5836 struct appctx *ctx = t->context;
5837 struct stream_interface *si = ctx->owner;
5838
5839 /* If the applet is wake up without any expected work, the sheduler
5840 * remove it from the run queue. This flag indicate that the applet
5841 * is waiting for write. If the buffer is full, the main processing
5842 * will send some data and after call the applet, otherwise it call
5843 * the applet ASAP.
5844 */
5845 si_applet_cant_put(si);
5846 appctx_wakeup(ctx);
5847 return NULL;
5848}
5849
5850static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5851{
5852 struct stream_interface *si = ctx->owner;
5853 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5854 struct task *task;
5855 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005856 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005857
5858 HLUA_INIT(hlua);
5859 ctx->ctx.hlua_apptcp.flags = 0;
5860
5861 /* Create task used by signal to wakeup applets. */
5862 task = task_new();
5863 if (!task) {
5864 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
5865 ctx->rule->arg.hlua_rule->fcn.name);
5866 return 0;
5867 }
5868 task->nice = 0;
5869 task->context = ctx;
5870 task->process = hlua_applet_wakeup;
5871 ctx->ctx.hlua_apptcp.task = task;
5872
5873 /* In the execution wrappers linked with a stream, the
5874 * Lua context can be not initialized. This behavior
5875 * permits to save performances because a systematic
5876 * Lua initialization cause 5% performances loss.
5877 */
5878 if (!hlua_ctx_init(hlua, task)) {
5879 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
5880 ctx->rule->arg.hlua_rule->fcn.name);
5881 return 0;
5882 }
5883
5884 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005885 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005886
5887 /* The following Lua calls can fail. */
5888 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005889 if (lua_type(hlua->T, -1) == LUA_TSTRING)
5890 error = lua_tostring(hlua->T, -1);
5891 else
5892 error = "critical error";
5893 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
5894 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005895 RESET_SAFE_LJMP(hlua->T);
5896 return 0;
5897 }
5898
5899 /* Check stack available size. */
5900 if (!lua_checkstack(hlua->T, 1)) {
5901 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5902 ctx->rule->arg.hlua_rule->fcn.name);
5903 RESET_SAFE_LJMP(hlua->T);
5904 return 0;
5905 }
5906
5907 /* Restore the function in the stack. */
5908 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
5909
5910 /* Create and and push object stream in the stack. */
5911 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
5912 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5913 ctx->rule->arg.hlua_rule->fcn.name);
5914 RESET_SAFE_LJMP(hlua->T);
5915 return 0;
5916 }
5917 hlua->nargs = 1;
5918
5919 /* push keywords in the stack. */
5920 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
5921 if (!lua_checkstack(hlua->T, 1)) {
5922 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5923 ctx->rule->arg.hlua_rule->fcn.name);
5924 RESET_SAFE_LJMP(hlua->T);
5925 return 0;
5926 }
5927 lua_pushstring(hlua->T, *arg);
5928 hlua->nargs++;
5929 }
5930
5931 RESET_SAFE_LJMP(hlua->T);
5932
5933 /* Wakeup the applet ASAP. */
5934 si_applet_cant_get(si);
5935 si_applet_cant_put(si);
5936
5937 return 1;
5938}
5939
5940static void hlua_applet_tcp_fct(struct appctx *ctx)
5941{
5942 struct stream_interface *si = ctx->owner;
5943 struct stream *strm = si_strm(si);
5944 struct channel *res = si_ic(si);
5945 struct act_rule *rule = ctx->rule;
5946 struct proxy *px = strm->be;
5947 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5948
5949 /* The applet execution is already done. */
5950 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
5951 return;
5952
5953 /* If the stream is disconnect or closed, ldo nothing. */
5954 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
5955 return;
5956
5957 /* Execute the function. */
5958 switch (hlua_ctx_resume(hlua, 1)) {
5959 /* finished. */
5960 case HLUA_E_OK:
5961 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
5962
5963 /* log time */
5964 strm->logs.tv_request = now;
5965
5966 /* eat the whole request */
5967 bo_skip(si_oc(si), si_ob(si)->o);
5968 res->flags |= CF_READ_NULL;
5969 si_shutr(si);
5970 return;
5971
5972 /* yield. */
5973 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01005974 if (hlua->wake_time != TICK_ETERNITY)
5975 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005976 return;
5977
5978 /* finished with error. */
5979 case HLUA_E_ERRMSG:
5980 /* Display log. */
5981 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
5982 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
5983 lua_pop(hlua->T, 1);
5984 goto error;
5985
5986 case HLUA_E_ERR:
5987 /* Display log. */
5988 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
5989 rule->arg.hlua_rule->fcn.name);
5990 goto error;
5991
5992 default:
5993 goto error;
5994 }
5995
5996error:
5997
5998 /* For all other cases, just close the stream. */
5999 si_shutw(si);
6000 si_shutr(si);
6001 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6002}
6003
6004static void hlua_applet_tcp_release(struct appctx *ctx)
6005{
6006 task_free(ctx->ctx.hlua_apptcp.task);
6007 ctx->ctx.hlua_apptcp.task = NULL;
6008 hlua_ctx_destroy(&ctx->ctx.hlua_apptcp.hlua);
6009}
6010
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006011/* The function returns 1 if the initialisation is complete, 0 if
6012 * an errors occurs and -1 if more data are required for initializing
6013 * the applet.
6014 */
6015static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6016{
6017 struct stream_interface *si = ctx->owner;
6018 struct channel *req = si_oc(si);
6019 struct http_msg *msg;
6020 struct http_txn *txn;
6021 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
6022 char **arg;
6023 struct hdr_ctx hdr;
6024 struct task *task;
6025 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01006026 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006027
6028 /* Wait for a full HTTP request. */
6029 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
6030 if (smp.flags & SMP_F_MAY_CHANGE)
6031 return -1;
6032 return 0;
6033 }
6034 txn = strm->txn;
6035 msg = &txn->req;
6036
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006037 /* We want two things in HTTP mode :
6038 * - enforce server-close mode if we were in keep-alive, so that the
6039 * applet is released after each response ;
6040 * - enable request body transfer to the applet in order to resync
6041 * with the response body.
6042 */
6043 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
6044 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006045
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006046 HLUA_INIT(hlua);
6047 ctx->ctx.hlua_apphttp.left_bytes = -1;
6048 ctx->ctx.hlua_apphttp.flags = 0;
6049
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006050 if (txn->req.flags & HTTP_MSGF_VER_11)
6051 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6052
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006053 /* Create task used by signal to wakeup applets. */
6054 task = task_new();
6055 if (!task) {
6056 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6057 ctx->rule->arg.hlua_rule->fcn.name);
6058 return 0;
6059 }
6060 task->nice = 0;
6061 task->context = ctx;
6062 task->process = hlua_applet_wakeup;
6063 ctx->ctx.hlua_apphttp.task = task;
6064
6065 /* In the execution wrappers linked with a stream, the
6066 * Lua context can be not initialized. This behavior
6067 * permits to save performances because a systematic
6068 * Lua initialization cause 5% performances loss.
6069 */
6070 if (!hlua_ctx_init(hlua, task)) {
6071 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6072 ctx->rule->arg.hlua_rule->fcn.name);
6073 return 0;
6074 }
6075
6076 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006077 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006078
6079 /* The following Lua calls can fail. */
6080 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006081 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6082 error = lua_tostring(hlua->T, -1);
6083 else
6084 error = "critical error";
6085 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6086 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006087 return 0;
6088 }
6089
6090 /* Check stack available size. */
6091 if (!lua_checkstack(hlua->T, 1)) {
6092 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6093 ctx->rule->arg.hlua_rule->fcn.name);
6094 RESET_SAFE_LJMP(hlua->T);
6095 return 0;
6096 }
6097
6098 /* Restore the function in the stack. */
6099 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6100
6101 /* Create and and push object stream in the stack. */
6102 if (!hlua_applet_http_new(hlua->T, ctx)) {
6103 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6104 ctx->rule->arg.hlua_rule->fcn.name);
6105 RESET_SAFE_LJMP(hlua->T);
6106 return 0;
6107 }
6108 hlua->nargs = 1;
6109
6110 /* Look for a 100-continue expected. */
6111 if (msg->flags & HTTP_MSGF_VER_11) {
6112 hdr.idx = 0;
6113 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
6114 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
6115 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
6116 }
6117
6118 /* push keywords in the stack. */
6119 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6120 if (!lua_checkstack(hlua->T, 1)) {
6121 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6122 ctx->rule->arg.hlua_rule->fcn.name);
6123 RESET_SAFE_LJMP(hlua->T);
6124 return 0;
6125 }
6126 lua_pushstring(hlua->T, *arg);
6127 hlua->nargs++;
6128 }
6129
6130 RESET_SAFE_LJMP(hlua->T);
6131
6132 /* Wakeup the applet when data is ready for read. */
6133 si_applet_cant_get(si);
6134
6135 return 1;
6136}
6137
6138static void hlua_applet_http_fct(struct appctx *ctx)
6139{
6140 struct stream_interface *si = ctx->owner;
6141 struct stream *strm = si_strm(si);
6142 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006143 struct act_rule *rule = ctx->rule;
6144 struct proxy *px = strm->be;
6145 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
6146 char *blk1;
6147 int len1;
6148 char *blk2;
6149 int len2;
6150 int ret;
6151
6152 /* If the stream is disconnect or closed, ldo nothing. */
6153 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6154 return;
6155
6156 /* Set the currently running flag. */
6157 if (!HLUA_IS_RUNNING(hlua) &&
6158 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6159
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006160 /* Wait for full HTTP analysys. */
6161 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6162 si_applet_cant_get(si);
6163 return;
6164 }
6165
6166 /* Store the max amount of bytes that we can read. */
6167 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6168
6169 /* We need to flush the request header. This left the body
6170 * for the Lua.
6171 */
6172
6173 /* Read the maximum amount of data avalaible. */
6174 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
6175 if (ret == -1)
6176 return;
6177
6178 /* No data available, ask for more data. */
6179 if (ret == 1)
6180 len2 = 0;
6181 if (ret == 0)
6182 len1 = 0;
6183 if (len1 + len2 < strm->txn->req.eoh + 2) {
6184 si_applet_cant_get(si);
6185 return;
6186 }
6187
6188 /* skip the requests bytes. */
6189 bo_skip(si_oc(si), strm->txn->req.eoh + 2);
6190 }
6191
6192 /* Executes The applet if it is not done. */
6193 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6194
6195 /* Execute the function. */
6196 switch (hlua_ctx_resume(hlua, 1)) {
6197 /* finished. */
6198 case HLUA_E_OK:
6199 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6200 break;
6201
6202 /* yield. */
6203 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006204 if (hlua->wake_time != TICK_ETERNITY)
6205 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006206 return;
6207
6208 /* finished with error. */
6209 case HLUA_E_ERRMSG:
6210 /* Display log. */
6211 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6212 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6213 lua_pop(hlua->T, 1);
6214 goto error;
6215
6216 case HLUA_E_ERR:
6217 /* Display log. */
6218 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6219 rule->arg.hlua_rule->fcn.name);
6220 goto error;
6221
6222 default:
6223 goto error;
6224 }
6225 }
6226
6227 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6228
6229 /* We must send the final chunk. */
6230 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6231 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6232
6233 /* sent last chunk at once. */
6234 ret = bi_putblk(res, "0\r\n\r\n", 5);
6235
6236 /* critical error. */
6237 if (ret == -2 || ret == -3) {
6238 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6239 rule->arg.hlua_rule->fcn.name);
6240 goto error;
6241 }
6242
6243 /* no enough space error. */
6244 if (ret == -1) {
6245 si_applet_cant_put(si);
6246 return;
6247 }
6248
6249 /* set the last chunk sent. */
6250 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6251 }
6252
6253 /* close the connection. */
6254
6255 /* status / log */
6256 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6257 strm->logs.tv_request = now;
6258
6259 /* eat the whole request */
6260 bo_skip(si_oc(si), si_ob(si)->o);
6261 res->flags |= CF_READ_NULL;
6262 si_shutr(si);
6263
6264 return;
6265 }
6266
6267error:
6268
6269 /* If we are in HTTP mode, and we are not send any
6270 * data, return a 500 server error in best effort:
6271 * if there are no room avalaible in the buffer,
6272 * just close the connection.
6273 */
6274 bi_putblk(res, error_500, strlen(error_500));
6275 if (!(strm->flags & SF_ERR_MASK))
6276 strm->flags |= SF_ERR_RESOURCE;
6277 si_shutw(si);
6278 si_shutr(si);
6279 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6280}
6281
6282static void hlua_applet_http_release(struct appctx *ctx)
6283{
6284 task_free(ctx->ctx.hlua_apphttp.task);
6285 ctx->ctx.hlua_apphttp.task = NULL;
6286 hlua_ctx_destroy(&ctx->ctx.hlua_apphttp.hlua);
6287}
6288
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006289/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6290 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006291 *
6292 * This function can fail with an abort() due to an Lua critical error.
6293 * We are in the configuration parsing process of HAProxy, this abort() is
6294 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006295 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006296static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6297 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006298{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006299 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006300 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006301
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006302 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006303 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006304 if (!rule->arg.hlua_rule) {
6305 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006306 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006307 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006308
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006309 /* Memory for arguments. */
6310 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
6311 if (!rule->arg.hlua_rule->args) {
6312 memprintf(err, "out of memory error");
6313 return ACT_RET_PRS_ERR;
6314 }
6315
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006316 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006317 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006318
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006319 /* Expect some arguments */
6320 for (i = 0; i < fcn->nargs; i++) {
6321 if (*args[i+1] == '\0') {
6322 memprintf(err, "expect %d arguments", fcn->nargs);
6323 return ACT_RET_PRS_ERR;
6324 }
6325 rule->arg.hlua_rule->args[i] = strdup(args[i + 1]);
6326 if (!rule->arg.hlua_rule->args[i]) {
6327 memprintf(err, "out of memory error");
6328 return ACT_RET_PRS_ERR;
6329 }
6330 (*cur_arg)++;
6331 }
6332 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006333
Thierry FOURNIER42148732015-09-02 17:17:33 +02006334 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006335 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006336 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006337}
6338
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006339static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6340 struct act_rule *rule, char **err)
6341{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006342 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006343
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006344 /* HTTP applets are forbidden in tcp-request rules.
6345 * HTTP applet request requires everything initilized by
6346 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6347 * The applet will be immediately initilized, but its before
6348 * the call of this analyzer.
6349 */
6350 if (rule->from != ACT_F_HTTP_REQ) {
6351 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6352 return ACT_RET_PRS_ERR;
6353 }
6354
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006355 /* Memory for the rule. */
6356 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6357 if (!rule->arg.hlua_rule) {
6358 memprintf(err, "out of memory error");
6359 return ACT_RET_PRS_ERR;
6360 }
6361
6362 /* Reference the Lua function and store the reference. */
6363 rule->arg.hlua_rule->fcn = *fcn;
6364
6365 /* TODO: later accept arguments. */
6366 rule->arg.hlua_rule->args = NULL;
6367
6368 /* Add applet pointer in the rule. */
6369 rule->applet.obj_type = OBJ_TYPE_APPLET;
6370 rule->applet.name = fcn->name;
6371 rule->applet.init = hlua_applet_http_init;
6372 rule->applet.fct = hlua_applet_http_fct;
6373 rule->applet.release = hlua_applet_http_release;
6374 rule->applet.timeout = hlua_timeout_applet;
6375
6376 return ACT_RET_PRS_OK;
6377}
6378
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006379/* This function is an LUA binding used for registering
6380 * "sample-conv" functions. It expects a converter name used
6381 * in the haproxy configuration file, and an LUA function.
6382 */
6383__LJMP static int hlua_register_action(lua_State *L)
6384{
6385 struct action_kw_list *akl;
6386 const char *name;
6387 int ref;
6388 int len;
6389 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006390 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006391
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006392 /* Initialise the number of expected arguments at 0. */
6393 nargs = 0;
6394
6395 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6396 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006397
6398 /* First argument : converter name. */
6399 name = MAY_LJMP(luaL_checkstring(L, 1));
6400
6401 /* Second argument : environment. */
6402 if (lua_type(L, 2) != LUA_TTABLE)
6403 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6404
6405 /* Third argument : lua function. */
6406 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6407
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006408 /* Fouth argument : number of mandatories arguments expected on the configuration line. */
6409 if (lua_gettop(L) >= 4)
6410 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
6411
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006412 /* browse the second argulent as an array. */
6413 lua_pushnil(L);
6414 while (lua_next(L, 2) != 0) {
6415 if (lua_type(L, -1) != LUA_TSTRING)
6416 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6417
6418 /* Check required environment. Only accepted "http" or "tcp". */
6419 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006420 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006421 if (!akl)
6422 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006423 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006424 if (!fcn)
6425 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6426
6427 /* Fill fcn. */
6428 fcn->name = strdup(name);
6429 if (!fcn->name)
6430 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6431 fcn->function_ref = ref;
6432
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006433 /* Set the expected number od arguments. */
6434 fcn->nargs = nargs;
6435
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006436 /* List head */
6437 akl->list.n = akl->list.p = NULL;
6438
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006439 /* action keyword. */
6440 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006441 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006442 if (!akl->kw[0].kw)
6443 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6444
6445 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6446
6447 akl->kw[0].match_pfx = 0;
6448 akl->kw[0].private = fcn;
6449 akl->kw[0].parse = action_register_lua;
6450
6451 /* select the action registering point. */
6452 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6453 tcp_req_cont_keywords_register(akl);
6454 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6455 tcp_res_cont_keywords_register(akl);
6456 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6457 http_req_keywords_register(akl);
6458 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6459 http_res_keywords_register(akl);
6460 else
6461 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
6462 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6463 "are expected.", lua_tostring(L, -1)));
6464
6465 /* pop the environment string. */
6466 lua_pop(L, 1);
6467 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006468 return ACT_RET_PRS_OK;
6469}
6470
6471static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6472 struct act_rule *rule, char **err)
6473{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006474 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006475
6476 /* Memory for the rule. */
6477 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6478 if (!rule->arg.hlua_rule) {
6479 memprintf(err, "out of memory error");
6480 return ACT_RET_PRS_ERR;
6481 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006482
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006483 /* Reference the Lua function and store the reference. */
6484 rule->arg.hlua_rule->fcn = *fcn;
6485
6486 /* TODO: later accept arguments. */
6487 rule->arg.hlua_rule->args = NULL;
6488
6489 /* Add applet pointer in the rule. */
6490 rule->applet.obj_type = OBJ_TYPE_APPLET;
6491 rule->applet.name = fcn->name;
6492 rule->applet.init = hlua_applet_tcp_init;
6493 rule->applet.fct = hlua_applet_tcp_fct;
6494 rule->applet.release = hlua_applet_tcp_release;
6495 rule->applet.timeout = hlua_timeout_applet;
6496
6497 return 0;
6498}
6499
6500/* This function is an LUA binding used for registering
6501 * "sample-conv" functions. It expects a converter name used
6502 * in the haproxy configuration file, and an LUA function.
6503 */
6504__LJMP static int hlua_register_service(lua_State *L)
6505{
6506 struct action_kw_list *akl;
6507 const char *name;
6508 const char *env;
6509 int ref;
6510 int len;
6511 struct hlua_function *fcn;
6512
6513 MAY_LJMP(check_args(L, 3, "register_service"));
6514
6515 /* First argument : converter name. */
6516 name = MAY_LJMP(luaL_checkstring(L, 1));
6517
6518 /* Second argument : environment. */
6519 env = MAY_LJMP(luaL_checkstring(L, 2));
6520
6521 /* Third argument : lua function. */
6522 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6523
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006524 /* Allocate and fill the sample fetch keyword struct. */
6525 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6526 if (!akl)
6527 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6528 fcn = calloc(1, sizeof(*fcn));
6529 if (!fcn)
6530 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6531
6532 /* Fill fcn. */
6533 len = strlen("<lua.>") + strlen(name) + 1;
6534 fcn->name = calloc(1, len);
6535 if (!fcn->name)
6536 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6537 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6538 fcn->function_ref = ref;
6539
6540 /* List head */
6541 akl->list.n = akl->list.p = NULL;
6542
6543 /* converter keyword. */
6544 len = strlen("lua.") + strlen(name) + 1;
6545 akl->kw[0].kw = calloc(1, len);
6546 if (!akl->kw[0].kw)
6547 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6548
6549 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6550
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01006551 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006552 if (strcmp(env, "tcp") == 0)
6553 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006554 else if (strcmp(env, "http") == 0)
6555 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006556 else
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006557 WILL_LJMP(luaL_error(L, "lua service environment '%s' is unknown. "
6558 "'tcp' or 'http' are expected."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006559
6560 akl->kw[0].match_pfx = 0;
6561 akl->kw[0].private = fcn;
6562
6563 /* End of array. */
6564 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6565
6566 /* Register this new converter */
6567 service_keywords_register(akl);
6568
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006569 return 0;
6570}
6571
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006572/* This function initialises Lua cli handler. It copies the
6573 * arguments in the Lua stack and create channel IO objects.
6574 */
6575static int hlua_cli_parse_fct(char **args, struct appctx *appctx, void *private)
6576{
6577 struct hlua *hlua;
6578 struct hlua_function *fcn;
6579 int i;
6580 const char *error;
6581
6582 hlua = &appctx->ctx.hlua_cli.hlua;
6583 fcn = private;
6584 appctx->private = private;
6585
6586 /* Create task used by signal to wakeup applets.
6587 * We use the same wakeup fonction than the Lua applet_tcp and
6588 * applet_http. It is absolutely compatible.
6589 */
6590 appctx->ctx.hlua_cli.task = task_new();
6591 if (!appctx->ctx.hlua_cli.task) {
6592 SEND_ERR(NULL, "Lua applet tcp '%s': out of memory.\n", fcn->name);
6593 return 0;
6594 }
6595 appctx->ctx.hlua_cli.task->nice = 0;
6596 appctx->ctx.hlua_cli.task->context = appctx;
6597 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
6598
6599 /* Initialises the Lua context */
6600 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
6601 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
6602 return 1;
6603 }
6604
6605 /* The following Lua calls can fail. */
6606 if (!SET_SAFE_LJMP(hlua->T)) {
6607 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6608 error = lua_tostring(hlua->T, -1);
6609 else
6610 error = "critical error";
6611 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
6612 goto error;
6613 }
6614
6615 /* Check stack available size. */
6616 if (!lua_checkstack(hlua->T, 2)) {
6617 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6618 goto error;
6619 }
6620
6621 /* Restore the function in the stack. */
6622 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
6623
6624 /* Once the arguments parsed, the CLI is like an AppletTCP,
6625 * so push AppletTCP in the stack.
6626 * TODO: get_priv() and set_priv() are useless. Maybe we will
6627 * create a new object without these two functions.
6628 */
6629 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
6630 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6631 goto error;
6632 }
6633 hlua->nargs = 1;
6634
6635 /* push keywords in the stack. */
6636 for (i = 0; *args[i]; i++) {
6637 /* Check stack available size. */
6638 if (!lua_checkstack(hlua->T, 1)) {
6639 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6640 goto error;
6641 }
6642 lua_pushstring(hlua->T, args[i]);
6643 hlua->nargs++;
6644 }
6645
6646 /* We must initialize the execution timeouts. */
6647 hlua->max_time = hlua_timeout_session;
6648
6649 /* At this point the execution is safe. */
6650 RESET_SAFE_LJMP(hlua->T);
6651
6652 /* It's ok */
6653 return 0;
6654
6655 /* It's not ok. */
6656error:
6657 RESET_SAFE_LJMP(hlua->T);
6658 hlua_ctx_destroy(hlua);
6659 return 1;
6660}
6661
6662static int hlua_cli_io_handler_fct(struct appctx *appctx)
6663{
6664 struct hlua *hlua;
6665 struct stream_interface *si;
6666 struct hlua_function *fcn;
6667
6668 hlua = &appctx->ctx.hlua_cli.hlua;
6669 si = appctx->owner;
6670 fcn = appctx->private;
6671
6672 /* If the stream is disconnect or closed, ldo nothing. */
6673 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6674 return 1;
6675
6676 /* Execute the function. */
6677 switch (hlua_ctx_resume(hlua, 1)) {
6678
6679 /* finished. */
6680 case HLUA_E_OK:
6681 return 1;
6682
6683 /* yield. */
6684 case HLUA_E_AGAIN:
6685 /* We want write. */
6686 if (HLUA_IS_WAKERESWR(hlua))
6687 si_applet_cant_put(si);
6688 /* Set the timeout. */
6689 if (hlua->wake_time != TICK_ETERNITY)
6690 task_schedule(hlua->task, hlua->wake_time);
6691 return 0;
6692
6693 /* finished with error. */
6694 case HLUA_E_ERRMSG:
6695 /* Display log. */
6696 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
6697 fcn->name, lua_tostring(hlua->T, -1));
6698 lua_pop(hlua->T, 1);
6699 return 1;
6700
6701 case HLUA_E_ERR:
6702 /* Display log. */
6703 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
6704 fcn->name);
6705 return 1;
6706
6707 default:
6708 return 1;
6709 }
6710
6711 return 1;
6712}
6713
6714static void hlua_cli_io_release_fct(struct appctx *appctx)
6715{
6716 struct hlua *hlua;
6717
6718 hlua = &appctx->ctx.hlua_cli.hlua;
6719 hlua_ctx_destroy(hlua);
6720}
6721
6722/* This function is an LUA binding used for registering
6723 * new keywords in the cli. It expects a list of keywords
6724 * which are the "path". It is limited to 5 keywords. A
6725 * description of the command, a function to be executed
6726 * for the parsing and a function for io handlers.
6727 */
6728__LJMP static int hlua_register_cli(lua_State *L)
6729{
6730 struct cli_kw_list *cli_kws;
6731 const char *message;
6732 int ref_io;
6733 int len;
6734 struct hlua_function *fcn;
6735 int index;
6736 int i;
6737
6738 MAY_LJMP(check_args(L, 3, "register_cli"));
6739
6740 /* First argument : an array of maximum 5 keywords. */
6741 if (!lua_istable(L, 1))
6742 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
6743
6744 /* Second argument : string with contextual message. */
6745 message = MAY_LJMP(luaL_checkstring(L, 2));
6746
6747 /* Third and fourth argument : lua function. */
6748 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
6749
6750 /* Allocate and fill the sample fetch keyword struct. */
6751 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
6752 if (!cli_kws)
6753 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6754 fcn = calloc(1, sizeof(*fcn));
6755 if (!fcn)
6756 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6757
6758 /* Fill path. */
6759 index = 0;
6760 lua_pushnil(L);
6761 while(lua_next(L, 1) != 0) {
6762 if (index >= 5)
6763 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
6764 if (lua_type(L, -1) != LUA_TSTRING)
6765 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
6766 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
6767 if (!cli_kws->kw[0].str_kw[index])
6768 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6769 index++;
6770 lua_pop(L, 1);
6771 }
6772
6773 /* Copy help message. */
6774 cli_kws->kw[0].usage = strdup(message);
6775 if (!cli_kws->kw[0].usage)
6776 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6777
6778 /* Fill fcn io handler. */
6779 len = strlen("<lua.cli>") + 1;
6780 for (i = 0; i < index; i++)
6781 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
6782 fcn->name = calloc(1, len);
6783 if (!fcn->name)
6784 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6785 strncat((char *)fcn->name, "<lua.cli", len);
6786 for (i = 0; i < index; i++) {
6787 strncat((char *)fcn->name, ".", len);
6788 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
6789 }
6790 strncat((char *)fcn->name, ">", len);
6791 fcn->function_ref = ref_io;
6792
6793 /* Fill last entries. */
6794 cli_kws->kw[0].private = fcn;
6795 cli_kws->kw[0].parse = hlua_cli_parse_fct;
6796 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
6797 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
6798
6799 /* Register this new converter */
6800 cli_register_kw(cli_kws);
6801
6802 return 0;
6803}
6804
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006805static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
6806 struct proxy *defpx, const char *file, int line,
6807 char **err, unsigned int *timeout)
6808{
6809 const char *error;
6810
6811 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
6812 if (error && *error != '\0') {
6813 memprintf(err, "%s: invalid timeout", args[0]);
6814 return -1;
6815 }
6816 return 0;
6817}
6818
6819static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
6820 struct proxy *defpx, const char *file, int line,
6821 char **err)
6822{
6823 return hlua_read_timeout(args, section_type, curpx, defpx,
6824 file, line, err, &hlua_timeout_session);
6825}
6826
6827static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
6828 struct proxy *defpx, const char *file, int line,
6829 char **err)
6830{
6831 return hlua_read_timeout(args, section_type, curpx, defpx,
6832 file, line, err, &hlua_timeout_task);
6833}
6834
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006835static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
6836 struct proxy *defpx, const char *file, int line,
6837 char **err)
6838{
6839 return hlua_read_timeout(args, section_type, curpx, defpx,
6840 file, line, err, &hlua_timeout_applet);
6841}
6842
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006843static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
6844 struct proxy *defpx, const char *file, int line,
6845 char **err)
6846{
6847 char *error;
6848
6849 hlua_nb_instruction = strtoll(args[1], &error, 10);
6850 if (*error != '\0') {
6851 memprintf(err, "%s: invalid number", args[0]);
6852 return -1;
6853 }
6854 return 0;
6855}
6856
Willy Tarreau32f61e22015-03-18 17:54:59 +01006857static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
6858 struct proxy *defpx, const char *file, int line,
6859 char **err)
6860{
6861 char *error;
6862
6863 if (*(args[1]) == 0) {
6864 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
6865 return -1;
6866 }
6867 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
6868 if (*error != '\0') {
6869 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
6870 return -1;
6871 }
6872 return 0;
6873}
6874
6875
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006876/* This function is called by the main configuration key "lua-load". It loads and
6877 * execute an lua file during the parsing of the HAProxy configuration file. It is
6878 * the main lua entry point.
6879 *
6880 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
6881 * occured, otherwise it returns 0.
6882 *
6883 * In some error case, LUA set an error message in top of the stack. This function
6884 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006885 *
6886 * This function can fail with an abort() due to an Lua critical error.
6887 * We are in the configuration parsing process of HAProxy, this abort() is
6888 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006889 */
6890static int hlua_load(char **args, int section_type, struct proxy *curpx,
6891 struct proxy *defpx, const char *file, int line,
6892 char **err)
6893{
6894 int error;
6895
6896 /* Just load and compile the file. */
6897 error = luaL_loadfile(gL.T, args[1]);
6898 if (error) {
6899 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
6900 lua_pop(gL.T, 1);
6901 return -1;
6902 }
6903
6904 /* If no syntax error where detected, execute the code. */
6905 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
6906 switch (error) {
6907 case LUA_OK:
6908 break;
6909 case LUA_ERRRUN:
6910 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
6911 lua_pop(gL.T, 1);
6912 return -1;
6913 case LUA_ERRMEM:
6914 memprintf(err, "lua out of memory error\n");
6915 return -1;
6916 case LUA_ERRERR:
6917 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
6918 lua_pop(gL.T, 1);
6919 return -1;
6920 case LUA_ERRGCMM:
6921 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
6922 lua_pop(gL.T, 1);
6923 return -1;
6924 default:
6925 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
6926 lua_pop(gL.T, 1);
6927 return -1;
6928 }
6929
6930 return 0;
6931}
6932
6933/* configuration keywords declaration */
6934static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006935 { CFG_GLOBAL, "lua-load", hlua_load },
6936 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
6937 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02006938 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006939 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01006940 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006941 { 0, NULL, NULL },
6942}};
6943
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006944/* This function can fail with an abort() due to an Lua critical error.
6945 * We are in the initialisation process of HAProxy, this abort() is
6946 * tolerated.
6947 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006948int hlua_post_init()
6949{
6950 struct hlua_init_function *init;
6951 const char *msg;
6952 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006953 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006954
Thierry Fournier3d4a6752016-02-19 20:53:30 +01006955 /* Call post initialisation function in safe environement. */
6956 if (!SET_SAFE_LJMP(gL.T)) {
6957 if (lua_type(gL.T, -1) == LUA_TSTRING)
6958 error = lua_tostring(gL.T, -1);
6959 else
6960 error = "critical error";
6961 fprintf(stderr, "Lua post-init: %s.\n", error);
6962 exit(1);
6963 }
6964 hlua_fcn_post_init(gL.T);
6965 RESET_SAFE_LJMP(gL.T);
6966
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006967 list_for_each_entry(init, &hlua_init_functions, l) {
6968 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
6969 ret = hlua_ctx_resume(&gL, 0);
6970 switch (ret) {
6971 case HLUA_E_OK:
6972 lua_pop(gL.T, -1);
6973 return 1;
6974 case HLUA_E_AGAIN:
6975 Alert("lua init: yield not allowed.\n");
6976 return 0;
6977 case HLUA_E_ERRMSG:
6978 msg = lua_tostring(gL.T, -1);
6979 Alert("lua init: %s.\n", msg);
6980 return 0;
6981 case HLUA_E_ERR:
6982 default:
6983 Alert("lua init: unknown runtime error.\n");
6984 return 0;
6985 }
6986 }
6987 return 1;
6988}
6989
Willy Tarreau32f61e22015-03-18 17:54:59 +01006990/* The memory allocator used by the Lua stack. <ud> is a pointer to the
6991 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
6992 * is the previously allocated size or the kind of object in case of a new
6993 * allocation. <nsize> is the requested new size.
6994 */
6995static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
6996{
6997 struct hlua_mem_allocator *zone = ud;
6998
6999 if (nsize == 0) {
7000 /* it's a free */
7001 if (ptr)
7002 zone->allocated -= osize;
7003 free(ptr);
7004 return NULL;
7005 }
7006
7007 if (!ptr) {
7008 /* it's a new allocation */
7009 if (zone->limit && zone->allocated + nsize > zone->limit)
7010 return NULL;
7011
7012 ptr = malloc(nsize);
7013 if (ptr)
7014 zone->allocated += nsize;
7015 return ptr;
7016 }
7017
7018 /* it's a realloc */
7019 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7020 return NULL;
7021
7022 ptr = realloc(ptr, nsize);
7023 if (ptr)
7024 zone->allocated += nsize - osize;
7025 return ptr;
7026}
7027
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007028/* Ithis function can fail with an abort() due to an Lua critical error.
7029 * We are in the initialisation process of HAProxy, this abort() is
7030 * tolerated.
7031 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007032void hlua_init(void)
7033{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007034 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007035 int idx;
7036 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007037 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007038 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007039 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007040#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007041 struct srv_kw *kw;
7042 int tmp_error;
7043 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007044 char *args[] = { /* SSL client configuration. */
7045 "ssl",
7046 "verify",
7047 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007048 NULL
7049 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007050#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007051
Willy Tarreau87b09662015-04-03 00:22:06 +02007052 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007053 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
7054
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007055 /* Register configuration keywords. */
7056 cfg_register_keywords(&cfg_kws);
7057
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007058 /* Init main lua stack. */
7059 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01007060 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007061 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007062 gL.T = luaL_newstate();
7063 hlua_sethlua(&gL);
7064 gL.Tref = LUA_REFNIL;
7065 gL.task = NULL;
7066
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007067 /* From this point, until the end of the initialisation fucntion,
7068 * the Lua function can fail with an abort. We are in the initialisation
7069 * process of HAProxy, this abort() is tolerated.
7070 */
7071
Willy Tarreau32f61e22015-03-18 17:54:59 +01007072 /* change the memory allocators to track memory usage */
7073 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
7074
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007075 /* Initialise lua. */
7076 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007077
Thierry Fournier75933d42016-01-21 09:30:18 +01007078 /* Set safe environment for the initialisation. */
7079 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007080 if (lua_type(gL.T, -1) == LUA_TSTRING)
7081 error_msg = lua_tostring(gL.T, -1);
7082 else
7083 error_msg = "critical error";
7084 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01007085 exit(1);
7086 }
7087
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007088 /*
7089 *
7090 * Create "core" object.
7091 *
7092 */
7093
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01007094 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007095 lua_newtable(gL.T);
7096
7097 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007098 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007099 hlua_class_const_int(gL.T, log_levels[i], i);
7100
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007101 /* Register special functions. */
7102 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007103 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007104 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007105 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007106 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007107 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007108 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007109 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01007110 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007111 hlua_class_function(gL.T, "sleep", hlua_sleep);
7112 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01007113 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
7114 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
7115 hlua_class_function(gL.T, "set_map", hlua_set_map);
7116 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007117 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007118 hlua_class_function(gL.T, "log", hlua_log);
7119 hlua_class_function(gL.T, "Debug", hlua_log_debug);
7120 hlua_class_function(gL.T, "Info", hlua_log_info);
7121 hlua_class_function(gL.T, "Warning", hlua_log_warning);
7122 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02007123 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01007124 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007125
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007126 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007127
7128 /*
7129 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007130 * Register class Map
7131 *
7132 */
7133
7134 /* This table entry is the object "Map" base. */
7135 lua_newtable(gL.T);
7136
7137 /* register pattern types. */
7138 for (i=0; i<PAT_MATCH_NUM; i++)
7139 hlua_class_const_int(gL.T, pat_match_names[i], i);
7140
7141 /* register constructor. */
7142 hlua_class_function(gL.T, "new", hlua_map_new);
7143
7144 /* Create and fill the metatable. */
7145 lua_newtable(gL.T);
7146
7147 /* Create and fille the __index entry. */
7148 lua_pushstring(gL.T, "__index");
7149 lua_newtable(gL.T);
7150
7151 /* Register . */
7152 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
7153 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
7154
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007155 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007156
Thierry Fournier45e78d72016-02-19 18:34:46 +01007157 /* Register previous table in the registry with reference and named entry.
7158 * The function hlua_register_metatable() pops the stack, so we
7159 * previously create a copy of the table.
7160 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007161 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007162 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007163
7164 /* Assign the metatable to the mai Map object. */
7165 lua_setmetatable(gL.T, -2);
7166
7167 /* Set a name to the table. */
7168 lua_setglobal(gL.T, "Map");
7169
7170 /*
7171 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007172 * Register class Channel
7173 *
7174 */
7175
7176 /* Create and fill the metatable. */
7177 lua_newtable(gL.T);
7178
7179 /* Create and fille the __index entry. */
7180 lua_pushstring(gL.T, "__index");
7181 lua_newtable(gL.T);
7182
7183 /* Register . */
7184 hlua_class_function(gL.T, "get", hlua_channel_get);
7185 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7186 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7187 hlua_class_function(gL.T, "set", hlua_channel_set);
7188 hlua_class_function(gL.T, "append", hlua_channel_append);
7189 hlua_class_function(gL.T, "send", hlua_channel_send);
7190 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7191 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7192 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007193 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007194
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007195 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007196
7197 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007198 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007199
7200 /*
7201 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007202 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007203 *
7204 */
7205
7206 /* Create and fill the metatable. */
7207 lua_newtable(gL.T);
7208
7209 /* Create and fille the __index entry. */
7210 lua_pushstring(gL.T, "__index");
7211 lua_newtable(gL.T);
7212
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007213 /* Browse existing fetches and create the associated
7214 * object method.
7215 */
7216 sf = NULL;
7217 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7218
7219 /* Dont register the keywork if the arguments check function are
7220 * not safe during the runtime.
7221 */
7222 if ((sf->val_args != NULL) &&
7223 (sf->val_args != val_payload_lv) &&
7224 (sf->val_args != val_hdr))
7225 continue;
7226
7227 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7228 * by an underscore.
7229 */
7230 strncpy(trash.str, sf->kw, trash.size);
7231 trash.str[trash.size - 1] = '\0';
7232 for (p = trash.str; *p; p++)
7233 if (*p == '.' || *p == '-' || *p == '+')
7234 *p = '_';
7235
7236 /* Register the function. */
7237 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007238 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007239 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007240 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007241 }
7242
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007243 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007244
7245 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007246 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007247
7248 /*
7249 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007250 * Register class Converters
7251 *
7252 */
7253
7254 /* Create and fill the metatable. */
7255 lua_newtable(gL.T);
7256
7257 /* Create and fill the __index entry. */
7258 lua_pushstring(gL.T, "__index");
7259 lua_newtable(gL.T);
7260
7261 /* Browse existing converters and create the associated
7262 * object method.
7263 */
7264 sc = NULL;
7265 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7266 /* Dont register the keywork if the arguments check function are
7267 * not safe during the runtime.
7268 */
7269 if (sc->val_args != NULL)
7270 continue;
7271
7272 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7273 * by an underscore.
7274 */
7275 strncpy(trash.str, sc->kw, trash.size);
7276 trash.str[trash.size - 1] = '\0';
7277 for (p = trash.str; *p; p++)
7278 if (*p == '.' || *p == '-' || *p == '+')
7279 *p = '_';
7280
7281 /* Register the function. */
7282 lua_pushstring(gL.T, trash.str);
7283 lua_pushlightuserdata(gL.T, sc);
7284 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007285 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007286 }
7287
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007288 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007289
7290 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007291 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007292
7293 /*
7294 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007295 * Register class HTTP
7296 *
7297 */
7298
7299 /* Create and fill the metatable. */
7300 lua_newtable(gL.T);
7301
7302 /* Create and fille the __index entry. */
7303 lua_pushstring(gL.T, "__index");
7304 lua_newtable(gL.T);
7305
7306 /* Register Lua functions. */
7307 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7308 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7309 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7310 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7311 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7312 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7313 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7314 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7315 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7316 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7317
7318 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7319 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7320 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7321 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7322 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7323 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007324 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007325
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007326 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007327
7328 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007329 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007330
7331 /*
7332 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007333 * Register class AppletTCP
7334 *
7335 */
7336
7337 /* Create and fill the metatable. */
7338 lua_newtable(gL.T);
7339
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007340 /* Create and fille the __index entry. */
7341 lua_pushstring(gL.T, "__index");
7342 lua_newtable(gL.T);
7343
7344 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01007345 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7346 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7347 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7348 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7349 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007350 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
7351 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
7352 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007353
7354 lua_settable(gL.T, -3);
7355
7356 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007357 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007358
7359 /*
7360 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007361 * Register class AppletHTTP
7362 *
7363 */
7364
7365 /* Create and fill the metatable. */
7366 lua_newtable(gL.T);
7367
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007368 /* Create and fille the __index entry. */
7369 lua_pushstring(gL.T, "__index");
7370 lua_newtable(gL.T);
7371
7372 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007373 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7374 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007375 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
7376 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
7377 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007378 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7379 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7380 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7381 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7382 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7383 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7384
7385 lua_settable(gL.T, -3);
7386
7387 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007388 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007389
7390 /*
7391 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007392 * Register class TXN
7393 *
7394 */
7395
7396 /* Create and fill the metatable. */
7397 lua_newtable(gL.T);
7398
7399 /* Create and fille the __index entry. */
7400 lua_pushstring(gL.T, "__index");
7401 lua_newtable(gL.T);
7402
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007403 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01007404 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7405 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007406 hlua_class_function(gL.T, "set_var", hlua_set_var);
Christopher Faulet85d79c92016-11-09 16:54:56 +01007407 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007408 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007409 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007410 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
7411 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7412 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007413 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7414 hlua_class_function(gL.T, "log", hlua_txn_log);
7415 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7416 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7417 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7418 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007419
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007420 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007421
7422 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007423 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007424
7425 /*
7426 *
7427 * Register class Socket
7428 *
7429 */
7430
7431 /* Create and fill the metatable. */
7432 lua_newtable(gL.T);
7433
7434 /* Create and fille the __index entry. */
7435 lua_pushstring(gL.T, "__index");
7436 lua_newtable(gL.T);
7437
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007438#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007439 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007440#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007441 hlua_class_function(gL.T, "connect", hlua_socket_connect);
7442 hlua_class_function(gL.T, "send", hlua_socket_send);
7443 hlua_class_function(gL.T, "receive", hlua_socket_receive);
7444 hlua_class_function(gL.T, "close", hlua_socket_close);
7445 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
7446 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
7447 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
7448 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
7449
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007450 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007451
7452 /* Register the garbage collector entry. */
7453 lua_pushstring(gL.T, "__gc");
7454 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007455 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007456
7457 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007458 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007459
7460 /* Proxy and server configuration initialisation. */
7461 memset(&socket_proxy, 0, sizeof(socket_proxy));
7462 init_new_proxy(&socket_proxy);
7463 socket_proxy.parent = NULL;
7464 socket_proxy.last_change = now.tv_sec;
7465 socket_proxy.id = "LUA-SOCKET";
7466 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
7467 socket_proxy.maxconn = 0;
7468 socket_proxy.accept = NULL;
7469 socket_proxy.options2 |= PR_O2_INDEPSTR;
7470 socket_proxy.srv = NULL;
7471 socket_proxy.conn_retries = 0;
7472 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
7473
7474 /* Init TCP server: unchanged parameters */
7475 memset(&socket_tcp, 0, sizeof(socket_tcp));
7476 socket_tcp.next = NULL;
7477 socket_tcp.proxy = &socket_proxy;
7478 socket_tcp.obj_type = OBJ_TYPE_SERVER;
7479 LIST_INIT(&socket_tcp.actconns);
7480 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007481 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007482 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007483 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007484 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
7485 socket_tcp.last_change = 0;
7486 socket_tcp.id = "LUA-TCP-CONN";
7487 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7488 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7489 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
7490
7491 /* XXX: Copy default parameter from default server,
7492 * but the default server is not initialized.
7493 */
7494 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
7495 socket_tcp.minconn = socket_proxy.defsrv.minconn;
7496 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
7497 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
7498 socket_tcp.onerror = socket_proxy.defsrv.onerror;
7499 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7500 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
7501 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7502 socket_tcp.uweight = socket_proxy.defsrv.iweight;
7503 socket_tcp.iweight = socket_proxy.defsrv.iweight;
7504
7505 socket_tcp.check.status = HCHK_STATUS_INI;
7506 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
7507 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
7508 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
7509 socket_tcp.check.server = &socket_tcp;
7510
7511 socket_tcp.agent.status = HCHK_STATUS_INI;
7512 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
7513 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
7514 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
7515 socket_tcp.agent.server = &socket_tcp;
7516
7517 socket_tcp.xprt = &raw_sock;
7518
7519#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007520 /* Init TCP server: unchanged parameters */
7521 memset(&socket_ssl, 0, sizeof(socket_ssl));
7522 socket_ssl.next = NULL;
7523 socket_ssl.proxy = &socket_proxy;
7524 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7525 LIST_INIT(&socket_ssl.actconns);
7526 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007527 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007528 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007529 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007530 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
7531 socket_ssl.last_change = 0;
7532 socket_ssl.id = "LUA-SSL-CONN";
7533 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7534 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7535 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7536
7537 /* XXX: Copy default parameter from default server,
7538 * but the default server is not initialized.
7539 */
7540 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7541 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7542 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7543 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7544 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7545 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7546 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7547 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7548 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7549 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7550
7551 socket_ssl.check.status = HCHK_STATUS_INI;
7552 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7553 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7554 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7555 socket_ssl.check.server = &socket_ssl;
7556
7557 socket_ssl.agent.status = HCHK_STATUS_INI;
7558 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7559 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7560 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7561 socket_ssl.agent.server = &socket_ssl;
7562
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007563 socket_ssl.use_ssl = 1;
7564 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007565
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007566 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007567 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7568 /*
7569 *
7570 * If the keyword is not known, we can search in the registered
7571 * server keywords. This is usefull to configure special SSL
7572 * features like client certificates and ssl_verify.
7573 *
7574 */
7575 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7576 if (tmp_error != 0) {
7577 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7578 abort(); /* This must be never arrives because the command line
7579 not editable by the user. */
7580 }
7581 idx += kw->skip;
7582 }
7583 }
7584
7585 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007586 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007587#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01007588
7589 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007590}