blob: f444c1573f28d0498105c410328151d5602f7a63 [file] [log] [blame]
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001#include <sys/socket.h>
2
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01003#include <lauxlib.h>
4#include <lua.h>
5#include <lualib.h>
6
Cyril Bontédc0306e2015-03-02 00:08:40 +01007#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
8#error "Requires Lua 5.2 or later."
9#endif
10
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011#include <ebpttree.h>
12
13#include <common/cfgparse.h>
14
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010015#include <types/connection.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010016#include <types/hlua.h>
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010017#include <types/proto_tcp.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010018#include <types/proxy.h>
19
Thierry FOURNIER55da1652015-01-23 11:36:30 +010020#include <proto/arg.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010021#include <proto/channel.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010022#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010023#include <proto/hlua.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010024#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010025#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010026#include <proto/payload.h>
27#include <proto/proto_http.h>
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010028#include <proto/proto_tcp.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010029#include <proto/raw_sock.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010030#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010031#include <proto/server.h>
32#include <proto/session.h>
33#include <proto/ssl_sock.h>
34#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010035#include <proto/task.h>
36
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010037/* Lua uses longjmp to perform yield or throwing errors. This
38 * macro is used only for identifying the function that can
39 * not return because a longjmp is executed.
40 * __LJMP marks a prototype of hlua file that can use longjmp.
41 * WILL_LJMP() marks an lua function that will use longjmp.
42 * MAY_LJMP() marks an lua function that may use longjmp.
43 */
44#define __LJMP
45#define WILL_LJMP(func) func
46#define MAY_LJMP(func) func
47
Thierry FOURNIER380d0932015-01-23 14:27:52 +010048/* The main Lua execution context. */
49struct hlua gL;
50
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010051/* This is the memory pool containing all the signal structs. These
52 * struct are used to store each requiered signal between two tasks.
53 */
54struct pool_head *pool2_hlua_com;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +010055struct pool_head *pool2_hlua_sleep;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010056
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010057/* Used for Socket connection. */
58static struct proxy socket_proxy;
59static struct server socket_tcp;
60#ifdef USE_OPENSSL
61static struct server socket_ssl;
62#endif
63
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010064/* List head of the function called at the initialisation time. */
65struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
66
Thierry FOURNIER380d0932015-01-23 14:27:52 +010067/* Store the fast lua context for coroutines. This tree uses the
68 * Lua stack pointer value as indexed entry, and store the associated
69 * hlua context.
70 */
71struct eb_root hlua_ctx = EB_ROOT_UNIQUE;
72
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010073/* The following variables contains the reference of the different
74 * Lua classes. These references are useful for identify metadata
75 * associated with an object.
76 */
77static int class_core_ref;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010078static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010079static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010080static int class_channel_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010081
Thierry FOURNIERbd413492015-03-03 16:52:26 +010082/* Global Lua execution timeout. By default Lua, execution linked
83 * with session (actions, sample-fetches and converters) have a
84 * short timeout. Lua linked with tasks doesn't have a timeout
85 * because a task may remain alive during all the haproxy execution.
86 */
87static unsigned int hlua_timeout_session = 4000; /* session timeout. */
88static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
89
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010090/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
91 * it is used for preventing infinite loops.
92 *
93 * I test the scheer with an infinite loop containing one incrementation
94 * and one test. I run this loop between 10 seconds, I raise a ceil of
95 * 710M loops from one interrupt each 9000 instructions, so I fix the value
96 * to one interrupt each 10 000 instructions.
97 *
98 * configured | Number of
99 * instructions | loops executed
100 * between two | in milions
101 * forced yields |
102 * ---------------+---------------
103 * 10 | 160
104 * 500 | 670
105 * 1000 | 680
106 * 5000 | 700
107 * 7000 | 700
108 * 8000 | 700
109 * 9000 | 710 <- ceil
110 * 10000 | 710
111 * 100000 | 710
112 * 1000000 | 710
113 *
114 */
115static unsigned int hlua_nb_instruction = 10000;
116
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100117/* These functions converts types between HAProxy internal args or
118 * sample and LUA types. Another function permits to check if the
119 * LUA stack contains arguments according with an required ARG_T
120 * format.
121 */
122static int hlua_arg2lua(lua_State *L, const struct arg *arg);
123static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
124__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp, unsigned int mask);
125static int hlua_smp2lua(lua_State *L, const struct sample *smp);
126static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
127
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100128/* Used to check an Lua function type in the stack. It creates and
129 * returns a reference of the function. This function throws an
130 * error if the rgument is not a "function".
131 */
132__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
133{
134 if (!lua_isfunction(L, argno)) {
135 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
136 WILL_LJMP(luaL_argerror(L, argno, msg));
137 }
138 lua_pushvalue(L, argno);
139 return luaL_ref(L, LUA_REGISTRYINDEX);
140}
141
142/* The three following functions are useful for adding entries
143 * in a table. These functions takes a string and respectively an
144 * integer, a string or a function and add it to the table in the
145 * top of the stack.
146 *
147 * These functions throws an error if no more stack size is
148 * available.
149 */
150__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
151 unsigned int value)
152{
153 if (!lua_checkstack(L, 2))
154 WILL_LJMP(luaL_error(L, "full stack"));
155 lua_pushstring(L, name);
156 lua_pushunsigned(L, value);
157 lua_settable(L, -3);
158}
159__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
160 const char *value)
161{
162 if (!lua_checkstack(L, 2))
163 WILL_LJMP(luaL_error(L, "full stack"));
164 lua_pushstring(L, name);
165 lua_pushstring(L, value);
166 lua_settable(L, -3);
167}
168__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
169 int (*function)(lua_State *L))
170{
171 if (!lua_checkstack(L, 2))
172 WILL_LJMP(luaL_error(L, "full stack"));
173 lua_pushstring(L, name);
174 lua_pushcclosure(L, function, 0);
175 lua_settable(L, -3);
176}
177
178/* This function check the number of arguments available in the
179 * stack. If the number of arguments available is not the same
180 * then <nb> an error is throwed.
181 */
182__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
183{
184 if (lua_gettop(L) == nb)
185 return;
186 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
187}
188
189/* Return true if the data in stack[<ud>] is an object of
190 * type <class_ref>.
191 */
192static int hlua_udataistype(lua_State *L, int ud, int class_ref)
193{
194 void *p = lua_touserdata(L, ud);
195 if (!p)
196 return 0;
197
198 if (!lua_getmetatable(L, ud))
199 return 0;
200
201 lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
202 if (!lua_rawequal(L, -1, -2)) {
203 lua_pop(L, 2);
204 return 0;
205 }
206
207 lua_pop(L, 2);
208 return 1;
209}
210
211/* Return an object of the expected type, or throws an error. */
212__LJMP static void *hlua_checkudata(lua_State *L, int ud, int class_ref)
213{
214 if (!hlua_udataistype(L, ud, class_ref))
215 WILL_LJMP(luaL_argerror(L, 1, NULL));
216 return lua_touserdata(L, ud);
217}
218
219/* This fucntion push an error string prefixed by the file name
220 * and the line number where the error is encountered.
221 */
222static int hlua_pusherror(lua_State *L, const char *fmt, ...)
223{
224 va_list argp;
225 va_start(argp, fmt);
226 luaL_where(L, 1);
227 lua_pushvfstring(L, fmt, argp);
228 va_end(argp);
229 lua_concat(L, 2);
230 return 1;
231}
232
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100233/* This function register a new signal. "lua" is the current lua
234 * execution context. It contains a pointer to the associated task.
235 * "link" is a list head attached to an other task that must be wake
236 * the lua task if an event occurs. This is useful with external
237 * events like TCP I/O or sleep functions. This funcion allocate
238 * memory for the signal.
239 */
240static int hlua_com_new(struct hlua *lua, struct list *link)
241{
242 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
243 if (!com)
244 return 0;
245 LIST_ADDQ(&lua->com, &com->purge_me);
246 LIST_ADDQ(link, &com->wake_me);
247 com->task = lua->task;
248 return 1;
249}
250
251/* This function purge all the pending signals when the LUA execution
252 * is finished. This prevent than a coprocess try to wake a deleted
253 * task. This function remove the memory associated to the signal.
254 */
255static void hlua_com_purge(struct hlua *lua)
256{
257 struct hlua_com *com, *back;
258
259 /* Delete all pending communication signals. */
260 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
261 LIST_DEL(&com->purge_me);
262 LIST_DEL(&com->wake_me);
263 pool_free2(pool2_hlua_com, com);
264 }
265}
266
267/* This function sends signals. It wakes all the tasks attached
268 * to a list head, and remove the signal, and free the used
269 * memory.
270 */
271static void hlua_com_wake(struct list *wake)
272{
273 struct hlua_com *com, *back;
274
275 /* Wake task and delete all pending communication signals. */
276 list_for_each_entry_safe(com, back, wake, wake_me) {
277 LIST_DEL(&com->purge_me);
278 LIST_DEL(&com->wake_me);
279 task_wakeup(com->task, TASK_WOKEN_MSG);
280 pool_free2(pool2_hlua_com, com);
281 }
282}
283
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100284/* This functions is used with sample fetch and converters. It
285 * converts the HAProxy configuration argument in a lua stack
286 * values.
287 *
288 * It takes an array of "arg", and each entry of the array is
289 * converted and pushed in the LUA stack.
290 */
291static int hlua_arg2lua(lua_State *L, const struct arg *arg)
292{
293 switch (arg->type) {
294 case ARGT_SINT:
295 lua_pushinteger(L, arg->data.sint);
296 break;
297
298 case ARGT_UINT:
299 case ARGT_TIME:
300 case ARGT_SIZE:
301 lua_pushunsigned(L, arg->data.sint);
302 break;
303
304 case ARGT_STR:
305 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
306 break;
307
308 case ARGT_IPV4:
309 case ARGT_IPV6:
310 case ARGT_MSK4:
311 case ARGT_MSK6:
312 case ARGT_FE:
313 case ARGT_BE:
314 case ARGT_TAB:
315 case ARGT_SRV:
316 case ARGT_USR:
317 case ARGT_MAP:
318 default:
319 lua_pushnil(L);
320 break;
321 }
322 return 1;
323}
324
325/* This function take one entrie in an LUA stack at the index "ud",
326 * and try to convert it in an HAProxy argument entry. This is useful
327 * with sample fetch wrappers. The input arguments are gived to the
328 * lua wrapper and converted as arg list by thi function.
329 */
330static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
331{
332 switch (lua_type(L, ud)) {
333
334 case LUA_TNUMBER:
335 case LUA_TBOOLEAN:
336 arg->type = ARGT_SINT;
337 arg->data.sint = lua_tointeger(L, ud);
338 break;
339
340 case LUA_TSTRING:
341 arg->type = ARGT_STR;
342 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
343 break;
344
345 case LUA_TUSERDATA:
346 case LUA_TNIL:
347 case LUA_TTABLE:
348 case LUA_TFUNCTION:
349 case LUA_TTHREAD:
350 case LUA_TLIGHTUSERDATA:
351 arg->type = ARGT_SINT;
352 arg->data.uint = 0;
353 break;
354 }
355 return 1;
356}
357
358/* the following functions are used to convert a struct sample
359 * in Lua type. This useful to convert the return of the
360 * fetchs or converters.
361 */
362static int hlua_smp2lua(lua_State *L, const struct sample *smp)
363{
364 switch (smp->type) {
365 case SMP_T_SINT:
366 lua_pushinteger(L, smp->data.sint);
367 break;
368
369 case SMP_T_BOOL:
370 case SMP_T_UINT:
371 lua_pushunsigned(L, smp->data.uint);
372 break;
373
374 case SMP_T_BIN:
375 case SMP_T_STR:
376 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
377 break;
378
379 case SMP_T_METH:
380 switch (smp->data.meth.meth) {
381 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
382 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
383 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
384 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
385 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
386 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
387 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
388 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
389 case HTTP_METH_OTHER:
390 lua_pushlstring(L, smp->data.meth.str.str, smp->data.meth.str.len);
391 break;
392 default:
393 lua_pushnil(L);
394 break;
395 }
396 break;
397
398 case SMP_T_IPV4:
399 case SMP_T_IPV6:
400 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
401 default:
402 lua_pushnil(L);
403 break;
404 }
405 return 1;
406}
407
408/* the following functions are used to convert an Lua type in a
409 * struct sample. This is useful to provide data from a converter
410 * to the LUA code.
411 */
412static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
413{
414 switch (lua_type(L, ud)) {
415
416 case LUA_TNUMBER:
417 smp->type = SMP_T_SINT;
418 smp->data.sint = lua_tointeger(L, ud);
419 break;
420
421
422 case LUA_TBOOLEAN:
423 smp->type = SMP_T_BOOL;
424 smp->data.uint = lua_toboolean(L, ud);
425 break;
426
427 case LUA_TSTRING:
428 smp->type = SMP_T_STR;
429 smp->flags |= SMP_F_CONST;
430 smp->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.str.len);
431 break;
432
433 case LUA_TUSERDATA:
434 case LUA_TNIL:
435 case LUA_TTABLE:
436 case LUA_TFUNCTION:
437 case LUA_TTHREAD:
438 case LUA_TLIGHTUSERDATA:
439 smp->type = SMP_T_BOOL;
440 smp->data.uint = 0;
441 break;
442 }
443 return 1;
444}
445
446/* This function check the "argp" builded by another conversion function
447 * is in accord with the expected argp defined by the "mask". The fucntion
448 * returns true or false. It can be adjust the types if there compatibles.
449 */
450__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp, unsigned int mask)
451{
452 int min_arg;
453 int idx;
454
455 idx = 0;
456 min_arg = ARGM(mask);
457 mask >>= ARGM_BITS;
458
459 while (1) {
460
461 /* Check oversize. */
462 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100463 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100464 }
465
466 /* Check for mandatory arguments. */
467 if (argp[idx].type == ARGT_STOP) {
468 if (idx + 1 < min_arg)
469 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
470 return 0;
471 }
472
473 /* Check for exceed the number of requiered argument. */
474 if ((mask & ARGT_MASK) == ARGT_STOP &&
475 argp[idx].type != ARGT_STOP) {
476 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
477 }
478
479 if ((mask & ARGT_MASK) == ARGT_STOP &&
480 argp[idx].type == ARGT_STOP) {
481 return 0;
482 }
483
484 /* Compatibility mask. */
485 switch (argp[idx].type) {
486 case ARGT_SINT:
487 switch (mask & ARGT_MASK) {
488 case ARGT_UINT: argp[idx].type = mask & ARGT_MASK; break;
489 case ARGT_TIME: argp[idx].type = mask & ARGT_MASK; break;
490 case ARGT_SIZE: argp[idx].type = mask & ARGT_MASK; break;
491 }
492 break;
493 }
494
495 /* Check for type of argument. */
496 if ((mask & ARGT_MASK) != argp[idx].type) {
497 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
498 arg_type_names[(mask & ARGT_MASK)],
499 arg_type_names[argp[idx].type & ARGT_MASK]);
500 WILL_LJMP(luaL_argerror(L, first + idx, msg));
501 }
502
503 /* Next argument. */
504 mask >>= ARGT_BITS;
505 idx++;
506 }
507}
508
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100509/*
510 * The following functions are used to make correspondance between the the
511 * executed lua pointer and the "struct hlua *" that contain the context.
512 * They run with the tree head "hlua_ctx", they just perform lookup in the
513 * tree.
514 *
515 * - hlua_gethlua : return the hlua context associated with an lua_State.
516 * - hlua_delhlua : remove the association between hlua context and lua_state.
517 * - hlua_sethlua : create the association between hlua context and lua_state.
518 */
519static inline struct hlua *hlua_gethlua(lua_State *L)
520{
521 struct ebpt_node *node;
522
523 node = ebpt_lookup(&hlua_ctx, L);
524 if (!node)
525 return NULL;
526 return ebpt_entry(node, struct hlua, node);
527}
528static inline void hlua_delhlua(struct hlua *hlua)
529{
530 if (hlua->node.key)
531 ebpt_delete(&hlua->node);
532}
533static inline void hlua_sethlua(struct hlua *hlua)
534{
535 hlua->node.key = hlua->T;
536 ebpt_insert(&hlua_ctx, &hlua->node);
537}
538
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100539/* This function just ensure that the yield will be always
540 * returned with a timeout and permit to set some flags
541 */
542__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100543 lua_CFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100544{
545 struct hlua *hlua = hlua_gethlua(L);
546
547 /* Set the wake timeout. If timeout is required, we set
548 * the expiration time.
549 */
550 hlua->wake_time = timeout;
551 if (hlua->wake_time == TICK_ETERNITY)
552 hlua->wake_time = hlua->expire;
553
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100554 hlua->flags |= flags;
555
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100556 /* Process the yield. */
557 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
558}
559
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100560/* This function initialises the Lua environment stored in the session.
561 * It must be called at the start of the session. This function creates
562 * an LUA coroutine. It can not be use to crete the main LUA context.
563 */
564int hlua_ctx_init(struct hlua *lua, struct task *task)
565{
566 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100567 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100568 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100569 lua->T = lua_newthread(gL.T);
570 if (!lua->T) {
571 lua->Tref = LUA_REFNIL;
572 return 0;
573 }
574 hlua_sethlua(lua);
575 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
576 lua->task = task;
577 return 1;
578}
579
580/* Used to destroy the Lua coroutine when the attached session or task
581 * is destroyed. The destroy also the memory context. The struct "lua"
582 * is not freed.
583 */
584void hlua_ctx_destroy(struct hlua *lua)
585{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100586 if (!lua->T)
587 return;
588
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100589 /* Remove context. */
590 hlua_delhlua(lua);
591
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100592 /* Purge all the pending signals. */
593 hlua_com_purge(lua);
594
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100595 /* The thread is garbage collected by Lua. */
596 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
597 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
598}
599
600/* This function is used to restore the Lua context when a coroutine
601 * fails. This function copy the common memory between old coroutine
602 * and the new coroutine. The old coroutine is destroyed, and its
603 * replaced by the new coroutine.
604 * If the flag "keep_msg" is set, the last entry of the old is assumed
605 * as string error message and it is copied in the new stack.
606 */
607static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
608{
609 lua_State *T;
610 int new_ref;
611
612 /* Renew the main LUA stack doesn't have sense. */
613 if (lua == &gL)
614 return 0;
615
616 /* Remove context. */
617 hlua_delhlua(lua);
618
619 /* New Lua coroutine. */
620 T = lua_newthread(gL.T);
621 if (!T)
622 return 0;
623
624 /* Copy last error message. */
625 if (keep_msg)
626 lua_xmove(lua->T, T, 1);
627
628 /* Copy data between the coroutines. */
629 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
630 lua_xmove(lua->T, T, 1);
631 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
632
633 /* Destroy old data. */
634 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
635
636 /* The thread is garbage collected by Lua. */
637 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
638
639 /* Fill the struct with the new coroutine values. */
640 lua->Mref = new_ref;
641 lua->T = T;
642 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
643
644 /* Set context. */
645 hlua_sethlua(lua);
646
647 return 1;
648}
649
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100650void hlua_hook(lua_State *L, lua_Debug *ar)
651{
652 hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD);
653}
654
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100655/* This function start or resumes the Lua stack execution. If the flag
656 * "yield_allowed" if no set and the LUA stack execution returns a yield
657 * The function return an error.
658 *
659 * The function can returns 4 values:
660 * - HLUA_E_OK : The execution is terminated without any errors.
661 * - HLUA_E_AGAIN : The execution must continue at the next associated
662 * task wakeup.
663 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
664 * the top of the stack.
665 * - HLUA_E_ERR : An error has occured without error message.
666 *
667 * If an error occured, the stack is renewed and it is ready to run new
668 * LUA code.
669 */
670static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
671{
672 int ret;
673 const char *msg;
674
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100675 HLUA_SET_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100676
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100677resume_execution:
678
679 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
680 * instructions. it is used for preventing infinite loops.
681 */
682 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
683
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100684 /* Call the function. */
685 ret = lua_resume(lua->T, gL.T, lua->nargs);
686 switch (ret) {
687
688 case LUA_OK:
689 ret = HLUA_E_OK;
690 break;
691
692 case LUA_YIELD:
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100693 /* If the yield id received join to the flag HLUA_CTRLYIELD,
694 * we check the Lua timeout execution.
695 */
696 if (HLUA_IS_CTRLYIELDING(lua)) {
697 /* If the timeout is expired, we break the Lua execution. */
698 if (tick_is_expired(lua->expire, now_ms)) {
699 lua_settop(lua->T, 0); /* Empty the stack. */
700 if (!lua_checkstack(lua->T, 1)) {
701 ret = HLUA_E_ERR;
702 break;
703 }
704 lua_pushfstring(lua->T, "execution timeout");
705 ret = HLUA_E_ERRMSG;
706 break;
707 }
708 /* if the general yield is not allowed or if no task were
709 * associated this the current Lua execution coroutine, we
710 * resume the execution.
711 */
712 if (!yield_allowed || !lua->task)
713 goto resume_execution;
714 /* Re-schedule the task. */
715 task_wakeup(lua->task, TASK_WOKEN_MSG);
716
717 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100718 if (!yield_allowed) {
719 lua_settop(lua->T, 0); /* Empty the stack. */
720 if (!lua_checkstack(lua->T, 1)) {
721 ret = HLUA_E_ERR;
722 break;
723 }
724 lua_pushfstring(lua->T, "yield not allowed");
725 ret = HLUA_E_ERRMSG;
726 break;
727 }
728 ret = HLUA_E_AGAIN;
729 break;
730
731 case LUA_ERRRUN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100732 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100733 if (!lua_checkstack(lua->T, 1)) {
734 ret = HLUA_E_ERR;
735 break;
736 }
737 msg = lua_tostring(lua->T, -1);
738 lua_settop(lua->T, 0); /* Empty the stack. */
739 lua_pop(lua->T, 1);
740 if (msg)
741 lua_pushfstring(lua->T, "runtime error: %s", msg);
742 else
743 lua_pushfstring(lua->T, "unknown runtime error");
744 ret = HLUA_E_ERRMSG;
745 break;
746
747 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100748 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100749 lua_settop(lua->T, 0); /* Empty the stack. */
750 if (!lua_checkstack(lua->T, 1)) {
751 ret = HLUA_E_ERR;
752 break;
753 }
754 lua_pushfstring(lua->T, "out of memory error");
755 ret = HLUA_E_ERRMSG;
756 break;
757
758 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100759 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100760 if (!lua_checkstack(lua->T, 1)) {
761 ret = HLUA_E_ERR;
762 break;
763 }
764 msg = lua_tostring(lua->T, -1);
765 lua_settop(lua->T, 0); /* Empty the stack. */
766 lua_pop(lua->T, 1);
767 if (msg)
768 lua_pushfstring(lua->T, "message handler error: %s", msg);
769 else
770 lua_pushfstring(lua->T, "message handler error");
771 ret = HLUA_E_ERRMSG;
772 break;
773
774 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100775 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100776 lua_settop(lua->T, 0); /* Empty the stack. */
777 if (!lua_checkstack(lua->T, 1)) {
778 ret = HLUA_E_ERR;
779 break;
780 }
781 lua_pushfstring(lua->T, "unknonwn error");
782 ret = HLUA_E_ERRMSG;
783 break;
784 }
785
786 switch (ret) {
787 case HLUA_E_AGAIN:
788 break;
789
790 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100791 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100792 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100793 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100794 break;
795
796 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100797 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100798 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100799 hlua_ctx_renew(lua, 0);
800 break;
801
802 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100803 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100804 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100805 break;
806 }
807
808 return ret;
809}
810
Thierry FOURNIER83758bb2015-02-04 13:21:04 +0100811/* This function is an LUA binding. It provides a function
812 * for deleting ACL from a referenced ACL file.
813 */
814__LJMP static int hlua_del_acl(lua_State *L)
815{
816 const char *name;
817 const char *key;
818 struct pat_ref *ref;
819
820 MAY_LJMP(check_args(L, 2, "del_acl"));
821
822 name = MAY_LJMP(luaL_checkstring(L, 1));
823 key = MAY_LJMP(luaL_checkstring(L, 2));
824
825 ref = pat_ref_lookup(name);
826 if (!ref)
827 WILL_LJMP(luaL_error(L, "'del_acl': unkown acl file '%s'", name));
828
829 pat_ref_delete(ref, key);
830 return 0;
831}
832
833/* This function is an LUA binding. It provides a function
834 * for deleting map entry from a referenced map file.
835 */
836static int hlua_del_map(lua_State *L)
837{
838 const char *name;
839 const char *key;
840 struct pat_ref *ref;
841
842 MAY_LJMP(check_args(L, 2, "del_map"));
843
844 name = MAY_LJMP(luaL_checkstring(L, 1));
845 key = MAY_LJMP(luaL_checkstring(L, 2));
846
847 ref = pat_ref_lookup(name);
848 if (!ref)
849 WILL_LJMP(luaL_error(L, "'del_map': unkown acl file '%s'", name));
850
851 pat_ref_delete(ref, key);
852 return 0;
853}
854
855/* This function is an LUA binding. It provides a function
856 * for adding ACL pattern from a referenced ACL file.
857 */
858static int hlua_add_acl(lua_State *L)
859{
860 const char *name;
861 const char *key;
862 struct pat_ref *ref;
863
864 MAY_LJMP(check_args(L, 2, "add_acl"));
865
866 name = MAY_LJMP(luaL_checkstring(L, 1));
867 key = MAY_LJMP(luaL_checkstring(L, 2));
868
869 ref = pat_ref_lookup(name);
870 if (!ref)
871 WILL_LJMP(luaL_error(L, "'add_acl': unkown acl file '%s'", name));
872
873 if (pat_ref_find_elt(ref, key) == NULL)
874 pat_ref_add(ref, key, NULL, NULL);
875 return 0;
876}
877
878/* This function is an LUA binding. It provides a function
879 * for setting map pattern and sample from a referenced map
880 * file.
881 */
882static int hlua_set_map(lua_State *L)
883{
884 const char *name;
885 const char *key;
886 const char *value;
887 struct pat_ref *ref;
888
889 MAY_LJMP(check_args(L, 3, "set_map"));
890
891 name = MAY_LJMP(luaL_checkstring(L, 1));
892 key = MAY_LJMP(luaL_checkstring(L, 2));
893 value = MAY_LJMP(luaL_checkstring(L, 3));
894
895 ref = pat_ref_lookup(name);
896 if (!ref)
897 WILL_LJMP(luaL_error(L, "'set_map': unkown map file '%s'", name));
898
899 if (pat_ref_find_elt(ref, key) != NULL)
900 pat_ref_set(ref, key, value, NULL);
901 else
902 pat_ref_add(ref, key, value, NULL);
903 return 0;
904}
905
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100906/* A class is a lot of memory that contain data. This data can be a table,
907 * an integer or user data. This data is associated with a metatable. This
908 * metatable have an original version registred in the global context with
909 * the name of the object (_G[<name>] = <metable> ).
910 *
911 * A metable is a table that modify the standard behavior of a standard
912 * access to the associated data. The entries of this new metatable are
913 * defined as is:
914 *
915 * http://lua-users.org/wiki/MetatableEvents
916 *
917 * __index
918 *
919 * we access an absent field in a table, the result is nil. This is
920 * true, but it is not the whole truth. Actually, such access triggers
921 * the interpreter to look for an __index metamethod: If there is no
922 * such method, as usually happens, then the access results in nil;
923 * otherwise, the metamethod will provide the result.
924 *
925 * Control 'prototype' inheritance. When accessing "myTable[key]" and
926 * the key does not appear in the table, but the metatable has an __index
927 * property:
928 *
929 * - if the value is a function, the function is called, passing in the
930 * table and the key; the return value of that function is returned as
931 * the result.
932 *
933 * - if the value is another table, the value of the key in that table is
934 * asked for and returned (and if it doesn't exist in that table, but that
935 * table's metatable has an __index property, then it continues on up)
936 *
937 * - Use "rawget(myTable,key)" to skip this metamethod.
938 *
939 * http://www.lua.org/pil/13.4.1.html
940 *
941 * __newindex
942 *
943 * Like __index, but control property assignment.
944 *
945 * __mode - Control weak references. A string value with one or both
946 * of the characters 'k' and 'v' which specifies that the the
947 * keys and/or values in the table are weak references.
948 *
949 * __call - Treat a table like a function. When a table is followed by
950 * parenthesis such as "myTable( 'foo' )" and the metatable has
951 * a __call key pointing to a function, that function is invoked
952 * (passing any specified arguments) and the return value is
953 * returned.
954 *
955 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
956 * called, if the metatable for myTable has a __metatable
957 * key, the value of that key is returned instead of the
958 * actual metatable.
959 *
960 * __tostring - Control string representation. When the builtin
961 * "tostring( myTable )" function is called, if the metatable
962 * for myTable has a __tostring property set to a function,
963 * that function is invoked (passing myTable to it) and the
964 * return value is used as the string representation.
965 *
966 * __len - Control table length. When the table length is requested using
967 * the length operator ( '#' ), if the metatable for myTable has
968 * a __len key pointing to a function, that function is invoked
969 * (passing myTable to it) and the return value used as the value
970 * of "#myTable".
971 *
972 * __gc - Userdata finalizer code. When userdata is set to be garbage
973 * collected, if the metatable has a __gc field pointing to a
974 * function, that function is first invoked, passing the userdata
975 * to it. The __gc metamethod is not called for tables.
976 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
977 *
978 * Special metamethods for redefining standard operators:
979 * http://www.lua.org/pil/13.1.html
980 *
981 * __add "+"
982 * __sub "-"
983 * __mul "*"
984 * __div "/"
985 * __unm "!"
986 * __pow "^"
987 * __concat ".."
988 *
989 * Special methods for redfining standar relations
990 * http://www.lua.org/pil/13.2.html
991 *
992 * __eq "=="
993 * __lt "<"
994 * __le "<="
995 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100996
997/*
998 *
999 *
1000 * Class Socket
1001 *
1002 *
1003 */
1004
1005__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1006{
1007 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1008}
1009
1010/* This function is the handler called for each I/O on the established
1011 * connection. It is used for notify space avalaible to send or data
1012 * received.
1013 */
1014static void hlua_socket_handler(struct stream_interface *si)
1015{
1016 struct appctx *appctx = objt_appctx(si->end);
1017 struct connection *c = objt_conn(si->ib->cons->end);
1018
1019 /* Wakeup the main session if the client connection is closed. */
1020 if (!c || channel_output_closed(si->ib) || channel_input_closed(si->ob)) {
1021 if (appctx->ctx.hlua.socket) {
1022 appctx->ctx.hlua.socket->s = NULL;
1023 appctx->ctx.hlua.socket = NULL;
1024 }
1025 si_shutw(si);
1026 si_shutr(si);
1027 si->ib->flags |= CF_READ_NULL;
1028 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1029 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1030 return;
1031 }
1032
1033 if (!(c->flags & CO_FL_CONNECTED))
1034 return;
1035
1036 /* This function is called after the connect. */
1037 appctx->ctx.hlua.connected = 1;
1038
1039 /* Wake the tasks which wants to write if the buffer have avalaible space. */
1040 if (channel_may_recv(si->ob))
1041 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1042
1043 /* Wake the tasks which wants to read if the buffer contains data. */
1044 if (channel_is_empty(si->ib))
1045 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1046}
1047
1048/* This function is called when the "struct session" is destroyed.
1049 * Remove the link from the object to this session.
1050 * Wake all the pending signals.
1051 */
1052static void hlua_socket_release(struct stream_interface *si)
1053{
1054 struct appctx *appctx = objt_appctx(si->end);
1055
1056 /* Remove my link in the original object. */
1057 if (appctx->ctx.hlua.socket)
1058 appctx->ctx.hlua.socket->s = NULL;
1059
1060 /* Wake all the task waiting for me. */
1061 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1062 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1063}
1064
1065/* If the garbage collectio of the object is launch, nobody
1066 * uses this object. If the session does not exists, just quit.
1067 * Send the shutdown signal to the session. In some cases,
1068 * pending signal can rest in the read and write lists. destroy
1069 * it.
1070 */
1071__LJMP static int hlua_socket_gc(lua_State *L)
1072{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001073 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001074 struct appctx *appctx;
1075
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001076 MAY_LJMP(check_args(L, 1, "__gc"));
1077
1078 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001079 if (!socket->s)
1080 return 0;
1081
1082 /* Remove all reference between the Lua stack and the coroutine session. */
1083 appctx = objt_appctx(socket->s->si[0].end);
1084 session_shutdown(socket->s, SN_ERR_KILLED);
1085 socket->s = NULL;
1086 appctx->ctx.hlua.socket = NULL;
1087
1088 return 0;
1089}
1090
1091/* The close function send shutdown signal and break the
1092 * links between the session and the object.
1093 */
1094__LJMP static int hlua_socket_close(lua_State *L)
1095{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001096 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001097 struct appctx *appctx;
1098
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001099 MAY_LJMP(check_args(L, 1, "close"));
1100
1101 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001102 if (!socket->s)
1103 return 0;
1104
1105 /* Close the session and remove the associated stop task. */
1106 session_shutdown(socket->s, SN_ERR_KILLED);
1107 appctx = objt_appctx(socket->s->si[0].end);
1108 appctx->ctx.hlua.socket = NULL;
1109 socket->s = NULL;
1110
1111 return 0;
1112}
1113
1114/* This Lua function assumes that the stack contain three parameters.
1115 * 1 - USERDATA containing a struct socket
1116 * 2 - INTEGER with values of the macro defined below
1117 * If the integer is -1, we must read at most one line.
1118 * If the integer is -2, we ust read all the data until the
1119 * end of the stream.
1120 * If the integer is positive value, we must read a number of
1121 * bytes corresponding to this value.
1122 */
1123#define HLSR_READ_LINE (-1)
1124#define HLSR_READ_ALL (-2)
1125__LJMP static int hlua_socket_receive_yield(struct lua_State *L)
1126{
1127 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1128 int wanted = lua_tointeger(L, 2);
1129 struct hlua *hlua = hlua_gethlua(L);
1130 struct appctx *appctx;
1131 int len;
1132 int nblk;
1133 char *blk1;
1134 int len1;
1135 char *blk2;
1136 int len2;
1137
1138 /* Check if this lua stack is schedulable. */
1139 if (!hlua || !hlua->task)
1140 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1141 "'frontend', 'backend' or 'task'"));
1142
1143 /* check for connection closed. If some data where read, return it. */
1144 if (!socket->s)
1145 goto connection_closed;
1146
1147 if (wanted == HLSR_READ_LINE) {
1148
1149 /* Read line. */
1150 nblk = bo_getline_nc(socket->s->si[0].ob, &blk1, &len1, &blk2, &len2);
1151 if (nblk < 0) /* Connection close. */
1152 goto connection_closed;
1153 if (nblk == 0) /* No data avalaible. */
1154 goto connection_empty;
1155 }
1156
1157 else if (wanted == HLSR_READ_ALL) {
1158
1159 /* Read all the available data. */
1160 nblk = bo_getblk_nc(socket->s->si[0].ob, &blk1, &len1, &blk2, &len2);
1161 if (nblk < 0) /* Connection close. */
1162 goto connection_closed;
1163 if (nblk == 0) /* No data avalaible. */
1164 goto connection_empty;
1165 }
1166
1167 else {
1168
1169 /* Read a block of data. */
1170 nblk = bo_getblk_nc(socket->s->si[0].ob, &blk1, &len1, &blk2, &len2);
1171 if (nblk < 0) /* Connection close. */
1172 goto connection_closed;
1173 if (nblk == 0) /* No data avalaible. */
1174 goto connection_empty;
1175
1176 if (len1 > wanted) {
1177 nblk = 1;
1178 len1 = wanted;
1179 } if (nblk == 2 && len1 + len2 > wanted)
1180 len2 = wanted - len1;
1181 }
1182
1183 len = len1;
1184
1185 luaL_addlstring(&socket->b, blk1, len1);
1186 if (nblk == 2) {
1187 len += len2;
1188 luaL_addlstring(&socket->b, blk2, len2);
1189 }
1190
1191 /* Consume data. */
1192 bo_skip(socket->s->si[0].ob, len);
1193
1194 /* Don't wait anything. */
1195 si_update(&socket->s->si[0]);
1196
1197 /* If the pattern reclaim to read all the data
1198 * in the connection, got out.
1199 */
1200 if (wanted == HLSR_READ_ALL)
1201 goto connection_empty;
1202 else if (wanted >= 0 && len < wanted)
1203 goto connection_empty;
1204
1205 /* Return result. */
1206 luaL_pushresult(&socket->b);
1207 return 1;
1208
1209connection_closed:
1210
1211 /* If the buffer containds data. */
1212 if (socket->b.n > 0) {
1213 luaL_pushresult(&socket->b);
1214 return 1;
1215 }
1216 lua_pushnil(L);
1217 lua_pushstring(L, "connection closed.");
1218 return 2;
1219
1220connection_empty:
1221
1222 appctx = objt_appctx(socket->s->si[0].end);
1223 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1224 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001225 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001226 return 0;
1227}
1228
1229/* This Lus function gets two parameters. The first one can be string
1230 * or a number. If the string is "*l", the user require one line. If
1231 * the string is "*a", the user require all the content of the stream.
1232 * If the value is a number, the user require a number of bytes equal
1233 * to the value. The default value is "*l" (a line).
1234 *
1235 * This paraeter with a variable type is converted in integer. This
1236 * integer takes this values:
1237 * -1 : read a line
1238 * -2 : read all the stream
1239 * >0 : amount if bytes.
1240 *
1241 * The second parameter is optinal. It contains a string that must be
1242 * concatenated with the read data.
1243 */
1244__LJMP static int hlua_socket_receive(struct lua_State *L)
1245{
1246 int wanted = HLSR_READ_LINE;
1247 const char *pattern;
1248 int type;
1249 char *error;
1250 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001251 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001252
1253 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1254 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1255
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001256 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001257
1258 /* check for pattern. */
1259 if (lua_gettop(L) >= 2) {
1260 type = lua_type(L, 2);
1261 if (type == LUA_TSTRING) {
1262 pattern = lua_tostring(L, 2);
1263 if (strcmp(pattern, "*a") == 0)
1264 wanted = HLSR_READ_ALL;
1265 else if (strcmp(pattern, "*l") == 0)
1266 wanted = HLSR_READ_LINE;
1267 else {
1268 wanted = strtoll(pattern, &error, 10);
1269 if (*error != '\0')
1270 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1271 }
1272 }
1273 else if (type == LUA_TNUMBER) {
1274 wanted = lua_tointeger(L, 2);
1275 if (wanted < 0)
1276 WILL_LJMP(luaL_error(L, "Unsupported size."));
1277 }
1278 }
1279
1280 /* Set pattern. */
1281 lua_pushinteger(L, wanted);
1282 lua_replace(L, 2);
1283
1284 /* init bufffer, and fiil it wih prefix. */
1285 luaL_buffinit(L, &socket->b);
1286
1287 /* Check prefix. */
1288 if (lua_gettop(L) >= 3) {
1289 if (lua_type(L, 3) != LUA_TSTRING)
1290 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1291 pattern = lua_tolstring(L, 3, &len);
1292 luaL_addlstring(&socket->b, pattern, len);
1293 }
1294
1295 return __LJMP(hlua_socket_receive_yield(L));
1296}
1297
1298/* Write the Lua input string in the output buffer.
1299 * This fucntion returns a yield if no space are available.
1300 */
1301static int hlua_socket_write_yield(struct lua_State *L)
1302{
1303 struct hlua_socket *socket;
1304 struct hlua *hlua = hlua_gethlua(L);
1305 struct appctx *appctx;
1306 size_t buf_len;
1307 const char *buf;
1308 int len;
1309 int send_len;
1310 int sent;
1311
1312 /* Check if this lua stack is schedulable. */
1313 if (!hlua || !hlua->task)
1314 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1315 "'frontend', 'backend' or 'task'"));
1316
1317 /* Get object */
1318 socket = MAY_LJMP(hlua_checksocket(L, 1));
1319 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1320 sent = MAY_LJMP(luaL_checkunsigned(L, 3));
1321
1322 /* Check for connection close. */
1323 if (!socket->s || channel_output_closed(socket->s->req)) {
1324 lua_pushinteger(L, -1);
1325 return 1;
1326 }
1327
1328 /* Update the input buffer data. */
1329 buf += sent;
1330 send_len = buf_len - sent;
1331
1332 /* All the data are sent. */
1333 if (sent >= buf_len)
1334 return 1; /* Implicitly return the length sent. */
1335
1336 /* Check for avalaible space. */
1337 len = buffer_total_space(socket->s->si[0].ib->buf);
1338 if (len <= 0)
1339 goto hlua_socket_write_yield_return;
1340
1341 /* send data */
1342 if (len < send_len)
1343 send_len = len;
1344 len = bi_putblk(socket->s->si[0].ib, buf+sent, send_len);
1345
1346 /* "Not enough space" (-1), "Buffer too little to contain
1347 * the data" (-2) are not expected because the available length
1348 * is tested.
1349 * Other unknown error are also not expected.
1350 */
1351 if (len <= 0) {
1352 MAY_LJMP(hlua_socket_close(L));
1353 lua_pop(L, 1);
1354 lua_pushunsigned(L, -1);
1355 return 1;
1356 }
1357
1358 /* update buffers. */
1359 si_update(&socket->s->si[0]);
1360 socket->s->si[0].ib->rex = TICK_ETERNITY;
1361 socket->s->si[0].ob->wex = TICK_ETERNITY;
1362
1363 /* Update length sent. */
1364 lua_pop(L, 1);
1365 lua_pushunsigned(L, sent + len);
1366
1367 /* All the data buffer is sent ? */
1368 if (sent + len >= buf_len)
1369 return 1;
1370
1371hlua_socket_write_yield_return:
1372 appctx = objt_appctx(socket->s->si[0].end);
1373 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1374 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001375 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001376 return 0;
1377}
1378
1379/* This function initiate the send of data. It just check the input
1380 * parameters and push an integer in the Lua stack that contain the
1381 * amount of data writed in the buffer. This is used by the function
1382 * "hlua_socket_write_yield" that can yield.
1383 *
1384 * The Lua function gets between 3 and 4 parameters. The first one is
1385 * the associated object. The second is a string buffer. The third is
1386 * a facultative integer that represents where is the buffer position
1387 * of the start of the data that can send. The first byte is the
1388 * position "1". The default value is "1". The fourth argument is a
1389 * facultative integer that represents where is the buffer position
1390 * of the end of the data that can send. The default is the last byte.
1391 */
1392static int hlua_socket_send(struct lua_State *L)
1393{
1394 int i;
1395 int j;
1396 const char *buf;
1397 size_t buf_len;
1398
1399 /* Check number of arguments. */
1400 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1401 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1402
1403 /* Get the string. */
1404 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1405
1406 /* Get and check j. */
1407 if (lua_gettop(L) == 4) {
1408 j = MAY_LJMP(luaL_checkinteger(L, 4));
1409 if (j < 0)
1410 j = buf_len + j + 1;
1411 if (j > buf_len)
1412 j = buf_len + 1;
1413 lua_pop(L, 1);
1414 }
1415 else
1416 j = buf_len;
1417
1418 /* Get and check i. */
1419 if (lua_gettop(L) == 3) {
1420 i = MAY_LJMP(luaL_checkinteger(L, 3));
1421 if (i < 0)
1422 i = buf_len + i + 1;
1423 if (i > buf_len)
1424 i = buf_len + 1;
1425 lua_pop(L, 1);
1426 } else
1427 i = 1;
1428
1429 /* Check bth i and j. */
1430 if (i > j) {
1431 lua_pushunsigned(L, 0);
1432 return 1;
1433 }
1434 if (i == 0 && j == 0) {
1435 lua_pushunsigned(L, 0);
1436 return 1;
1437 }
1438 if (i == 0)
1439 i = 1;
1440 if (j == 0)
1441 j = 1;
1442
1443 /* Pop the string. */
1444 lua_pop(L, 1);
1445
1446 /* Update the buffer length. */
1447 buf += i - 1;
1448 buf_len = j - i + 1;
1449 lua_pushlstring(L, buf, buf_len);
1450
1451 /* This unsigned is used to remember the amount of sent data. */
1452 lua_pushunsigned(L, 0);
1453
1454 return MAY_LJMP(hlua_socket_write_yield(L));
1455}
1456
1457#define SOCKET_INFO_EXPANDED_FORM "[0000:0000:0000:0000:0000:0000:0000:0000]:12345"
1458static char _socket_info_expanded_form[] = SOCKET_INFO_EXPANDED_FORM;
1459#define SOCKET_INFO_MAX_LEN (sizeof(_socket_info_expanded_form))
1460__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
1461{
1462 static char buffer[SOCKET_INFO_MAX_LEN];
1463 int ret;
1464 int len;
1465 char *p;
1466
1467 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
1468 if (ret <= 0) {
1469 lua_pushnil(L);
1470 return 1;
1471 }
1472
1473 if (ret == AF_UNIX) {
1474 lua_pushstring(L, buffer+1);
1475 return 1;
1476 }
1477 else if (ret == AF_INET6) {
1478 buffer[0] = '[';
1479 len = strlen(buffer);
1480 buffer[len] = ']';
1481 len++;
1482 buffer[len] = ':';
1483 len++;
1484 p = buffer;
1485 }
1486 else if (ret == AF_INET) {
1487 p = buffer + 1;
1488 len = strlen(p);
1489 p[len] = ':';
1490 len++;
1491 }
1492 else {
1493 lua_pushnil(L);
1494 return 1;
1495 }
1496
1497 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
1498 lua_pushnil(L);
1499 return 1;
1500 }
1501
1502 lua_pushstring(L, p);
1503 return 1;
1504}
1505
1506/* Returns information about the peer of the connection. */
1507__LJMP static int hlua_socket_getpeername(struct lua_State *L)
1508{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001509 struct hlua_socket *socket;
1510 struct connection *conn;
1511
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001512 MAY_LJMP(check_args(L, 1, "getpeername"));
1513
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001514 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001515
1516 /* Check if the tcp object is avalaible. */
1517 if (!socket->s) {
1518 lua_pushnil(L);
1519 return 1;
1520 }
1521
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001522 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001523 if (!conn) {
1524 lua_pushnil(L);
1525 return 1;
1526 }
1527
1528 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
1529 unsigned int salen = sizeof(conn->addr.to);
1530 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
1531 lua_pushnil(L);
1532 return 1;
1533 }
1534 conn->flags |= CO_FL_ADDR_TO_SET;
1535 }
1536
1537 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
1538}
1539
1540/* Returns information about my connection side. */
1541static int hlua_socket_getsockname(struct lua_State *L)
1542{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001543 struct hlua_socket *socket;
1544 struct connection *conn;
1545
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001546 MAY_LJMP(check_args(L, 1, "getsockname"));
1547
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001548 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001549
1550 /* Check if the tcp object is avalaible. */
1551 if (!socket->s) {
1552 lua_pushnil(L);
1553 return 1;
1554 }
1555
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001556 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001557 if (!conn) {
1558 lua_pushnil(L);
1559 return 1;
1560 }
1561
1562 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
1563 unsigned int salen = sizeof(conn->addr.from);
1564 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
1565 lua_pushnil(L);
1566 return 1;
1567 }
1568 conn->flags |= CO_FL_ADDR_FROM_SET;
1569 }
1570
1571 return hlua_socket_info(L, &conn->addr.from);
1572}
1573
1574/* This struct define the applet. */
1575static struct si_applet update_applet = {
1576 .obj_type = OBJ_TYPE_APPLET,
1577 .name = "<LUA_TCP>",
1578 .fct = hlua_socket_handler,
1579 .release = hlua_socket_release,
1580};
1581
1582__LJMP static int hlua_socket_connect_yield(struct lua_State *L)
1583{
1584 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1585 struct hlua *hlua = hlua_gethlua(L);
1586 struct appctx *appctx;
1587
1588 /* Check for connection close. */
1589 if (!hlua || !socket->s || channel_output_closed(socket->s->req)) {
1590 lua_pushnil(L);
1591 lua_pushstring(L, "Can't connect");
1592 return 2;
1593 }
1594
1595 appctx = objt_appctx(socket->s->si[0].end);
1596
1597 /* Check for connection established. */
1598 if (appctx->ctx.hlua.connected) {
1599 lua_pushinteger(L, 1);
1600 return 1;
1601 }
1602
1603 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1604 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001605 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001606 return 0;
1607}
1608
1609/* This function fail or initite the connection. */
1610__LJMP static int hlua_socket_connect(struct lua_State *L)
1611{
1612 struct hlua_socket *socket;
1613 unsigned int port;
1614 const char *ip;
1615 struct connection *conn;
1616
1617 MAY_LJMP(check_args(L, 3, "connect"));
1618
1619 /* Get args. */
1620 socket = MAY_LJMP(hlua_checksocket(L, 1));
1621 ip = MAY_LJMP(luaL_checkstring(L, 2));
1622 port = MAY_LJMP(luaL_checkunsigned(L, 3));
1623
1624 conn = si_alloc_conn(socket->s->req->cons, 0);
1625 if (!conn)
1626 WILL_LJMP(luaL_error(L, "connect: internal error"));
1627
1628 /* Parse ip address. */
1629 conn->addr.to.ss_family = AF_UNSPEC;
1630 if (!str2ip2(ip, &conn->addr.to, 0))
1631 WILL_LJMP(luaL_error(L, "connect: cannot parse ip address '%s'", ip));
1632
1633 /* Set port. */
1634 if (conn->addr.to.ss_family == AF_INET)
1635 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
1636 else if (conn->addr.to.ss_family == AF_INET6)
1637 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
1638
1639 /* it is important not to call the wakeup function directly but to
1640 * pass through task_wakeup(), because this one knows how to apply
1641 * priorities to tasks.
1642 */
1643 task_wakeup(socket->s->task, TASK_WOKEN_INIT);
1644
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001645 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001646
1647 return 0;
1648}
1649
Baptiste Assmann84bb4932015-03-02 21:40:06 +01001650#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001651__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
1652{
1653 struct hlua_socket *socket;
1654
1655 MAY_LJMP(check_args(L, 3, "connect_ssl"));
1656 socket = MAY_LJMP(hlua_checksocket(L, 1));
1657 socket->s->target = &socket_ssl.obj_type;
1658 return MAY_LJMP(hlua_socket_connect(L));
1659}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01001660#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001661
1662__LJMP static int hlua_socket_setoption(struct lua_State *L)
1663{
1664 return 0;
1665}
1666
1667__LJMP static int hlua_socket_settimeout(struct lua_State *L)
1668{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001669 struct hlua_socket *socket;
1670 unsigned int tmout;
1671
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001672 MAY_LJMP(check_args(L, 2, "settimeout"));
1673
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001674 socket = MAY_LJMP(hlua_checksocket(L, 1));
1675 tmout = MAY_LJMP(luaL_checkunsigned(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001676
1677 socket->s->req->rto = tmout;
1678 socket->s->req->wto = tmout;
1679 socket->s->rep->rto = tmout;
1680 socket->s->rep->wto = tmout;
1681
1682 return 0;
1683}
1684
1685__LJMP static int hlua_socket_new(lua_State *L)
1686{
1687 struct hlua_socket *socket;
1688 struct appctx *appctx;
1689
1690 /* Check stack size. */
1691 if (!lua_checkstack(L, 2)) {
1692 hlua_pusherror(L, "socket: full stack");
1693 goto out_fail_conf;
1694 }
1695
1696 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
1697 memset(socket, 0, sizeof(*socket));
1698
1699 /* Pop a class session metatable and affect it to the userdata. */
1700 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
1701 lua_setmetatable(L, -2);
1702
1703 /*
1704 *
1705 * Get memory for the request.
1706 *
1707 */
1708
1709 socket->s = pool_alloc2(pool2_session);
1710 if (!socket->s) {
1711 hlua_pusherror(L, "socket: out of memory");
1712 goto out_fail_conf;
1713 }
1714
1715 socket->s->task = task_new();
1716 if (!socket->s->task) {
1717 hlua_pusherror(L, "socket: out of memory");
1718 goto out_free_session;
1719 }
1720
1721 socket->s->req = pool_alloc2(pool2_channel);
1722 if (!socket->s->req) {
1723 hlua_pusherror(L, "socket: out of memory");
1724 goto out_fail_req;
1725 }
1726
1727 socket->s->req->buf = pool_alloc2(pool2_buffer);
1728 if (!socket->s->req->buf) {
1729 hlua_pusherror(L, "socket: out of memory");
1730 goto out_fail_req_buf;
1731 }
1732
1733 socket->s->rep = pool_alloc2(pool2_channel);
1734 if (!socket->s->rep) {
1735 hlua_pusherror(L, "socket: out of memory");
1736 goto out_fail_rep;
1737 }
1738
1739 socket->s->rep->buf = pool_alloc2(pool2_buffer);
1740 if (!socket->s->rep->buf) {
1741 hlua_pusherror(L, "socket: out of memory");
1742 goto out_fail_rep_buf;
1743 }
1744
1745 /* Configura empty Lua for the session. */
1746 socket->s->hlua.T = NULL;
1747 socket->s->hlua.Tref = LUA_REFNIL;
1748 socket->s->hlua.Mref = LUA_REFNIL;
1749 socket->s->hlua.nargs = 0;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001750 socket->s->hlua.flags = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001751 LIST_INIT(&socket->s->hlua.com);
1752
1753 /* session initialisation. */
1754 session_init_srv_conn(socket->s);
1755
1756 /*
1757 *
1758 * Configure the associated task.
1759 *
1760 */
1761
1762 /* This is the dedicated function to process the session. This function
1763 * is able to establish the conection, process the timeouts, etc ...
1764 */
1765 socket->s->task->process = process_session;
1766
1767 /* Back reference to session. This is used by process_session(). */
1768 socket->s->task->context = socket->s;
1769
1770 /* The priority of the task is normal. */
1771 socket->s->task->nice = 0;
1772
1773 /* Init the next run to eternity. Later in this function, this task is
1774 * waked.
1775 */
1776 socket->s->task->expire = TICK_ETERNITY;
1777
1778 /*
1779 *
1780 * Initialize the attached buffers
1781 *
1782 */
1783 socket->s->req->buf->size = global.tune.bufsize;
1784 socket->s->rep->buf->size = global.tune.bufsize;
1785
1786 /*
1787 *
1788 * Initialize channels.
1789 *
1790 */
1791
1792 /* This function reset the struct. It must be called
1793 * before the configuration.
1794 */
1795 channel_init(socket->s->req);
1796 channel_init(socket->s->rep);
1797
1798 socket->s->req->prod = &socket->s->si[0];
1799 socket->s->req->cons = &socket->s->si[1];
1800
1801 socket->s->rep->prod = &socket->s->si[1];
1802 socket->s->rep->cons = &socket->s->si[0];
1803
1804 socket->s->si[0].ib = socket->s->req;
1805 socket->s->si[0].ob = socket->s->rep;
1806
1807 socket->s->si[1].ib = socket->s->rep;
1808 socket->s->si[1].ob = socket->s->req;
1809
1810 socket->s->req->analysers = 0;
1811 socket->s->req->rto = socket_proxy.timeout.client;
1812 socket->s->req->wto = socket_proxy.timeout.server;
1813 socket->s->req->rex = TICK_ETERNITY;
1814 socket->s->req->wex = TICK_ETERNITY;
1815 socket->s->req->analyse_exp = TICK_ETERNITY;
1816
1817 socket->s->rep->analysers = 0;
1818 socket->s->rep->rto = socket_proxy.timeout.server;
1819 socket->s->rep->wto = socket_proxy.timeout.client;
1820 socket->s->rep->rex = TICK_ETERNITY;
1821 socket->s->rep->wex = TICK_ETERNITY;
1822 socket->s->rep->analyse_exp = TICK_ETERNITY;
1823
1824 /*
1825 *
1826 * Configure the session.
1827 *
1828 */
1829
1830 /* The session dont have listener. The listener is used with real
1831 * proxies.
1832 */
1833 socket->s->listener = NULL;
1834
1835 /* The flags are initialized to 0. Values are setted later. */
1836 socket->s->flags = 0;
1837
1838 /* Assign the configured proxy to the new session. */
1839 socket->s->be = &socket_proxy;
1840 socket->s->fe = &socket_proxy;
1841
1842 /* XXX: Set namy variables */
1843 socket->s->store_count = 0;
1844 memset(socket->s->stkctr, 0, sizeof(socket->s->stkctr));
1845
1846 /* Configure logs. */
1847 socket->s->logs.logwait = 0;
1848 socket->s->logs.level = 0;
1849 socket->s->logs.accept_date = date; /* user-visible date for logging */
1850 socket->s->logs.tv_accept = now; /* corrected date for internal use */
1851 socket->s->do_log = NULL;
1852
1853 /* Function used if an error is occured. */
1854 socket->s->srv_error = default_srv_error;
1855
1856 /* Init the list of buffers. */
1857 LIST_INIT(&socket->s->buffer_wait);
1858
1859 /* Dont configure the unique ID. */
1860 socket->s->uniq_id = 0;
1861 socket->s->unique_id = NULL;
1862
1863 /* XXX: ? */
1864 socket->s->pend_pos = NULL;
1865
1866 /* XXX: See later. */
1867 socket->s->txn.sessid = NULL;
1868 socket->s->txn.srv_cookie = NULL;
1869 socket->s->txn.cli_cookie = NULL;
1870 socket->s->txn.uri = NULL;
1871 socket->s->txn.req.cap = NULL;
1872 socket->s->txn.rsp.cap = NULL;
1873 socket->s->txn.hdr_idx.v = NULL;
1874 socket->s->txn.hdr_idx.size = 0;
1875 socket->s->txn.hdr_idx.used = 0;
1876
1877 /* Configure "left" stream interface as applet. This "si" produce
1878 * and use the data received from the server. The applet is initialized
1879 * and is attached to the stream interface.
1880 */
1881
1882 /* The data producer is already connected. It is the applet. */
1883 socket->s->req->flags = CF_READ_ATTACHED;
1884
1885 channel_auto_connect(socket->s->req); /* don't wait to establish connection */
1886 channel_auto_close(socket->s->req); /* let the producer forward close requests */
1887
1888 si_reset(&socket->s->si[0], socket->s->task);
1889 si_set_state(&socket->s->si[0], SI_ST_EST); /* connection established (resource exists) */
1890
1891 appctx = stream_int_register_handler(&socket->s->si[0], &update_applet);
1892 if (!appctx)
1893 goto out_fail_conn1;
1894 appctx->ctx.hlua.socket = socket;
1895 appctx->ctx.hlua.connected = 0;
1896 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
1897 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
1898
1899 /* Configure "right" stream interface. this "si" is used to connect
1900 * and retrieve data from the server. The connection is initialized
1901 * with the "struct server".
1902 */
1903 si_reset(&socket->s->si[1], socket->s->task);
1904 si_set_state(&socket->s->si[1], SI_ST_INI);
1905 socket->s->si[1].conn_retries = socket_proxy.conn_retries;
1906
1907 /* Force destination server. */
1908 socket->s->flags |= SN_DIRECT | SN_ASSIGNED | SN_ADDR_SET | SN_BE_ASSIGNED;
1909 socket->s->target = &socket_tcp.obj_type;
1910
1911 /* This session is added to te lists of alive sessions. */
1912 LIST_ADDQ(&sessions, &socket->s->list);
1913
1914 /* XXX: I think that this list is used by stats. */
1915 LIST_INIT(&socket->s->back_refs);
1916
1917 /* Update statistics counters. */
1918 socket_proxy.feconn++; /* beconn will be increased later */
1919 jobs++;
1920 totalconn++;
1921
1922 /* Return yield waiting for connection. */
1923 return 1;
1924
1925out_fail_conn1:
1926 pool_free2(pool2_buffer, socket->s->rep->buf);
1927out_fail_rep_buf:
1928 pool_free2(pool2_channel, socket->s->rep);
1929out_fail_rep:
1930 pool_free2(pool2_buffer, socket->s->req->buf);
1931out_fail_req_buf:
1932 pool_free2(pool2_channel, socket->s->req);
1933out_fail_req:
1934 task_free(socket->s->task);
1935out_free_session:
1936 pool_free2(pool2_session, socket->s);
1937out_fail_conf:
1938 WILL_LJMP(lua_error(L));
1939 return 0;
1940}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001941
1942/*
1943 *
1944 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01001945 * Class Channel
1946 *
1947 *
1948 */
1949
1950/* Returns the struct hlua_channel join to the class channel in the
1951 * stack entry "ud" or throws an argument error.
1952 */
1953__LJMP static struct hlua_channel *hlua_checkchannel(lua_State *L, int ud)
1954{
1955 return (struct hlua_channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
1956}
1957
1958/* Creates new channel object and put it on the top of the stack.
1959 * If the stask does not have a free slots, the function fails
1960 * and returns 0;
1961 */
1962static int hlua_channel_new(lua_State *L, struct channel *channel)
1963{
1964 struct hlua_channel *chn;
1965
1966 /* Check stack size. */
1967 if (!lua_checkstack(L, 2))
1968 return 0;
1969
1970 /* NOTE: The allocation never fails. The failure
1971 * throw an error, and the function never returns.
1972 */
1973 chn = lua_newuserdata(L, sizeof(*chn));
1974 chn->chn = channel;
1975
1976 /* Pop a class sesison metatable and affect it to the userdata. */
1977 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
1978 lua_setmetatable(L, -2);
1979
1980 return 1;
1981}
1982
1983/* Duplicate all the data present in the input channel and put it
1984 * in a string LUA variables. Returns -1 and push a nil value in
1985 * the stack if the channel is closed and all the data are consumed,
1986 * returns 0 if no data are available, otherwise it returns the length
1987 * of the builded string.
1988 */
1989static inline int _hlua_channel_dup(struct hlua_channel *chn, lua_State *L)
1990{
1991 char *blk1;
1992 char *blk2;
1993 int len1;
1994 int len2;
1995 int ret;
1996 luaL_Buffer b;
1997
1998 ret = bi_getblk_nc(chn->chn, &blk1, &len1, &blk2, &len2);
1999 if (unlikely(ret == 0))
2000 return 0;
2001
2002 if (unlikely(ret < 0)) {
2003 lua_pushnil(L);
2004 return -1;
2005 }
2006
2007 luaL_buffinit(L, &b);
2008 luaL_addlstring(&b, blk1, len1);
2009 if (unlikely(ret == 2))
2010 luaL_addlstring(&b, blk2, len2);
2011 luaL_pushresult(&b);
2012
2013 if (unlikely(ret == 2))
2014 return len1 + len2;
2015 return len1;
2016}
2017
2018/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2019 * a yield. This function keep the data in the buffer.
2020 */
2021__LJMP static int hlua_channel_dup(lua_State *L)
2022{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002023 struct hlua_channel *chn;
2024
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002025 MAY_LJMP(check_args(L, 1, "dup"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002026
2027 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2028
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002029 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002030 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002031 return 1;
2032}
2033
2034/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2035 * a yield. This function consumes the data in the buffer. It returns
2036 * a string containing the data or a nil pointer if no data are available
2037 * and the channel is closed.
2038 */
2039__LJMP static int hlua_channel_get(lua_State *L)
2040{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002041 struct hlua_channel *chn;
2042 int ret;
2043
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002044 MAY_LJMP(check_args(L, 1, "get"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002045
2046 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2047 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002048 if (unlikely(ret == 0))
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002049 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002050
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002051 if (unlikely(ret == -1))
2052 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002053
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002054 chn->chn->buf->i -= ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002055 return 1;
2056}
2057
2058/* This functions consumes and returns one line. If the channel is closed,
2059 * and the last data does not contains a final '\n', the data are returned
2060 * without the final '\n'. When no more data are avalaible, it returns nil
2061 * value.
2062 */
2063__LJMP static int hlua_channel_getline(lua_State *L)
2064{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002065 char *blk1;
2066 char *blk2;
2067 int len1;
2068 int len2;
2069 int len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002070 struct hlua_channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002071 int ret;
2072 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002073
2074 MAY_LJMP(check_args(L, 1, "getline"));
2075 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2076
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002077 ret = bi_getline_nc(chn->chn, &blk1, &len1, &blk2, &len2);
2078 if (ret == 0)
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002079 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002080
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002081 if (ret == -1) {
2082 lua_pushnil(L);
2083 return 1;
2084 }
2085
2086 luaL_buffinit(L, &b);
2087 luaL_addlstring(&b, blk1, len1);
2088 len = len1;
2089 if (unlikely(ret == 2)) {
2090 luaL_addlstring(&b, blk2, len2);
2091 len += len2;
2092 }
2093 luaL_pushresult(&b);
2094 buffer_replace2(chn->chn->buf, chn->chn->buf->p, chn->chn->buf->p + len, NULL, 0);
2095 return 1;
2096}
2097
2098/* This function takes a string as input, and append it at the
2099 * input side of channel. If the data is too big, but a space
2100 * is probably available after sending some data, the function
2101 * yield. If the data is bigger than the buffer, or if the
2102 * channel is closed, it returns -1. otherwise, it returns the
2103 * amount of data writed.
2104 */
2105__LJMP static int _hlua_channel_append(lua_State *L)
2106{
2107 struct hlua_channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
2108 size_t len;
2109 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2110 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2111 int ret;
2112 int max;
2113
2114 max = channel_recv_limit(chn->chn) - buffer_len(chn->chn->buf);
2115 if (max > len - l)
2116 max = len - l;
2117
2118 ret = bi_putblk(chn->chn, str+l, max);
2119 if (ret == -2 || ret == -3) {
2120 lua_pushinteger(L, -1);
2121 return 1;
2122 }
2123 if (ret == -1)
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002124 WILL_LJMP(hlua_yieldk(L, 0, 0, _hlua_channel_append, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002125 l += ret;
2126 lua_pop(L, 1);
2127 lua_pushinteger(L, l);
2128
2129 max = channel_recv_limit(chn->chn) - buffer_len(chn->chn->buf);
2130 if (max == 0 && chn->chn->buf->o == 0) {
2131 /* There are no space avalaible, and the output buffer is empty.
2132 * in this case, we cannot add more data, so we cannot yield,
2133 * we return the amount of copyied data.
2134 */
2135 return 1;
2136 }
2137 if (l < len)
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002138 WILL_LJMP(hlua_yieldk(L, 0, 0, _hlua_channel_append, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002139 return 1;
2140}
2141
2142/* just a wrapper of "_hlua_channel_append". It returns the length
2143 * of the writed string, or -1 if the channel is closed or if the
2144 * buffer size is too little for the data.
2145 */
2146__LJMP static int hlua_channel_append(lua_State *L)
2147{
2148 MAY_LJMP(check_args(L, 2, "append"));
2149 lua_pushinteger(L, 0);
2150
2151 return MAY_LJMP(_hlua_channel_append(L));
2152}
2153
2154/* just a wrapper of "_hlua_channel_append". This wrapper starts
2155 * his process by cleaning the buffer. The result is a replacement
2156 * of the current data. It returns the length of the writed string,
2157 * or -1 if the channel is closed or if the buffer size is too
2158 * little for the data.
2159 */
2160__LJMP static int hlua_channel_set(lua_State *L)
2161{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002162 struct hlua_channel *chn;
2163
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002164 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002165 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002166 lua_pushinteger(L, 0);
2167
2168 chn->chn->buf->i = 0;
2169
2170 return MAY_LJMP(_hlua_channel_append(L));
2171}
2172
2173/* Append data in the output side of the buffer. This data is immediatly
2174 * sent. The fcuntion returns the ammount of data writed. If the buffer
2175 * cannot contains the data, the function yield. The function returns -1
2176 * if the channel is closed.
2177 */
2178__LJMP static int _hlua_channel_send(lua_State *L)
2179{
2180 struct hlua_channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
2181 size_t len;
2182 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2183 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2184 int max;
2185
2186 if (unlikely(channel_output_closed(chn->chn))) {
2187 lua_pushinteger(L, -1);
2188 return 1;
2189 }
2190
2191 max = channel_recv_limit(chn->chn) - buffer_len(chn->chn->buf);
2192 if (max > len - l)
2193 max = len - l;
2194
Thierry FOURNIER506e46c2015-03-04 11:44:47 +01002195 max = buffer_replace2(chn->chn->buf, chn->chn->buf->p, chn->chn->buf->p, str+l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002196 /* buffer replace considers that the input part is filled.
2197 * so, I must forward these new data in the output part.
2198 */
2199 b_adv(chn->chn->buf, max);
2200
2201 l += max;
2202 lua_pop(L, 1);
2203 lua_pushinteger(L, l);
2204
2205 max = channel_recv_limit(chn->chn) - buffer_len(chn->chn->buf);
2206 if (max == 0 && chn->chn->buf->o == 0) {
2207 /* There are no space avalaible, and the output buffer is empty.
2208 * in this case, we cannot add more data, so we cannot yield,
2209 * we return the amount of copyied data.
2210 */
2211 return 1;
2212 }
2213 if (l < len)
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002214 WILL_LJMP(hlua_yieldk(L, 0, 0, _hlua_channel_send, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002215
2216 return 1;
2217}
2218
2219/* Just a wraper of "_hlua_channel_send". This wrapper permits
2220 * yield the LUA process, and resume it without checking the
2221 * input arguments.
2222 */
2223__LJMP static int hlua_channel_send(lua_State *L)
2224{
2225 MAY_LJMP(check_args(L, 2, "send"));
2226 lua_pushinteger(L, 0);
2227
2228 return MAY_LJMP(_hlua_channel_send(L));
2229}
2230
2231/* This function forward and amount of butes. The data pass from
2232 * the input side of the buffer to the output side, and can be
2233 * forwarded. This function never fails.
2234 *
2235 * The Lua function takes an amount of bytes to be forwarded in
2236 * imput. It returns the number of bytes forwarded.
2237 */
2238__LJMP static int hlua_channel_forward_yield(lua_State *L)
2239{
2240 struct hlua_channel *chn;
2241 int len;
2242 int l;
2243 int max;
2244
2245 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2246 len = MAY_LJMP(luaL_checkinteger(L, 2));
2247 l = MAY_LJMP(luaL_checkinteger(L, -1));
2248
2249 max = len - l;
2250 if (max > chn->chn->buf->i)
2251 max = chn->chn->buf->i;
2252 channel_forward(chn->chn, max);
2253 l += max;
2254
2255 lua_pop(L, 1);
2256 lua_pushinteger(L, l);
2257
2258 /* Check if it miss bytes to forward. */
2259 if (l < len) {
2260 /* The the input channel or the output channel are closed, we
2261 * must return the amount of data forwarded.
2262 */
2263 if (channel_input_closed(chn->chn) || channel_output_closed(chn->chn))
2264 return 1;
2265
2266 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002267 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002268 }
2269
2270 return 1;
2271}
2272
2273/* Just check the input and prepare the stack for the previous
2274 * function "hlua_channel_forward_yield"
2275 */
2276__LJMP static int hlua_channel_forward(lua_State *L)
2277{
2278 MAY_LJMP(check_args(L, 2, "forward"));
2279 MAY_LJMP(hlua_checkchannel(L, 1));
2280 MAY_LJMP(luaL_checkinteger(L, 2));
2281
2282 lua_pushinteger(L, 0);
2283 return MAY_LJMP(hlua_channel_forward_yield(L));
2284}
2285
2286/* Just returns the number of bytes available in the input
2287 * side of the buffer. This function never fails.
2288 */
2289__LJMP static int hlua_channel_get_in_len(lua_State *L)
2290{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002291 struct hlua_channel *chn;
2292
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002293 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002294 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002295 lua_pushinteger(L, chn->chn->buf->i);
2296 return 1;
2297}
2298
2299/* Just returns the number of bytes available in the output
2300 * side of the buffer. This function never fails.
2301 */
2302__LJMP static int hlua_channel_get_out_len(lua_State *L)
2303{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002304 struct hlua_channel *chn;
2305
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002306 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002307 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002308 lua_pushinteger(L, chn->chn->buf->o);
2309 return 1;
2310}
2311
2312
2313/*
2314 *
2315 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002316 * Class TXN
2317 *
2318 *
2319 */
2320
2321/* Returns a struct hlua_session if the stack entry "ud" is
2322 * a class session, otherwise it throws an error.
2323 */
2324__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
2325{
2326 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
2327}
2328
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002329__LJMP static int hlua_setpriv(lua_State *L)
2330{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002331 struct hlua *hlua;
2332
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002333 MAY_LJMP(check_args(L, 2, "set_priv"));
2334
2335 /* It is useles to retrieve the session, but this function
2336 * runs only in a session context.
2337 */
2338 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002339 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002340
2341 /* Remove previous value. */
2342 if (hlua->Mref != -1)
2343 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
2344
2345 /* Get and store new value. */
2346 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
2347 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
2348
2349 return 0;
2350}
2351
2352__LJMP static int hlua_getpriv(lua_State *L)
2353{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002354 struct hlua *hlua;
2355
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002356 MAY_LJMP(check_args(L, 1, "get_priv"));
2357
2358 /* It is useles to retrieve the session, but this function
2359 * runs only in a session context.
2360 */
2361 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002362 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002363
2364 /* Push configuration index in the stack. */
2365 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
2366
2367 return 1;
2368}
2369
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002370/* Create stack entry containing a class TXN. This function
2371 * return 0 if the stack does not contains free slots,
2372 * otherwise it returns 1.
2373 */
2374static int hlua_txn_new(lua_State *L, struct session *s, struct proxy *p, void *l7)
2375{
2376 struct hlua_txn *hs;
2377
2378 /* Check stack size. */
2379 if (!lua_checkstack(L, 2))
2380 return 0;
2381
2382 /* NOTE: The allocation never fails. The failure
2383 * throw an error, and the function never returns.
2384 * if the throw is not avalaible, the process is aborted.
2385 */
2386 hs = lua_newuserdata(L, sizeof(struct hlua_txn));
2387 hs->s = s;
2388 hs->p = p;
2389 hs->l7 = l7;
2390
2391 /* Pop a class sesison metatable and affect it to the userdata. */
2392 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
2393 lua_setmetatable(L, -2);
2394
2395 return 1;
2396}
2397
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002398/* This function returns a channel object associated
2399 * with the request channel. This function never fails,
2400 * however if the stack is full, it throws an error.
2401 */
2402__LJMP static int hlua_txn_req_channel(lua_State *L)
2403{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002404 struct hlua_txn *s;
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002405
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002406 MAY_LJMP(check_args(L, 1, "req_channel"));
2407 s = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002408
2409 if (!hlua_channel_new(L, s->s->req))
2410 WILL_LJMP(luaL_error(L, "full stack"));
2411
2412 return 1;
2413}
2414
2415/* This function returns a channel object associated
2416 * with the response channel. This function never fails,
2417 * however if the stack is full, it throws an error.
2418 */
2419__LJMP static int hlua_txn_res_channel(lua_State *L)
2420{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002421 struct hlua_txn *s;
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002422
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002423 MAY_LJMP(check_args(L, 1, "req_channel"));
2424 s = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002425
2426 if (!hlua_channel_new(L, s->s->rep))
2427 WILL_LJMP(luaL_error(L, "full stack"));
2428
2429 return 1;
2430}
2431
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002432/* This function is an Lua binding that send pending data
2433 * to the client, and close the stream interface.
2434 */
2435__LJMP static int hlua_txn_close(lua_State *L)
2436{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002437 struct hlua_txn *s;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002438
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002439 MAY_LJMP(check_args(L, 1, "close"));
2440 s = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002441
2442 channel_abort(s->s->si[0].ib);
2443 channel_auto_close(s->s->si[0].ib);
2444 channel_erase(s->s->si[0].ib);
2445 channel_auto_read(s->s->si[0].ob);
2446 channel_auto_close(s->s->si[0].ob);
2447 channel_shutr_now(s->s->si[0].ob);
2448
2449 return 0;
2450}
2451
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01002452/* This function is an LUA binding. It is called with each sample-fetch.
2453 * It uses closure argument to store the associated sample-fetch. It
Cyril Bonté928ae5c2015-03-02 00:08:41 +01002454 * returns only one argument or throws an error. An error is thrown
2455 * only if an error is encountered during the argument parsing. If
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01002456 * the "sample-fetch" function fails, nil is returned.
2457 */
2458__LJMP static int hlua_run_sample_fetch(lua_State *L)
2459{
2460 struct hlua_txn *s;
2461 struct hlua_sample_fetch *f;
Cyril Bonté928ae5c2015-03-02 00:08:41 +01002462 struct arg args[ARGM_NBARGS + 1];
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01002463 int i;
2464 struct sample smp;
2465
2466 /* Get closure arguments. */
2467 f = (struct hlua_sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
2468
2469 /* Get traditionnal arguments. */
2470 s = MAY_LJMP(hlua_checktxn(L, 1));
2471
2472 /* Get extra arguments. */
Cyril Bonté928ae5c2015-03-02 00:08:41 +01002473 for (i = 0; i < lua_gettop(L) - 1; i++) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01002474 if (i >= ARGM_NBARGS)
2475 break;
2476 hlua_lua2arg(L, i + 2, &args[i]);
2477 }
2478 args[i].type = ARGT_STOP;
2479
2480 /* Check arguments. */
2481 MAY_LJMP(hlua_lua2arg_check(L, 1, args, f->f->arg_mask));
2482
Cyril Bonté928ae5c2015-03-02 00:08:41 +01002483 /* Run the special args checker. */
2484 if (f->f->val_args && !f->f->val_args(args, NULL)) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01002485 lua_pushfstring(L, "error in arguments");
2486 WILL_LJMP(lua_error(L));
2487 }
2488
2489 /* Initialise the sample. */
2490 memset(&smp, 0, sizeof(smp));
2491
2492 /* Run the sample fetch process. */
2493 if (!f->f->process(s->p, s->s, s->l7, 0, args, &smp, f->f->kw, f->f->private)) {
2494 lua_pushnil(L);
2495 return 1;
2496 }
2497
2498 /* Convert the returned sample in lua value. */
2499 hlua_smp2lua(L, &smp);
2500 return 1;
2501}
2502
Thierry FOURNIER9a819e72015-02-16 20:22:55 +01002503/* This function is an LUA binding. It creates ans returns
2504 * an array of HTTP headers. This function does not fails.
2505 */
2506static int hlua_session_getheaders(lua_State *L)
2507{
2508 struct hlua_txn *s = MAY_LJMP(hlua_checktxn(L, 1));
2509 struct session *sess = s->s;
2510 const char *cur_ptr, *cur_next, *p;
2511 int old_idx, cur_idx;
2512 struct hdr_idx_elem *cur_hdr;
2513 const char *hn, *hv;
2514 int hnl, hvl;
2515
2516 /* Create the table. */
2517 lua_newtable(L);
2518
2519 /* Build array of headers. */
2520 old_idx = 0;
2521 cur_next = sess->req->buf->p + hdr_idx_first_pos(&sess->txn.hdr_idx);
2522
2523 while (1) {
2524 cur_idx = sess->txn.hdr_idx.v[old_idx].next;
2525 if (!cur_idx)
2526 break;
2527 old_idx = cur_idx;
2528
2529 cur_hdr = &sess->txn.hdr_idx.v[cur_idx];
2530 cur_ptr = cur_next;
2531 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
2532
2533 /* Now we have one full header at cur_ptr of len cur_hdr->len,
2534 * and the next header starts at cur_next. We'll check
2535 * this header in the list as well as against the default
2536 * rule.
2537 */
2538
2539 /* look for ': *'. */
2540 hn = cur_ptr;
2541 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
2542 if (p >= cur_ptr+cur_hdr->len)
2543 continue;
2544 hnl = p - hn;
2545 p++;
2546 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
2547 p++;
2548 if (p >= cur_ptr+cur_hdr->len)
2549 continue;
2550 hv = p;
2551 hvl = cur_ptr+cur_hdr->len-p;
2552
2553 /* Push values in the table. */
2554 lua_pushlstring(L, hn, hnl);
2555 lua_pushlstring(L, hv, hvl);
2556 lua_settable(L, -3);
2557 }
2558
2559 return 1;
2560}
2561
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002562__LJMP static int hlua_sleep_yield(lua_State *L)
2563{
2564 int wakeup_ms = lua_tointeger(L, -1);
2565 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002566 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002567 return 0;
2568}
2569
2570__LJMP static int hlua_sleep(lua_State *L)
2571{
2572 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002573 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002574
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002575 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002576
2577 delay = MAY_LJMP(luaL_checkunsigned(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002578 wakeup_ms = tick_add(now_ms, delay);
2579 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002580
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002581 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
2582 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002583}
2584
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002585__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002586{
2587 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002588 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002589
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002590 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002591
2592 delay = MAY_LJMP(luaL_checkunsigned(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002593 wakeup_ms = tick_add(now_ms, delay);
2594 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002595
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002596 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
2597 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002598}
2599
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01002600/* This functionis an LUA binding. it permits to give back
2601 * the hand at the HAProxy scheduler. It is used when the
2602 * LUA processing consumes a lot of time.
2603 */
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002604__LJMP static int hlua_yield_yield(lua_State *L)
2605{
2606 return 0;
2607}
2608
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01002609__LJMP static int hlua_yield(lua_State *L)
2610{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002611 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
2612 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01002613}
2614
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002615/* This function change the nice of the currently executed
2616 * task. It is used set low or high priority at the current
2617 * task.
2618 */
2619__LJMP static int hlua_setnice(lua_State *L)
2620{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002621 struct hlua *hlua;
2622 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002623
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002624 MAY_LJMP(check_args(L, 1, "set_nice"));
2625 hlua = hlua_gethlua(L);
2626 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002627
2628 /* If he task is not set, I'm in a start mode. */
2629 if (!hlua || !hlua->task)
2630 return 0;
2631
2632 if (nice < -1024)
2633 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002634 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002635 nice = 1024;
2636
2637 hlua->task->nice = nice;
2638 return 0;
2639}
2640
Thierry FOURNIER24f33532015-01-23 12:13:00 +01002641/* This function is used as a calback of a task. It is called by the
2642 * HAProxy task subsystem when the task is awaked. The LUA runtime can
2643 * return an E_AGAIN signal, the emmiter of this signal must set a
2644 * signal to wake the task.
2645 */
2646static struct task *hlua_process_task(struct task *task)
2647{
2648 struct hlua *hlua = task->context;
2649 enum hlua_exec status;
2650
2651 /* We need to remove the task from the wait queue before executing
2652 * the Lua code because we don't know if it needs to wait for
2653 * another timer or not in the case of E_AGAIN.
2654 */
2655 task_delete(task);
2656
Thierry FOURNIERbd413492015-03-03 16:52:26 +01002657 /* If it is the first call to the task, we must initialize the
2658 * execution timeouts.
2659 */
2660 if (!HLUA_IS_RUNNING(hlua))
2661 hlua->expire = tick_add(now_ms, hlua_timeout_task);
2662
Thierry FOURNIER24f33532015-01-23 12:13:00 +01002663 /* Execute the Lua code. */
2664 status = hlua_ctx_resume(hlua, 1);
2665
2666 switch (status) {
2667 /* finished or yield */
2668 case HLUA_E_OK:
2669 hlua_ctx_destroy(hlua);
2670 task_delete(task);
2671 task_free(task);
2672 break;
2673
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01002674 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
2675 if (hlua->wake_time != TICK_ETERNITY)
2676 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01002677 break;
2678
2679 /* finished with error. */
2680 case HLUA_E_ERRMSG:
2681 send_log(NULL, LOG_ERR, "Lua task: %s.", lua_tostring(hlua->T, -1));
2682 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2683 Alert("Lua task: %s.\n", lua_tostring(hlua->T, -1));
2684 hlua_ctx_destroy(hlua);
2685 task_delete(task);
2686 task_free(task);
2687 break;
2688
2689 case HLUA_E_ERR:
2690 default:
2691 send_log(NULL, LOG_ERR, "Lua task: unknown error.");
2692 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2693 Alert("Lua task: unknown error.\n");
2694 hlua_ctx_destroy(hlua);
2695 task_delete(task);
2696 task_free(task);
2697 break;
2698 }
2699 return NULL;
2700}
2701
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01002702/* This function is an LUA binding that register LUA function to be
2703 * executed after the HAProxy configuration parsing and before the
2704 * HAProxy scheduler starts. This function expect only one LUA
2705 * argument that is a function. This function returns nothing, but
2706 * throws if an error is encountered.
2707 */
2708__LJMP static int hlua_register_init(lua_State *L)
2709{
2710 struct hlua_init_function *init;
2711 int ref;
2712
2713 MAY_LJMP(check_args(L, 1, "register_init"));
2714
2715 ref = MAY_LJMP(hlua_checkfunction(L, 1));
2716
2717 init = malloc(sizeof(*init));
2718 if (!init)
2719 WILL_LJMP(luaL_error(L, "lua out of memory error."));
2720
2721 init->function_ref = ref;
2722 LIST_ADDQ(&hlua_init_functions, &init->l);
2723 return 0;
2724}
2725
Thierry FOURNIER24f33532015-01-23 12:13:00 +01002726/* This functio is an LUA binding. It permits to register a task
2727 * executed in parallel of the main HAroxy activity. The task is
2728 * created and it is set in the HAProxy scheduler. It can be called
2729 * from the "init" section, "post init" or during the runtime.
2730 *
2731 * Lua prototype:
2732 *
2733 * <none> core.register_task(<function>)
2734 */
2735static int hlua_register_task(lua_State *L)
2736{
2737 struct hlua *hlua;
2738 struct task *task;
2739 int ref;
2740
2741 MAY_LJMP(check_args(L, 1, "register_task"));
2742
2743 ref = MAY_LJMP(hlua_checkfunction(L, 1));
2744
2745 hlua = malloc(sizeof(*hlua));
2746 if (!hlua)
2747 WILL_LJMP(luaL_error(L, "lua out of memory error."));
2748
2749 task = task_new();
2750 task->context = hlua;
2751 task->process = hlua_process_task;
2752
2753 if (!hlua_ctx_init(hlua, task))
2754 WILL_LJMP(luaL_error(L, "lua out of memory error."));
2755
2756 /* Restore the function in the stack. */
2757 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
2758 hlua->nargs = 0;
2759
2760 /* Schedule task. */
2761 task_schedule(task, now_ms);
2762
2763 return 0;
2764}
2765
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01002766/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
2767 * doesn't allow "yield" functions because the HAProxy engine cannot
2768 * resume converters.
2769 */
2770static int hlua_sample_conv_wrapper(struct session *session, const struct arg *arg_p,
2771 struct sample *smp, void *private)
2772{
2773 struct hlua_function *fcn = (struct hlua_function *)private;
2774
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01002775 /* In the execution wrappers linked with a session, the
2776 * Lua context can be not initialized. This behavior
2777 * permits to save performances because a systematic
2778 * Lua initialization cause 5% performances loss.
2779 */
2780 if (!session->hlua.T && !hlua_ctx_init(&session->hlua, session->task)) {
2781 send_log(session->be, LOG_ERR, "Lua converter '%s': can't initialize Lua context.", fcn->name);
2782 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2783 Alert("Lua converter '%s': can't initialize Lua context.\n", fcn->name);
2784 return 0;
2785 }
2786
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01002787 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01002788 if (!HLUA_IS_RUNNING(&session->hlua)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01002789 /* Check stack available size. */
2790 if (!lua_checkstack(session->hlua.T, 1)) {
2791 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
2792 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2793 Alert("Lua converter '%s': full stack.\n", fcn->name);
2794 return 0;
2795 }
2796
2797 /* Restore the function in the stack. */
2798 lua_rawgeti(session->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
2799
2800 /* convert input sample and pust-it in the stack. */
2801 if (!lua_checkstack(session->hlua.T, 1)) {
2802 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
2803 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2804 Alert("Lua converter '%s': full stack.\n", fcn->name);
2805 return 0;
2806 }
2807 hlua_smp2lua(session->hlua.T, smp);
2808 session->hlua.nargs = 2;
2809
2810 /* push keywords in the stack. */
2811 if (arg_p) {
2812 for (; arg_p->type != ARGT_STOP; arg_p++) {
2813 if (!lua_checkstack(session->hlua.T, 1)) {
2814 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
2815 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2816 Alert("Lua converter '%s': full stack.\n", fcn->name);
2817 return 0;
2818 }
2819 hlua_arg2lua(session->hlua.T, arg_p);
2820 session->hlua.nargs++;
2821 }
2822 }
2823
Thierry FOURNIERbd413492015-03-03 16:52:26 +01002824 /* We must initialize the execution timeouts. */
2825 session->hlua.expire = tick_add(now_ms, hlua_timeout_session);
2826
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01002827 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01002828 HLUA_SET_RUN(&session->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01002829 }
2830
2831 /* Execute the function. */
2832 switch (hlua_ctx_resume(&session->hlua, 0)) {
2833 /* finished. */
2834 case HLUA_E_OK:
2835 /* Convert the returned value in sample. */
2836 hlua_lua2smp(session->hlua.T, -1, smp);
2837 lua_pop(session->hlua.T, 1);
2838 return 1;
2839
2840 /* yield. */
2841 case HLUA_E_AGAIN:
2842 send_log(session->be, LOG_ERR, "Lua converter '%s': cannot use yielded functions.", fcn->name);
2843 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2844 Alert("Lua converter '%s': cannot use yielded functions.\n", fcn->name);
2845 return 0;
2846
2847 /* finished with error. */
2848 case HLUA_E_ERRMSG:
2849 /* Display log. */
2850 send_log(session->be, LOG_ERR, "Lua converter '%s': %s.", fcn->name, lua_tostring(session->hlua.T, -1));
2851 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2852 Alert("Lua converter '%s': %s.\n", fcn->name, lua_tostring(session->hlua.T, -1));
2853 lua_pop(session->hlua.T, 1);
2854 return 0;
2855
2856 case HLUA_E_ERR:
2857 /* Display log. */
2858 send_log(session->be, LOG_ERR, "Lua converter '%s' returns an unknown error.", fcn->name);
2859 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2860 Alert("Lua converter '%s' returns an unknown error.\n", fcn->name);
2861
2862 default:
2863 return 0;
2864 }
2865}
2866
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01002867/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
2868 * doesn't allow "yield" functions because the HAProxy engine cannot
2869 * resume sample-fetches.
2870 */
2871static int hlua_sample_fetch_wrapper(struct proxy *px, struct session *s, void *l7,
2872 unsigned int opt, const struct arg *arg_p,
2873 struct sample *smp, const char *kw, void *private)
2874{
2875 struct hlua_function *fcn = (struct hlua_function *)private;
2876
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01002877 /* In the execution wrappers linked with a session, the
2878 * Lua context can be not initialized. This behavior
2879 * permits to save performances because a systematic
2880 * Lua initialization cause 5% performances loss.
2881 */
2882 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
2883 send_log(s->be, LOG_ERR, "Lua sample-fetch '%s': can't initialize Lua context.", fcn->name);
2884 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2885 Alert("Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
2886 return 0;
2887 }
2888
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01002889 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01002890 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01002891 /* Check stack available size. */
2892 if (!lua_checkstack(s->hlua.T, 2)) {
2893 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
2894 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2895 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
2896 return 0;
2897 }
2898
2899 /* Restore the function in the stack. */
2900 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
2901
2902 /* push arguments in the stack. */
2903 if (!hlua_txn_new(s->hlua.T, s, px, l7)) {
2904 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
2905 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2906 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
2907 return 0;
2908 }
2909 s->hlua.nargs = 1;
2910
2911 /* push keywords in the stack. */
2912 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
2913 /* Check stack available size. */
2914 if (!lua_checkstack(s->hlua.T, 1)) {
2915 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
2916 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2917 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
2918 return 0;
2919 }
2920 if (!lua_checkstack(s->hlua.T, 1)) {
2921 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
2922 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2923 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
2924 return 0;
2925 }
2926 hlua_arg2lua(s->hlua.T, arg_p);
2927 s->hlua.nargs++;
2928 }
2929
Thierry FOURNIERbd413492015-03-03 16:52:26 +01002930 /* We must initialize the execution timeouts. */
2931 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
2932
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01002933 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01002934 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01002935 }
2936
2937 /* Execute the function. */
2938 switch (hlua_ctx_resume(&s->hlua, 0)) {
2939 /* finished. */
2940 case HLUA_E_OK:
2941 /* Convert the returned value in sample. */
2942 hlua_lua2smp(s->hlua.T, -1, smp);
2943 lua_pop(s->hlua.T, 1);
2944
2945 /* Set the end of execution flag. */
2946 smp->flags &= ~SMP_F_MAY_CHANGE;
2947 return 1;
2948
2949 /* yield. */
2950 case HLUA_E_AGAIN:
2951 send_log(px, LOG_ERR, "Lua sample-fetch '%s': cannot use yielded functions.", fcn->name);
2952 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2953 Alert("Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
2954 return 0;
2955
2956 /* finished with error. */
2957 case HLUA_E_ERRMSG:
2958 /* Display log. */
2959 send_log(px, LOG_ERR, "Lua sample-fetch '%s': %s.", fcn->name, lua_tostring(s->hlua.T, -1));
2960 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2961 Alert("Lua sample-fetch '%s': %s.\n", fcn->name, lua_tostring(s->hlua.T, -1));
2962 lua_pop(s->hlua.T, 1);
2963 return 0;
2964
2965 case HLUA_E_ERR:
2966 /* Display log. */
2967 send_log(px, LOG_ERR, "Lua sample-fetch '%s' returns an unknown error.", fcn->name);
2968 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2969 Alert("Lua sample-fetch '%s': returns an unknown error.\n", fcn->name);
2970
2971 default:
2972 return 0;
2973 }
2974}
2975
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01002976/* This function is an LUA binding used for registering
2977 * "sample-conv" functions. It expects a converter name used
2978 * in the haproxy configuration file, and an LUA function.
2979 */
2980__LJMP static int hlua_register_converters(lua_State *L)
2981{
2982 struct sample_conv_kw_list *sck;
2983 const char *name;
2984 int ref;
2985 int len;
2986 struct hlua_function *fcn;
2987
2988 MAY_LJMP(check_args(L, 2, "register_converters"));
2989
2990 /* First argument : converter name. */
2991 name = MAY_LJMP(luaL_checkstring(L, 1));
2992
2993 /* Second argument : lua function. */
2994 ref = MAY_LJMP(hlua_checkfunction(L, 2));
2995
2996 /* Allocate and fill the sample fetch keyword struct. */
2997 sck = malloc(sizeof(struct sample_conv_kw_list) +
2998 sizeof(struct sample_conv) * 2);
2999 if (!sck)
3000 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3001 fcn = malloc(sizeof(*fcn));
3002 if (!fcn)
3003 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3004
3005 /* Fill fcn. */
3006 fcn->name = strdup(name);
3007 if (!fcn->name)
3008 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3009 fcn->function_ref = ref;
3010
3011 /* List head */
3012 sck->list.n = sck->list.p = NULL;
3013
3014 /* converter keyword. */
3015 len = strlen("lua.") + strlen(name) + 1;
3016 sck->kw[0].kw = malloc(len);
3017 if (!sck->kw[0].kw)
3018 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3019
3020 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
3021 sck->kw[0].process = hlua_sample_conv_wrapper;
3022 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
3023 sck->kw[0].val_args = NULL;
3024 sck->kw[0].in_type = SMP_T_STR;
3025 sck->kw[0].out_type = SMP_T_STR;
3026 sck->kw[0].private = fcn;
3027
3028 /* End of array. */
3029 memset(&sck->kw[1], 0, sizeof(struct sample_conv));
3030
3031 /* Register this new converter */
3032 sample_register_convs(sck);
3033
3034 return 0;
3035}
3036
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003037/* This fucntion is an LUA binding used for registering
3038 * "sample-fetch" functions. It expects a converter name used
3039 * in the haproxy configuration file, and an LUA function.
3040 */
3041__LJMP static int hlua_register_fetches(lua_State *L)
3042{
3043 const char *name;
3044 int ref;
3045 int len;
3046 struct sample_fetch_kw_list *sfk;
3047 struct hlua_function *fcn;
3048
3049 MAY_LJMP(check_args(L, 2, "register_fetches"));
3050
3051 /* First argument : sample-fetch name. */
3052 name = MAY_LJMP(luaL_checkstring(L, 1));
3053
3054 /* Second argument : lua function. */
3055 ref = MAY_LJMP(hlua_checkfunction(L, 2));
3056
3057 /* Allocate and fill the sample fetch keyword struct. */
3058 sfk = malloc(sizeof(struct sample_fetch_kw_list) +
3059 sizeof(struct sample_fetch) * 2);
3060 if (!sfk)
3061 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3062 fcn = malloc(sizeof(*fcn));
3063 if (!fcn)
3064 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3065
3066 /* Fill fcn. */
3067 fcn->name = strdup(name);
3068 if (!fcn->name)
3069 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3070 fcn->function_ref = ref;
3071
3072 /* List head */
3073 sfk->list.n = sfk->list.p = NULL;
3074
3075 /* sample-fetch keyword. */
3076 len = strlen("lua.") + strlen(name) + 1;
3077 sfk->kw[0].kw = malloc(len);
3078 if (!sfk->kw[0].kw)
3079 return luaL_error(L, "lua out of memory error.");
3080
3081 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
3082 sfk->kw[0].process = hlua_sample_fetch_wrapper;
3083 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
3084 sfk->kw[0].val_args = NULL;
3085 sfk->kw[0].out_type = SMP_T_STR;
3086 sfk->kw[0].use = SMP_USE_HTTP_ANY;
3087 sfk->kw[0].val = 0;
3088 sfk->kw[0].private = fcn;
3089
3090 /* End of array. */
3091 memset(&sfk->kw[1], 0, sizeof(struct sample_fetch));
3092
3093 /* Register this new fetch. */
3094 sample_register_fetches(sfk);
3095
3096 return 0;
3097}
3098
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003099/* global {tcp|http}-request parser. Return 1 in succes case, else return 0. */
3100static int hlua_parse_rule(const char **args, int *cur_arg, struct proxy *px,
3101 struct hlua_rule **rule_p, char **err)
3102{
3103 struct hlua_rule *rule;
3104
3105 /* Memory for the rule. */
3106 rule = malloc(sizeof(*rule));
3107 if (!rule) {
3108 memprintf(err, "out of memory error");
3109 return 0;
3110 }
3111 *rule_p = rule;
3112
3113 /* The requiered arg is a function name. */
3114 if (!args[*cur_arg]) {
3115 memprintf(err, "expect Lua function name");
3116 return 0;
3117 }
3118
3119 /* Lookup for the symbol, and check if it is a function. */
3120 lua_getglobal(gL.T, args[*cur_arg]);
3121 if (lua_isnil(gL.T, -1)) {
3122 lua_pop(gL.T, 1);
3123 memprintf(err, "Lua function '%s' not found", args[*cur_arg]);
3124 return 0;
3125 }
3126 if (!lua_isfunction(gL.T, -1)) {
3127 lua_pop(gL.T, 1);
3128 memprintf(err, "'%s' is not a function", args[*cur_arg]);
3129 return 0;
3130 }
3131
3132 /* Reference the Lua function and store the reference. */
3133 rule->fcn.function_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
3134 rule->fcn.name = strdup(args[*cur_arg]);
3135 if (!rule->fcn.name) {
3136 memprintf(err, "out of memory error.");
3137 return 0;
3138 }
3139 (*cur_arg)++;
3140
3141 /* TODO: later accept arguments. */
3142 rule->args = NULL;
3143
3144 return 1;
3145}
3146
3147/* This function is a wrapper to execute each LUA function declared
3148 * as an action wrapper during the initialisation period. This function
3149 * return 1 if the processing is finished (with oe without error) and
3150 * return 0 if the function must be called again because the LUA
3151 * returns a yield.
3152 */
3153static int hlua_request_act_wrapper(struct hlua_rule *rule, struct proxy *px,
3154 struct session *s, struct http_txn *http_txn,
3155 unsigned int analyzer)
3156{
3157 char **arg;
3158
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003159 /* In the execution wrappers linked with a session, the
3160 * Lua context can be not initialized. This behavior
3161 * permits to save performances because a systematic
3162 * Lua initialization cause 5% performances loss.
3163 */
3164 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
3165 send_log(px, LOG_ERR, "Lua action '%s': can't initialize Lua context.", rule->fcn.name);
3166 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3167 Alert("Lua action '%s': can't initialize Lua context.\n", rule->fcn.name);
3168 return 0;
3169 }
3170
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003171 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003172 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003173 /* Check stack available size. */
3174 if (!lua_checkstack(s->hlua.T, 1)) {
3175 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
3176 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3177 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
3178 return 0;
3179 }
3180
3181 /* Restore the function in the stack. */
3182 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->fcn.function_ref);
3183
3184 /* Create and and push object session in the stack. */
3185 if (!hlua_txn_new(s->hlua.T, s, px, http_txn)) {
3186 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
3187 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3188 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
3189 return 0;
3190 }
3191 s->hlua.nargs = 1;
3192
3193 /* push keywords in the stack. */
3194 for (arg = rule->args; arg && *arg; arg++) {
3195 if (!lua_checkstack(s->hlua.T, 1)) {
3196 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
3197 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3198 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
3199 return 0;
3200 }
3201 lua_pushstring(s->hlua.T, *arg);
3202 s->hlua.nargs++;
3203 }
3204
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003205 /* We must initialize the execution timeouts. */
3206 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
3207
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003208 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003209 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003210 }
3211
3212 /* Execute the function. */
3213 switch (hlua_ctx_resume(&s->hlua, 1)) {
3214 /* finished. */
3215 case HLUA_E_OK:
3216 return 1;
3217
3218 /* yield. */
3219 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003220 /* Set timeout in the required channel. */
3221 if (s->hlua.wake_time != TICK_ETERNITY) {
3222 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
3223 s->req->analyse_exp = s->hlua.wake_time;
3224 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
3225 s->rep->analyse_exp = s->hlua.wake_time;
3226 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003227 /* Some actions can be wake up when a "write" event
3228 * is detected on a response channel. This is useful
3229 * only for actions targetted on the requests.
3230 */
3231 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)) {
3232 s->rep->flags |= CF_WAKE_WRITE;
3233 s->rep->analysers |= analyzer;
3234 }
3235 return 0;
3236
3237 /* finished with error. */
3238 case HLUA_E_ERRMSG:
3239 /* Display log. */
3240 send_log(px, LOG_ERR, "Lua function '%s': %s.", rule->fcn.name, lua_tostring(s->hlua.T, -1));
3241 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3242 Alert("Lua function '%s': %s.\n", rule->fcn.name, lua_tostring(s->hlua.T, -1));
3243 lua_pop(s->hlua.T, 1);
3244 return 1;
3245
3246 case HLUA_E_ERR:
3247 /* Display log. */
3248 send_log(px, LOG_ERR, "Lua function '%s' return an unknown error.", rule->fcn.name);
3249 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3250 Alert("Lua function '%s' return an unknown error.\n", rule->fcn.name);
3251
3252 default:
3253 return 1;
3254 }
3255}
3256
3257/* Lua execution wrapper for "tcp-request". This function uses
3258 * "hlua_request_act_wrapper" for executing the LUA code.
3259 */
3260int hlua_tcp_req_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
3261 struct session *s)
3262{
3263 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
3264 px, s, NULL, AN_REQ_INSPECT_FE);
3265}
3266
3267/* Lua execution wrapper for "tcp-response". This function uses
3268 * "hlua_request_act_wrapper" for executing the LUA code.
3269 */
3270int hlua_tcp_res_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
3271 struct session *s)
3272{
3273 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
3274 px, s, NULL, AN_RES_INSPECT);
3275}
3276
3277/* Lua execution wrapper for http-request.
3278 * This function uses "hlua_request_act_wrapper" for executing
3279 * the LUA code.
3280 */
3281int hlua_http_req_act_wrapper(struct http_req_rule *rule, struct proxy *px,
3282 struct session *s, struct http_txn *http_txn)
3283{
3284 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
3285 s, http_txn, AN_REQ_HTTP_PROCESS_FE);
3286}
3287
3288/* Lua execution wrapper for http-response.
3289 * This function uses "hlua_request_act_wrapper" for executing
3290 * the LUA code.
3291 */
3292int hlua_http_res_act_wrapper(struct http_res_rule *rule, struct proxy *px,
3293 struct session *s, struct http_txn *http_txn)
3294{
3295 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
3296 s, http_txn, AN_RES_HTTP_PROCESS_BE);
3297}
3298
3299/* tcp-request <*> configuration wrapper. */
3300static int tcp_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3301 struct tcp_rule *rule, char **err)
3302{
3303 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003304 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003305 rule->action = TCP_ACT_CUSTOM;
3306 rule->action_ptr = hlua_tcp_req_act_wrapper;
3307 return 1;
3308}
3309
3310/* tcp-response <*> configuration wrapper. */
3311static int tcp_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3312 struct tcp_rule *rule, char **err)
3313{
3314 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003315 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003316 rule->action = TCP_ACT_CUSTOM;
3317 rule->action_ptr = hlua_tcp_res_act_wrapper;
3318 return 1;
3319}
3320
3321/* http-request <*> configuration wrapper. */
3322static int http_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3323 struct http_req_rule *rule, char **err)
3324{
3325 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
3326 return -1;
3327 rule->action = HTTP_REQ_ACT_CUSTOM_CONT;
3328 rule->action_ptr = hlua_http_req_act_wrapper;
3329 return 1;
3330}
3331
3332/* http-response <*> configuration wrapper. */
3333static int http_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3334 struct http_res_rule *rule, char **err)
3335{
3336 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
3337 return -1;
3338 rule->action = HTTP_RES_ACT_CUSTOM_CONT;
3339 rule->action_ptr = hlua_http_res_act_wrapper;
3340 return 1;
3341}
3342
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003343static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
3344 struct proxy *defpx, const char *file, int line,
3345 char **err, unsigned int *timeout)
3346{
3347 const char *error;
3348
3349 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
3350 if (error && *error != '\0') {
3351 memprintf(err, "%s: invalid timeout", args[0]);
3352 return -1;
3353 }
3354 return 0;
3355}
3356
3357static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
3358 struct proxy *defpx, const char *file, int line,
3359 char **err)
3360{
3361 return hlua_read_timeout(args, section_type, curpx, defpx,
3362 file, line, err, &hlua_timeout_session);
3363}
3364
3365static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
3366 struct proxy *defpx, const char *file, int line,
3367 char **err)
3368{
3369 return hlua_read_timeout(args, section_type, curpx, defpx,
3370 file, line, err, &hlua_timeout_task);
3371}
3372
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01003373static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
3374 struct proxy *defpx, const char *file, int line,
3375 char **err)
3376{
3377 char *error;
3378
3379 hlua_nb_instruction = strtoll(args[1], &error, 10);
3380 if (*error != '\0') {
3381 memprintf(err, "%s: invalid number", args[0]);
3382 return -1;
3383 }
3384 return 0;
3385}
3386
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01003387/* This function is called by the main configuration key "lua-load". It loads and
3388 * execute an lua file during the parsing of the HAProxy configuration file. It is
3389 * the main lua entry point.
3390 *
3391 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
3392 * occured, otherwise it returns 0.
3393 *
3394 * In some error case, LUA set an error message in top of the stack. This function
3395 * returns this error message in the HAProxy logs and pop it from the stack.
3396 */
3397static int hlua_load(char **args, int section_type, struct proxy *curpx,
3398 struct proxy *defpx, const char *file, int line,
3399 char **err)
3400{
3401 int error;
3402
3403 /* Just load and compile the file. */
3404 error = luaL_loadfile(gL.T, args[1]);
3405 if (error) {
3406 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
3407 lua_pop(gL.T, 1);
3408 return -1;
3409 }
3410
3411 /* If no syntax error where detected, execute the code. */
3412 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
3413 switch (error) {
3414 case LUA_OK:
3415 break;
3416 case LUA_ERRRUN:
3417 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
3418 lua_pop(gL.T, 1);
3419 return -1;
3420 case LUA_ERRMEM:
3421 memprintf(err, "lua out of memory error\n");
3422 return -1;
3423 case LUA_ERRERR:
3424 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
3425 lua_pop(gL.T, 1);
3426 return -1;
3427 case LUA_ERRGCMM:
3428 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
3429 lua_pop(gL.T, 1);
3430 return -1;
3431 default:
3432 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
3433 lua_pop(gL.T, 1);
3434 return -1;
3435 }
3436
3437 return 0;
3438}
3439
3440/* configuration keywords declaration */
3441static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003442 { CFG_GLOBAL, "lua-load", hlua_load },
3443 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
3444 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01003445 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01003446 { 0, NULL, NULL },
3447}};
3448
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003449static struct http_req_action_kw_list http_req_kws = {"lua", { }, {
3450 { "lua", http_req_action_register_lua },
3451 { NULL, NULL }
3452}};
3453
3454static struct http_res_action_kw_list http_res_kws = {"lua", { }, {
3455 { "lua", http_res_action_register_lua },
3456 { NULL, NULL }
3457}};
3458
3459static struct tcp_action_kw_list tcp_req_cont_kws = {"lua", { }, {
3460 { "lua", tcp_req_action_register_lua },
3461 { NULL, NULL }
3462}};
3463
3464static struct tcp_action_kw_list tcp_res_cont_kws = {"lua", { }, {
3465 { "lua", tcp_res_action_register_lua },
3466 { NULL, NULL }
3467}};
3468
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003469int hlua_post_init()
3470{
3471 struct hlua_init_function *init;
3472 const char *msg;
3473 enum hlua_exec ret;
3474
3475 list_for_each_entry(init, &hlua_init_functions, l) {
3476 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
3477 ret = hlua_ctx_resume(&gL, 0);
3478 switch (ret) {
3479 case HLUA_E_OK:
3480 lua_pop(gL.T, -1);
3481 return 1;
3482 case HLUA_E_AGAIN:
3483 Alert("lua init: yield not allowed.\n");
3484 return 0;
3485 case HLUA_E_ERRMSG:
3486 msg = lua_tostring(gL.T, -1);
3487 Alert("lua init: %s.\n", msg);
3488 return 0;
3489 case HLUA_E_ERR:
3490 default:
3491 Alert("lua init: unknown runtime error.\n");
3492 return 0;
3493 }
3494 }
3495 return 1;
3496}
3497
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01003498void hlua_init(void)
3499{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003500 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01003501 int idx;
3502 struct sample_fetch *sf;
3503 struct hlua_sample_fetch *hsf;
3504 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003505#ifdef USE_OPENSSL
3506 char *args[4];
3507 struct srv_kw *kw;
3508 int tmp_error;
3509 char *error;
3510#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003511
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01003512 /* Initialise com signals pool session. */
3513 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
3514
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003515 /* Initialise sleep pool. */
3516 pool2_hlua_sleep = create_pool("hlua_sleep", sizeof(struct hlua_sleep), MEM_F_SHARED);
3517
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01003518 /* Register configuration keywords. */
3519 cfg_register_keywords(&cfg_kws);
3520
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003521 /* Register custom HTTP rules. */
3522 http_req_keywords_register(&http_req_kws);
3523 http_res_keywords_register(&http_res_kws);
3524 tcp_req_cont_keywords_register(&tcp_req_cont_kws);
3525 tcp_res_cont_keywords_register(&tcp_res_cont_kws);
3526
Thierry FOURNIER380d0932015-01-23 14:27:52 +01003527 /* Init main lua stack. */
3528 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003529 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01003530 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01003531 gL.T = luaL_newstate();
3532 hlua_sethlua(&gL);
3533 gL.Tref = LUA_REFNIL;
3534 gL.task = NULL;
3535
3536 /* Initialise lua. */
3537 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003538
3539 /*
3540 *
3541 * Create "core" object.
3542 *
3543 */
3544
3545 /* This integer entry is just used as base value for the object "core". */
3546 lua_pushinteger(gL.T, 0);
3547
3548 /* Create and fill the metatable. */
3549 lua_newtable(gL.T);
3550
3551 /* Create and fill the __index entry. */
3552 lua_pushstring(gL.T, "__index");
3553 lua_newtable(gL.T);
3554
3555 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003556 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003557 hlua_class_const_int(gL.T, log_levels[i], i);
3558
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003559 /* Register special functions. */
3560 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003561 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003562 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003563 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003564 hlua_class_function(gL.T, "yield", hlua_yield);
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003565 hlua_class_function(gL.T, "set_nice", hlua_setnice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003566 hlua_class_function(gL.T, "sleep", hlua_sleep);
3567 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01003568 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
3569 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
3570 hlua_class_function(gL.T, "set_map", hlua_set_map);
3571 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003572 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003573
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003574 /* Store the table __index in the metable. */
3575 lua_settable(gL.T, -3);
3576
3577 /* Register previous table in the registry with named entry. */
3578 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
3579 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CORE); /* register class session. */
3580
3581 /* Register previous table in the registry with reference. */
3582 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
3583 class_core_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
3584
3585 /* Create new object with class Core. */
3586 lua_setmetatable(gL.T, -2);
3587 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003588
3589 /*
3590 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003591 * Register class Channel
3592 *
3593 */
3594
3595 /* Create and fill the metatable. */
3596 lua_newtable(gL.T);
3597
3598 /* Create and fille the __index entry. */
3599 lua_pushstring(gL.T, "__index");
3600 lua_newtable(gL.T);
3601
3602 /* Register . */
3603 hlua_class_function(gL.T, "get", hlua_channel_get);
3604 hlua_class_function(gL.T, "dup", hlua_channel_dup);
3605 hlua_class_function(gL.T, "getline", hlua_channel_getline);
3606 hlua_class_function(gL.T, "set", hlua_channel_set);
3607 hlua_class_function(gL.T, "append", hlua_channel_append);
3608 hlua_class_function(gL.T, "send", hlua_channel_send);
3609 hlua_class_function(gL.T, "forward", hlua_channel_forward);
3610 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
3611 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
3612
3613 lua_settable(gL.T, -3);
3614
3615 /* Register previous table in the registry with reference and named entry. */
3616 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
3617 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
3618 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
3619
3620 /*
3621 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003622 * Register class TXN
3623 *
3624 */
3625
3626 /* Create and fill the metatable. */
3627 lua_newtable(gL.T);
3628
3629 /* Create and fille the __index entry. */
3630 lua_pushstring(gL.T, "__index");
3631 lua_newtable(gL.T);
3632
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01003633 /* Browse existing fetches and create the associated
3634 * object method.
3635 */
3636 sf = NULL;
3637 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
3638
3639 /* Dont register the keywork if the arguments check function are
3640 * not safe during the runtime.
3641 */
3642 if ((sf->val_args != NULL) &&
3643 (sf->val_args != val_payload_lv) &&
3644 (sf->val_args != val_hdr))
3645 continue;
3646
3647 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
3648 * by an underscore.
3649 */
3650 strncpy(trash.str, sf->kw, trash.size);
3651 trash.str[trash.size - 1] = '\0';
3652 for (p = trash.str; *p; p++)
3653 if (*p == '.' || *p == '-' || *p == '+')
3654 *p = '_';
3655
3656 /* Register the function. */
3657 lua_pushstring(gL.T, trash.str);
3658 hsf = lua_newuserdata(gL.T, sizeof(struct hlua_sample_fetch));
3659 hsf->f = sf;
3660 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
3661 lua_settable(gL.T, -3);
3662 }
3663
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003664 /* Register Lua functions. */
Thierry FOURNIER9a819e72015-02-16 20:22:55 +01003665 hlua_class_function(gL.T, "get_headers", hlua_session_getheaders);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003666 hlua_class_function(gL.T, "set_priv", hlua_setpriv);
3667 hlua_class_function(gL.T, "get_priv", hlua_getpriv);
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01003668 hlua_class_function(gL.T, "req_channel", hlua_txn_req_channel);
3669 hlua_class_function(gL.T, "res_channel", hlua_txn_res_channel);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003670 hlua_class_function(gL.T, "close", hlua_txn_close);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003671
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003672 lua_settable(gL.T, -3);
3673
3674 /* Register previous table in the registry with reference and named entry. */
3675 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
3676 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
3677 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003678
3679 /*
3680 *
3681 * Register class Socket
3682 *
3683 */
3684
3685 /* Create and fill the metatable. */
3686 lua_newtable(gL.T);
3687
3688 /* Create and fille the __index entry. */
3689 lua_pushstring(gL.T, "__index");
3690 lua_newtable(gL.T);
3691
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003692#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003693 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003694#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003695 hlua_class_function(gL.T, "connect", hlua_socket_connect);
3696 hlua_class_function(gL.T, "send", hlua_socket_send);
3697 hlua_class_function(gL.T, "receive", hlua_socket_receive);
3698 hlua_class_function(gL.T, "close", hlua_socket_close);
3699 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
3700 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
3701 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
3702 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
3703
3704 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
3705
3706 /* Register the garbage collector entry. */
3707 lua_pushstring(gL.T, "__gc");
3708 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
3709 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
3710
3711 /* Register previous table in the registry with reference and named entry. */
3712 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
3713 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
3714 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
3715 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
3716
3717 /* Proxy and server configuration initialisation. */
3718 memset(&socket_proxy, 0, sizeof(socket_proxy));
3719 init_new_proxy(&socket_proxy);
3720 socket_proxy.parent = NULL;
3721 socket_proxy.last_change = now.tv_sec;
3722 socket_proxy.id = "LUA-SOCKET";
3723 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
3724 socket_proxy.maxconn = 0;
3725 socket_proxy.accept = NULL;
3726 socket_proxy.options2 |= PR_O2_INDEPSTR;
3727 socket_proxy.srv = NULL;
3728 socket_proxy.conn_retries = 0;
3729 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
3730
3731 /* Init TCP server: unchanged parameters */
3732 memset(&socket_tcp, 0, sizeof(socket_tcp));
3733 socket_tcp.next = NULL;
3734 socket_tcp.proxy = &socket_proxy;
3735 socket_tcp.obj_type = OBJ_TYPE_SERVER;
3736 LIST_INIT(&socket_tcp.actconns);
3737 LIST_INIT(&socket_tcp.pendconns);
3738 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
3739 socket_tcp.last_change = 0;
3740 socket_tcp.id = "LUA-TCP-CONN";
3741 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
3742 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
3743 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
3744
3745 /* XXX: Copy default parameter from default server,
3746 * but the default server is not initialized.
3747 */
3748 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
3749 socket_tcp.minconn = socket_proxy.defsrv.minconn;
3750 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
3751 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
3752 socket_tcp.onerror = socket_proxy.defsrv.onerror;
3753 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
3754 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
3755 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
3756 socket_tcp.uweight = socket_proxy.defsrv.iweight;
3757 socket_tcp.iweight = socket_proxy.defsrv.iweight;
3758
3759 socket_tcp.check.status = HCHK_STATUS_INI;
3760 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
3761 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
3762 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
3763 socket_tcp.check.server = &socket_tcp;
3764
3765 socket_tcp.agent.status = HCHK_STATUS_INI;
3766 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
3767 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
3768 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
3769 socket_tcp.agent.server = &socket_tcp;
3770
3771 socket_tcp.xprt = &raw_sock;
3772
3773#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003774 /* Init TCP server: unchanged parameters */
3775 memset(&socket_ssl, 0, sizeof(socket_ssl));
3776 socket_ssl.next = NULL;
3777 socket_ssl.proxy = &socket_proxy;
3778 socket_ssl.obj_type = OBJ_TYPE_SERVER;
3779 LIST_INIT(&socket_ssl.actconns);
3780 LIST_INIT(&socket_ssl.pendconns);
3781 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
3782 socket_ssl.last_change = 0;
3783 socket_ssl.id = "LUA-SSL-CONN";
3784 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
3785 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
3786 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
3787
3788 /* XXX: Copy default parameter from default server,
3789 * but the default server is not initialized.
3790 */
3791 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
3792 socket_ssl.minconn = socket_proxy.defsrv.minconn;
3793 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
3794 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
3795 socket_ssl.onerror = socket_proxy.defsrv.onerror;
3796 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
3797 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
3798 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
3799 socket_ssl.uweight = socket_proxy.defsrv.iweight;
3800 socket_ssl.iweight = socket_proxy.defsrv.iweight;
3801
3802 socket_ssl.check.status = HCHK_STATUS_INI;
3803 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
3804 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
3805 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
3806 socket_ssl.check.server = &socket_ssl;
3807
3808 socket_ssl.agent.status = HCHK_STATUS_INI;
3809 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
3810 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
3811 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
3812 socket_ssl.agent.server = &socket_ssl;
3813
3814 socket_ssl.xprt = &raw_sock;
3815
3816 args[0] = "ssl";
3817 args[1] = "verify";
3818 args[2] = "none";
3819 args[3] = NULL;
3820
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003821 for (idx = 0; idx < 3; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003822 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
3823 /*
3824 *
3825 * If the keyword is not known, we can search in the registered
3826 * server keywords. This is usefull to configure special SSL
3827 * features like client certificates and ssl_verify.
3828 *
3829 */
3830 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
3831 if (tmp_error != 0) {
3832 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
3833 abort(); /* This must be never arrives because the command line
3834 not editable by the user. */
3835 }
3836 idx += kw->skip;
3837 }
3838 }
3839
3840 /* Initialize SSL server. */
3841 if (socket_ssl.xprt == &ssl_sock) {
3842 socket_ssl.use_ssl = 1;
3843 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
3844 }
3845#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01003846}