blob: e8907bef7717c5bc765e5ef11a4d1b6033f7fa33 [file] [log] [blame]
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01001#include <lauxlib.h>
2#include <lua.h>
3#include <lualib.h>
4
Thierry FOURNIER380d0932015-01-23 14:27:52 +01005#include <ebpttree.h>
6
7#include <common/cfgparse.h>
8
9#include <types/hlua.h>
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010010#include <types/proto_tcp.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011#include <types/proxy.h>
12
Thierry FOURNIER55da1652015-01-23 11:36:30 +010013#include <proto/arg.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010014#include <proto/hdr_idx.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010015#include <proto/payload.h>
16#include <proto/proto_http.h>
17#include <proto/sample.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010018#include <proto/task.h>
19
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010020/* Lua uses longjmp to perform yield or throwing errors. This
21 * macro is used only for identifying the function that can
22 * not return because a longjmp is executed.
23 * __LJMP marks a prototype of hlua file that can use longjmp.
24 * WILL_LJMP() marks an lua function that will use longjmp.
25 * MAY_LJMP() marks an lua function that may use longjmp.
26 */
27#define __LJMP
28#define WILL_LJMP(func) func
29#define MAY_LJMP(func) func
30
Thierry FOURNIER380d0932015-01-23 14:27:52 +010031/* The main Lua execution context. */
32struct hlua gL;
33
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010034/* This is the memory pool containing all the signal structs. These
35 * struct are used to store each requiered signal between two tasks.
36 */
37struct pool_head *pool2_hlua_com;
38
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010039/* List head of the function called at the initialisation time. */
40struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
41
Thierry FOURNIER380d0932015-01-23 14:27:52 +010042/* Store the fast lua context for coroutines. This tree uses the
43 * Lua stack pointer value as indexed entry, and store the associated
44 * hlua context.
45 */
46struct eb_root hlua_ctx = EB_ROOT_UNIQUE;
47
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010048/* The following variables contains the reference of the different
49 * Lua classes. These references are useful for identify metadata
50 * associated with an object.
51 */
52static int class_core_ref;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010053static int class_txn_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010054
Thierry FOURNIER55da1652015-01-23 11:36:30 +010055/* These functions converts types between HAProxy internal args or
56 * sample and LUA types. Another function permits to check if the
57 * LUA stack contains arguments according with an required ARG_T
58 * format.
59 */
60static int hlua_arg2lua(lua_State *L, const struct arg *arg);
61static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
62__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp, unsigned int mask);
63static int hlua_smp2lua(lua_State *L, const struct sample *smp);
64static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
65
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +010066/* Used to check an Lua function type in the stack. It creates and
67 * returns a reference of the function. This function throws an
68 * error if the rgument is not a "function".
69 */
70__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
71{
72 if (!lua_isfunction(L, argno)) {
73 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
74 WILL_LJMP(luaL_argerror(L, argno, msg));
75 }
76 lua_pushvalue(L, argno);
77 return luaL_ref(L, LUA_REGISTRYINDEX);
78}
79
80/* The three following functions are useful for adding entries
81 * in a table. These functions takes a string and respectively an
82 * integer, a string or a function and add it to the table in the
83 * top of the stack.
84 *
85 * These functions throws an error if no more stack size is
86 * available.
87 */
88__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
89 unsigned int value)
90{
91 if (!lua_checkstack(L, 2))
92 WILL_LJMP(luaL_error(L, "full stack"));
93 lua_pushstring(L, name);
94 lua_pushunsigned(L, value);
95 lua_settable(L, -3);
96}
97__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
98 const char *value)
99{
100 if (!lua_checkstack(L, 2))
101 WILL_LJMP(luaL_error(L, "full stack"));
102 lua_pushstring(L, name);
103 lua_pushstring(L, value);
104 lua_settable(L, -3);
105}
106__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
107 int (*function)(lua_State *L))
108{
109 if (!lua_checkstack(L, 2))
110 WILL_LJMP(luaL_error(L, "full stack"));
111 lua_pushstring(L, name);
112 lua_pushcclosure(L, function, 0);
113 lua_settable(L, -3);
114}
115
116/* This function check the number of arguments available in the
117 * stack. If the number of arguments available is not the same
118 * then <nb> an error is throwed.
119 */
120__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
121{
122 if (lua_gettop(L) == nb)
123 return;
124 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
125}
126
127/* Return true if the data in stack[<ud>] is an object of
128 * type <class_ref>.
129 */
130static int hlua_udataistype(lua_State *L, int ud, int class_ref)
131{
132 void *p = lua_touserdata(L, ud);
133 if (!p)
134 return 0;
135
136 if (!lua_getmetatable(L, ud))
137 return 0;
138
139 lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
140 if (!lua_rawequal(L, -1, -2)) {
141 lua_pop(L, 2);
142 return 0;
143 }
144
145 lua_pop(L, 2);
146 return 1;
147}
148
149/* Return an object of the expected type, or throws an error. */
150__LJMP static void *hlua_checkudata(lua_State *L, int ud, int class_ref)
151{
152 if (!hlua_udataistype(L, ud, class_ref))
153 WILL_LJMP(luaL_argerror(L, 1, NULL));
154 return lua_touserdata(L, ud);
155}
156
157/* This fucntion push an error string prefixed by the file name
158 * and the line number where the error is encountered.
159 */
160static int hlua_pusherror(lua_State *L, const char *fmt, ...)
161{
162 va_list argp;
163 va_start(argp, fmt);
164 luaL_where(L, 1);
165 lua_pushvfstring(L, fmt, argp);
166 va_end(argp);
167 lua_concat(L, 2);
168 return 1;
169}
170
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100171/* This function register a new signal. "lua" is the current lua
172 * execution context. It contains a pointer to the associated task.
173 * "link" is a list head attached to an other task that must be wake
174 * the lua task if an event occurs. This is useful with external
175 * events like TCP I/O or sleep functions. This funcion allocate
176 * memory for the signal.
177 */
178static int hlua_com_new(struct hlua *lua, struct list *link)
179{
180 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
181 if (!com)
182 return 0;
183 LIST_ADDQ(&lua->com, &com->purge_me);
184 LIST_ADDQ(link, &com->wake_me);
185 com->task = lua->task;
186 return 1;
187}
188
189/* This function purge all the pending signals when the LUA execution
190 * is finished. This prevent than a coprocess try to wake a deleted
191 * task. This function remove the memory associated to the signal.
192 */
193static void hlua_com_purge(struct hlua *lua)
194{
195 struct hlua_com *com, *back;
196
197 /* Delete all pending communication signals. */
198 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
199 LIST_DEL(&com->purge_me);
200 LIST_DEL(&com->wake_me);
201 pool_free2(pool2_hlua_com, com);
202 }
203}
204
205/* This function sends signals. It wakes all the tasks attached
206 * to a list head, and remove the signal, and free the used
207 * memory.
208 */
209static void hlua_com_wake(struct list *wake)
210{
211 struct hlua_com *com, *back;
212
213 /* Wake task and delete all pending communication signals. */
214 list_for_each_entry_safe(com, back, wake, wake_me) {
215 LIST_DEL(&com->purge_me);
216 LIST_DEL(&com->wake_me);
217 task_wakeup(com->task, TASK_WOKEN_MSG);
218 pool_free2(pool2_hlua_com, com);
219 }
220}
221
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100222/* This functions is used with sample fetch and converters. It
223 * converts the HAProxy configuration argument in a lua stack
224 * values.
225 *
226 * It takes an array of "arg", and each entry of the array is
227 * converted and pushed in the LUA stack.
228 */
229static int hlua_arg2lua(lua_State *L, const struct arg *arg)
230{
231 switch (arg->type) {
232 case ARGT_SINT:
233 lua_pushinteger(L, arg->data.sint);
234 break;
235
236 case ARGT_UINT:
237 case ARGT_TIME:
238 case ARGT_SIZE:
239 lua_pushunsigned(L, arg->data.sint);
240 break;
241
242 case ARGT_STR:
243 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
244 break;
245
246 case ARGT_IPV4:
247 case ARGT_IPV6:
248 case ARGT_MSK4:
249 case ARGT_MSK6:
250 case ARGT_FE:
251 case ARGT_BE:
252 case ARGT_TAB:
253 case ARGT_SRV:
254 case ARGT_USR:
255 case ARGT_MAP:
256 default:
257 lua_pushnil(L);
258 break;
259 }
260 return 1;
261}
262
263/* This function take one entrie in an LUA stack at the index "ud",
264 * and try to convert it in an HAProxy argument entry. This is useful
265 * with sample fetch wrappers. The input arguments are gived to the
266 * lua wrapper and converted as arg list by thi function.
267 */
268static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
269{
270 switch (lua_type(L, ud)) {
271
272 case LUA_TNUMBER:
273 case LUA_TBOOLEAN:
274 arg->type = ARGT_SINT;
275 arg->data.sint = lua_tointeger(L, ud);
276 break;
277
278 case LUA_TSTRING:
279 arg->type = ARGT_STR;
280 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
281 break;
282
283 case LUA_TUSERDATA:
284 case LUA_TNIL:
285 case LUA_TTABLE:
286 case LUA_TFUNCTION:
287 case LUA_TTHREAD:
288 case LUA_TLIGHTUSERDATA:
289 arg->type = ARGT_SINT;
290 arg->data.uint = 0;
291 break;
292 }
293 return 1;
294}
295
296/* the following functions are used to convert a struct sample
297 * in Lua type. This useful to convert the return of the
298 * fetchs or converters.
299 */
300static int hlua_smp2lua(lua_State *L, const struct sample *smp)
301{
302 switch (smp->type) {
303 case SMP_T_SINT:
304 lua_pushinteger(L, smp->data.sint);
305 break;
306
307 case SMP_T_BOOL:
308 case SMP_T_UINT:
309 lua_pushunsigned(L, smp->data.uint);
310 break;
311
312 case SMP_T_BIN:
313 case SMP_T_STR:
314 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
315 break;
316
317 case SMP_T_METH:
318 switch (smp->data.meth.meth) {
319 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
320 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
321 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
322 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
323 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
324 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
325 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
326 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
327 case HTTP_METH_OTHER:
328 lua_pushlstring(L, smp->data.meth.str.str, smp->data.meth.str.len);
329 break;
330 default:
331 lua_pushnil(L);
332 break;
333 }
334 break;
335
336 case SMP_T_IPV4:
337 case SMP_T_IPV6:
338 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
339 default:
340 lua_pushnil(L);
341 break;
342 }
343 return 1;
344}
345
346/* the following functions are used to convert an Lua type in a
347 * struct sample. This is useful to provide data from a converter
348 * to the LUA code.
349 */
350static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
351{
352 switch (lua_type(L, ud)) {
353
354 case LUA_TNUMBER:
355 smp->type = SMP_T_SINT;
356 smp->data.sint = lua_tointeger(L, ud);
357 break;
358
359
360 case LUA_TBOOLEAN:
361 smp->type = SMP_T_BOOL;
362 smp->data.uint = lua_toboolean(L, ud);
363 break;
364
365 case LUA_TSTRING:
366 smp->type = SMP_T_STR;
367 smp->flags |= SMP_F_CONST;
368 smp->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.str.len);
369 break;
370
371 case LUA_TUSERDATA:
372 case LUA_TNIL:
373 case LUA_TTABLE:
374 case LUA_TFUNCTION:
375 case LUA_TTHREAD:
376 case LUA_TLIGHTUSERDATA:
377 smp->type = SMP_T_BOOL;
378 smp->data.uint = 0;
379 break;
380 }
381 return 1;
382}
383
384/* This function check the "argp" builded by another conversion function
385 * is in accord with the expected argp defined by the "mask". The fucntion
386 * returns true or false. It can be adjust the types if there compatibles.
387 */
388__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp, unsigned int mask)
389{
390 int min_arg;
391 int idx;
392
393 idx = 0;
394 min_arg = ARGM(mask);
395 mask >>= ARGM_BITS;
396
397 while (1) {
398
399 /* Check oversize. */
400 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
401 WILL_LJMP(luaL_argerror(L, first + idx, "Malformad argument mask"));
402 }
403
404 /* Check for mandatory arguments. */
405 if (argp[idx].type == ARGT_STOP) {
406 if (idx + 1 < min_arg)
407 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
408 return 0;
409 }
410
411 /* Check for exceed the number of requiered argument. */
412 if ((mask & ARGT_MASK) == ARGT_STOP &&
413 argp[idx].type != ARGT_STOP) {
414 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
415 }
416
417 if ((mask & ARGT_MASK) == ARGT_STOP &&
418 argp[idx].type == ARGT_STOP) {
419 return 0;
420 }
421
422 /* Compatibility mask. */
423 switch (argp[idx].type) {
424 case ARGT_SINT:
425 switch (mask & ARGT_MASK) {
426 case ARGT_UINT: argp[idx].type = mask & ARGT_MASK; break;
427 case ARGT_TIME: argp[idx].type = mask & ARGT_MASK; break;
428 case ARGT_SIZE: argp[idx].type = mask & ARGT_MASK; break;
429 }
430 break;
431 }
432
433 /* Check for type of argument. */
434 if ((mask & ARGT_MASK) != argp[idx].type) {
435 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
436 arg_type_names[(mask & ARGT_MASK)],
437 arg_type_names[argp[idx].type & ARGT_MASK]);
438 WILL_LJMP(luaL_argerror(L, first + idx, msg));
439 }
440
441 /* Next argument. */
442 mask >>= ARGT_BITS;
443 idx++;
444 }
445}
446
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100447/*
448 * The following functions are used to make correspondance between the the
449 * executed lua pointer and the "struct hlua *" that contain the context.
450 * They run with the tree head "hlua_ctx", they just perform lookup in the
451 * tree.
452 *
453 * - hlua_gethlua : return the hlua context associated with an lua_State.
454 * - hlua_delhlua : remove the association between hlua context and lua_state.
455 * - hlua_sethlua : create the association between hlua context and lua_state.
456 */
457static inline struct hlua *hlua_gethlua(lua_State *L)
458{
459 struct ebpt_node *node;
460
461 node = ebpt_lookup(&hlua_ctx, L);
462 if (!node)
463 return NULL;
464 return ebpt_entry(node, struct hlua, node);
465}
466static inline void hlua_delhlua(struct hlua *hlua)
467{
468 if (hlua->node.key)
469 ebpt_delete(&hlua->node);
470}
471static inline void hlua_sethlua(struct hlua *hlua)
472{
473 hlua->node.key = hlua->T;
474 ebpt_insert(&hlua_ctx, &hlua->node);
475}
476
477/* This function initialises the Lua environment stored in the session.
478 * It must be called at the start of the session. This function creates
479 * an LUA coroutine. It can not be use to crete the main LUA context.
480 */
481int hlua_ctx_init(struct hlua *lua, struct task *task)
482{
483 lua->Mref = LUA_REFNIL;
484 lua->state = HLUA_STOP;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100485 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100486 lua->T = lua_newthread(gL.T);
487 if (!lua->T) {
488 lua->Tref = LUA_REFNIL;
489 return 0;
490 }
491 hlua_sethlua(lua);
492 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
493 lua->task = task;
494 return 1;
495}
496
497/* Used to destroy the Lua coroutine when the attached session or task
498 * is destroyed. The destroy also the memory context. The struct "lua"
499 * is not freed.
500 */
501void hlua_ctx_destroy(struct hlua *lua)
502{
503 /* Remove context. */
504 hlua_delhlua(lua);
505
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100506 /* Purge all the pending signals. */
507 hlua_com_purge(lua);
508
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100509 /* The thread is garbage collected by Lua. */
510 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
511 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
512}
513
514/* This function is used to restore the Lua context when a coroutine
515 * fails. This function copy the common memory between old coroutine
516 * and the new coroutine. The old coroutine is destroyed, and its
517 * replaced by the new coroutine.
518 * If the flag "keep_msg" is set, the last entry of the old is assumed
519 * as string error message and it is copied in the new stack.
520 */
521static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
522{
523 lua_State *T;
524 int new_ref;
525
526 /* Renew the main LUA stack doesn't have sense. */
527 if (lua == &gL)
528 return 0;
529
530 /* Remove context. */
531 hlua_delhlua(lua);
532
533 /* New Lua coroutine. */
534 T = lua_newthread(gL.T);
535 if (!T)
536 return 0;
537
538 /* Copy last error message. */
539 if (keep_msg)
540 lua_xmove(lua->T, T, 1);
541
542 /* Copy data between the coroutines. */
543 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
544 lua_xmove(lua->T, T, 1);
545 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
546
547 /* Destroy old data. */
548 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
549
550 /* The thread is garbage collected by Lua. */
551 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
552
553 /* Fill the struct with the new coroutine values. */
554 lua->Mref = new_ref;
555 lua->T = T;
556 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
557
558 /* Set context. */
559 hlua_sethlua(lua);
560
561 return 1;
562}
563
564/* This function start or resumes the Lua stack execution. If the flag
565 * "yield_allowed" if no set and the LUA stack execution returns a yield
566 * The function return an error.
567 *
568 * The function can returns 4 values:
569 * - HLUA_E_OK : The execution is terminated without any errors.
570 * - HLUA_E_AGAIN : The execution must continue at the next associated
571 * task wakeup.
572 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
573 * the top of the stack.
574 * - HLUA_E_ERR : An error has occured without error message.
575 *
576 * If an error occured, the stack is renewed and it is ready to run new
577 * LUA code.
578 */
579static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
580{
581 int ret;
582 const char *msg;
583
584 lua->state = HLUA_RUN;
585
586 /* Call the function. */
587 ret = lua_resume(lua->T, gL.T, lua->nargs);
588 switch (ret) {
589
590 case LUA_OK:
591 ret = HLUA_E_OK;
592 break;
593
594 case LUA_YIELD:
595 if (!yield_allowed) {
596 lua_settop(lua->T, 0); /* Empty the stack. */
597 if (!lua_checkstack(lua->T, 1)) {
598 ret = HLUA_E_ERR;
599 break;
600 }
601 lua_pushfstring(lua->T, "yield not allowed");
602 ret = HLUA_E_ERRMSG;
603 break;
604 }
605 ret = HLUA_E_AGAIN;
606 break;
607
608 case LUA_ERRRUN:
609 if (!lua_checkstack(lua->T, 1)) {
610 ret = HLUA_E_ERR;
611 break;
612 }
613 msg = lua_tostring(lua->T, -1);
614 lua_settop(lua->T, 0); /* Empty the stack. */
615 lua_pop(lua->T, 1);
616 if (msg)
617 lua_pushfstring(lua->T, "runtime error: %s", msg);
618 else
619 lua_pushfstring(lua->T, "unknown runtime error");
620 ret = HLUA_E_ERRMSG;
621 break;
622
623 case LUA_ERRMEM:
624 lua_settop(lua->T, 0); /* Empty the stack. */
625 if (!lua_checkstack(lua->T, 1)) {
626 ret = HLUA_E_ERR;
627 break;
628 }
629 lua_pushfstring(lua->T, "out of memory error");
630 ret = HLUA_E_ERRMSG;
631 break;
632
633 case LUA_ERRERR:
634 if (!lua_checkstack(lua->T, 1)) {
635 ret = HLUA_E_ERR;
636 break;
637 }
638 msg = lua_tostring(lua->T, -1);
639 lua_settop(lua->T, 0); /* Empty the stack. */
640 lua_pop(lua->T, 1);
641 if (msg)
642 lua_pushfstring(lua->T, "message handler error: %s", msg);
643 else
644 lua_pushfstring(lua->T, "message handler error");
645 ret = HLUA_E_ERRMSG;
646 break;
647
648 default:
649 lua_settop(lua->T, 0); /* Empty the stack. */
650 if (!lua_checkstack(lua->T, 1)) {
651 ret = HLUA_E_ERR;
652 break;
653 }
654 lua_pushfstring(lua->T, "unknonwn error");
655 ret = HLUA_E_ERRMSG;
656 break;
657 }
658
659 switch (ret) {
660 case HLUA_E_AGAIN:
661 break;
662
663 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100664 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100665 hlua_ctx_renew(lua, 1);
666 lua->state = HLUA_STOP;
667 break;
668
669 case HLUA_E_ERR:
670 lua->state = HLUA_STOP;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100671 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100672 hlua_ctx_renew(lua, 0);
673 break;
674
675 case HLUA_E_OK:
676 lua->state = HLUA_STOP;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100677 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100678 break;
679 }
680
681 return ret;
682}
683
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100684/* A class is a lot of memory that contain data. This data can be a table,
685 * an integer or user data. This data is associated with a metatable. This
686 * metatable have an original version registred in the global context with
687 * the name of the object (_G[<name>] = <metable> ).
688 *
689 * A metable is a table that modify the standard behavior of a standard
690 * access to the associated data. The entries of this new metatable are
691 * defined as is:
692 *
693 * http://lua-users.org/wiki/MetatableEvents
694 *
695 * __index
696 *
697 * we access an absent field in a table, the result is nil. This is
698 * true, but it is not the whole truth. Actually, such access triggers
699 * the interpreter to look for an __index metamethod: If there is no
700 * such method, as usually happens, then the access results in nil;
701 * otherwise, the metamethod will provide the result.
702 *
703 * Control 'prototype' inheritance. When accessing "myTable[key]" and
704 * the key does not appear in the table, but the metatable has an __index
705 * property:
706 *
707 * - if the value is a function, the function is called, passing in the
708 * table and the key; the return value of that function is returned as
709 * the result.
710 *
711 * - if the value is another table, the value of the key in that table is
712 * asked for and returned (and if it doesn't exist in that table, but that
713 * table's metatable has an __index property, then it continues on up)
714 *
715 * - Use "rawget(myTable,key)" to skip this metamethod.
716 *
717 * http://www.lua.org/pil/13.4.1.html
718 *
719 * __newindex
720 *
721 * Like __index, but control property assignment.
722 *
723 * __mode - Control weak references. A string value with one or both
724 * of the characters 'k' and 'v' which specifies that the the
725 * keys and/or values in the table are weak references.
726 *
727 * __call - Treat a table like a function. When a table is followed by
728 * parenthesis such as "myTable( 'foo' )" and the metatable has
729 * a __call key pointing to a function, that function is invoked
730 * (passing any specified arguments) and the return value is
731 * returned.
732 *
733 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
734 * called, if the metatable for myTable has a __metatable
735 * key, the value of that key is returned instead of the
736 * actual metatable.
737 *
738 * __tostring - Control string representation. When the builtin
739 * "tostring( myTable )" function is called, if the metatable
740 * for myTable has a __tostring property set to a function,
741 * that function is invoked (passing myTable to it) and the
742 * return value is used as the string representation.
743 *
744 * __len - Control table length. When the table length is requested using
745 * the length operator ( '#' ), if the metatable for myTable has
746 * a __len key pointing to a function, that function is invoked
747 * (passing myTable to it) and the return value used as the value
748 * of "#myTable".
749 *
750 * __gc - Userdata finalizer code. When userdata is set to be garbage
751 * collected, if the metatable has a __gc field pointing to a
752 * function, that function is first invoked, passing the userdata
753 * to it. The __gc metamethod is not called for tables.
754 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
755 *
756 * Special metamethods for redefining standard operators:
757 * http://www.lua.org/pil/13.1.html
758 *
759 * __add "+"
760 * __sub "-"
761 * __mul "*"
762 * __div "/"
763 * __unm "!"
764 * __pow "^"
765 * __concat ".."
766 *
767 * Special methods for redfining standar relations
768 * http://www.lua.org/pil/13.2.html
769 *
770 * __eq "=="
771 * __lt "<"
772 * __le "<="
773 */
774
775/*
776 *
777 *
778 * Class TXN
779 *
780 *
781 */
782
783/* Returns a struct hlua_session if the stack entry "ud" is
784 * a class session, otherwise it throws an error.
785 */
786__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
787{
788 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
789}
790
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +0100791__LJMP static int hlua_setpriv(lua_State *L)
792{
793 MAY_LJMP(check_args(L, 2, "set_priv"));
794
795 /* It is useles to retrieve the session, but this function
796 * runs only in a session context.
797 */
798 MAY_LJMP(hlua_checktxn(L, 1));
799 struct hlua *hlua = hlua_gethlua(L);
800
801 /* Remove previous value. */
802 if (hlua->Mref != -1)
803 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
804
805 /* Get and store new value. */
806 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
807 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
808
809 return 0;
810}
811
812__LJMP static int hlua_getpriv(lua_State *L)
813{
814 MAY_LJMP(check_args(L, 1, "get_priv"));
815
816 /* It is useles to retrieve the session, but this function
817 * runs only in a session context.
818 */
819 MAY_LJMP(hlua_checktxn(L, 1));
820 struct hlua *hlua = hlua_gethlua(L);
821
822 /* Push configuration index in the stack. */
823 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
824
825 return 1;
826}
827
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100828/* Create stack entry containing a class TXN. This function
829 * return 0 if the stack does not contains free slots,
830 * otherwise it returns 1.
831 */
832static int hlua_txn_new(lua_State *L, struct session *s, struct proxy *p, void *l7)
833{
834 struct hlua_txn *hs;
835
836 /* Check stack size. */
837 if (!lua_checkstack(L, 2))
838 return 0;
839
840 /* NOTE: The allocation never fails. The failure
841 * throw an error, and the function never returns.
842 * if the throw is not avalaible, the process is aborted.
843 */
844 hs = lua_newuserdata(L, sizeof(struct hlua_txn));
845 hs->s = s;
846 hs->p = p;
847 hs->l7 = l7;
848
849 /* Pop a class sesison metatable and affect it to the userdata. */
850 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
851 lua_setmetatable(L, -2);
852
853 return 1;
854}
855
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +0100856/* This function is an LUA binding. It is called with each sample-fetch.
857 * It uses closure argument to store the associated sample-fetch. It
858 * returns only one argument or throws an error. An error is throwed
859 * only if an error is encoutered during the argument parsing. If
860 * the "sample-fetch" function fails, nil is returned.
861 */
862__LJMP static int hlua_run_sample_fetch(lua_State *L)
863{
864 struct hlua_txn *s;
865 struct hlua_sample_fetch *f;
866 struct arg args[ARGM_NBARGS];
867 int i;
868 struct sample smp;
869
870 /* Get closure arguments. */
871 f = (struct hlua_sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
872
873 /* Get traditionnal arguments. */
874 s = MAY_LJMP(hlua_checktxn(L, 1));
875
876 /* Get extra arguments. */
877 for (i = 0; i <= lua_gettop(L); i++) {
878 if (i >= ARGM_NBARGS)
879 break;
880 hlua_lua2arg(L, i + 2, &args[i]);
881 }
882 args[i].type = ARGT_STOP;
883
884 /* Check arguments. */
885 MAY_LJMP(hlua_lua2arg_check(L, 1, args, f->f->arg_mask));
886
887 /* Run the special args cehcker. */
888 if (!f->f->val_args(args, NULL)) {
889 lua_pushfstring(L, "error in arguments");
890 WILL_LJMP(lua_error(L));
891 }
892
893 /* Initialise the sample. */
894 memset(&smp, 0, sizeof(smp));
895
896 /* Run the sample fetch process. */
897 if (!f->f->process(s->p, s->s, s->l7, 0, args, &smp, f->f->kw, f->f->private)) {
898 lua_pushnil(L);
899 return 1;
900 }
901
902 /* Convert the returned sample in lua value. */
903 hlua_smp2lua(L, &smp);
904 return 1;
905}
906
Thierry FOURNIER9a819e72015-02-16 20:22:55 +0100907/* This function is an LUA binding. It creates ans returns
908 * an array of HTTP headers. This function does not fails.
909 */
910static int hlua_session_getheaders(lua_State *L)
911{
912 struct hlua_txn *s = MAY_LJMP(hlua_checktxn(L, 1));
913 struct session *sess = s->s;
914 const char *cur_ptr, *cur_next, *p;
915 int old_idx, cur_idx;
916 struct hdr_idx_elem *cur_hdr;
917 const char *hn, *hv;
918 int hnl, hvl;
919
920 /* Create the table. */
921 lua_newtable(L);
922
923 /* Build array of headers. */
924 old_idx = 0;
925 cur_next = sess->req->buf->p + hdr_idx_first_pos(&sess->txn.hdr_idx);
926
927 while (1) {
928 cur_idx = sess->txn.hdr_idx.v[old_idx].next;
929 if (!cur_idx)
930 break;
931 old_idx = cur_idx;
932
933 cur_hdr = &sess->txn.hdr_idx.v[cur_idx];
934 cur_ptr = cur_next;
935 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
936
937 /* Now we have one full header at cur_ptr of len cur_hdr->len,
938 * and the next header starts at cur_next. We'll check
939 * this header in the list as well as against the default
940 * rule.
941 */
942
943 /* look for ': *'. */
944 hn = cur_ptr;
945 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
946 if (p >= cur_ptr+cur_hdr->len)
947 continue;
948 hnl = p - hn;
949 p++;
950 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
951 p++;
952 if (p >= cur_ptr+cur_hdr->len)
953 continue;
954 hv = p;
955 hvl = cur_ptr+cur_hdr->len-p;
956
957 /* Push values in the table. */
958 lua_pushlstring(L, hn, hnl);
959 lua_pushlstring(L, hv, hvl);
960 lua_settable(L, -3);
961 }
962
963 return 1;
964}
965
Thierry FOURNIER24f33532015-01-23 12:13:00 +0100966/* This function is used as a calback of a task. It is called by the
967 * HAProxy task subsystem when the task is awaked. The LUA runtime can
968 * return an E_AGAIN signal, the emmiter of this signal must set a
969 * signal to wake the task.
970 */
971static struct task *hlua_process_task(struct task *task)
972{
973 struct hlua *hlua = task->context;
974 enum hlua_exec status;
975
976 /* We need to remove the task from the wait queue before executing
977 * the Lua code because we don't know if it needs to wait for
978 * another timer or not in the case of E_AGAIN.
979 */
980 task_delete(task);
981
982 /* Execute the Lua code. */
983 status = hlua_ctx_resume(hlua, 1);
984
985 switch (status) {
986 /* finished or yield */
987 case HLUA_E_OK:
988 hlua_ctx_destroy(hlua);
989 task_delete(task);
990 task_free(task);
991 break;
992
993 case HLUA_E_AGAIN: /* co process wake me later. */
994 break;
995
996 /* finished with error. */
997 case HLUA_E_ERRMSG:
998 send_log(NULL, LOG_ERR, "Lua task: %s.", lua_tostring(hlua->T, -1));
999 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
1000 Alert("Lua task: %s.\n", lua_tostring(hlua->T, -1));
1001 hlua_ctx_destroy(hlua);
1002 task_delete(task);
1003 task_free(task);
1004 break;
1005
1006 case HLUA_E_ERR:
1007 default:
1008 send_log(NULL, LOG_ERR, "Lua task: unknown error.");
1009 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
1010 Alert("Lua task: unknown error.\n");
1011 hlua_ctx_destroy(hlua);
1012 task_delete(task);
1013 task_free(task);
1014 break;
1015 }
1016 return NULL;
1017}
1018
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01001019/* This function is an LUA binding that register LUA function to be
1020 * executed after the HAProxy configuration parsing and before the
1021 * HAProxy scheduler starts. This function expect only one LUA
1022 * argument that is a function. This function returns nothing, but
1023 * throws if an error is encountered.
1024 */
1025__LJMP static int hlua_register_init(lua_State *L)
1026{
1027 struct hlua_init_function *init;
1028 int ref;
1029
1030 MAY_LJMP(check_args(L, 1, "register_init"));
1031
1032 ref = MAY_LJMP(hlua_checkfunction(L, 1));
1033
1034 init = malloc(sizeof(*init));
1035 if (!init)
1036 WILL_LJMP(luaL_error(L, "lua out of memory error."));
1037
1038 init->function_ref = ref;
1039 LIST_ADDQ(&hlua_init_functions, &init->l);
1040 return 0;
1041}
1042
Thierry FOURNIER24f33532015-01-23 12:13:00 +01001043/* This functio is an LUA binding. It permits to register a task
1044 * executed in parallel of the main HAroxy activity. The task is
1045 * created and it is set in the HAProxy scheduler. It can be called
1046 * from the "init" section, "post init" or during the runtime.
1047 *
1048 * Lua prototype:
1049 *
1050 * <none> core.register_task(<function>)
1051 */
1052static int hlua_register_task(lua_State *L)
1053{
1054 struct hlua *hlua;
1055 struct task *task;
1056 int ref;
1057
1058 MAY_LJMP(check_args(L, 1, "register_task"));
1059
1060 ref = MAY_LJMP(hlua_checkfunction(L, 1));
1061
1062 hlua = malloc(sizeof(*hlua));
1063 if (!hlua)
1064 WILL_LJMP(luaL_error(L, "lua out of memory error."));
1065
1066 task = task_new();
1067 task->context = hlua;
1068 task->process = hlua_process_task;
1069
1070 if (!hlua_ctx_init(hlua, task))
1071 WILL_LJMP(luaL_error(L, "lua out of memory error."));
1072
1073 /* Restore the function in the stack. */
1074 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
1075 hlua->nargs = 0;
1076
1077 /* Schedule task. */
1078 task_schedule(task, now_ms);
1079
1080 return 0;
1081}
1082
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01001083/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
1084 * doesn't allow "yield" functions because the HAProxy engine cannot
1085 * resume converters.
1086 */
1087static int hlua_sample_conv_wrapper(struct session *session, const struct arg *arg_p,
1088 struct sample *smp, void *private)
1089{
1090 struct hlua_function *fcn = (struct hlua_function *)private;
1091
1092 /* If it is the first run, initialize the data for the call. */
1093 if (session->hlua.state == HLUA_STOP) {
1094 /* Check stack available size. */
1095 if (!lua_checkstack(session->hlua.T, 1)) {
1096 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
1097 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
1098 Alert("Lua converter '%s': full stack.\n", fcn->name);
1099 return 0;
1100 }
1101
1102 /* Restore the function in the stack. */
1103 lua_rawgeti(session->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
1104
1105 /* convert input sample and pust-it in the stack. */
1106 if (!lua_checkstack(session->hlua.T, 1)) {
1107 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
1108 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
1109 Alert("Lua converter '%s': full stack.\n", fcn->name);
1110 return 0;
1111 }
1112 hlua_smp2lua(session->hlua.T, smp);
1113 session->hlua.nargs = 2;
1114
1115 /* push keywords in the stack. */
1116 if (arg_p) {
1117 for (; arg_p->type != ARGT_STOP; arg_p++) {
1118 if (!lua_checkstack(session->hlua.T, 1)) {
1119 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
1120 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
1121 Alert("Lua converter '%s': full stack.\n", fcn->name);
1122 return 0;
1123 }
1124 hlua_arg2lua(session->hlua.T, arg_p);
1125 session->hlua.nargs++;
1126 }
1127 }
1128
1129 /* Set the currently running flag. */
1130 session->hlua.state = HLUA_RUN;
1131 }
1132
1133 /* Execute the function. */
1134 switch (hlua_ctx_resume(&session->hlua, 0)) {
1135 /* finished. */
1136 case HLUA_E_OK:
1137 /* Convert the returned value in sample. */
1138 hlua_lua2smp(session->hlua.T, -1, smp);
1139 lua_pop(session->hlua.T, 1);
1140 return 1;
1141
1142 /* yield. */
1143 case HLUA_E_AGAIN:
1144 send_log(session->be, LOG_ERR, "Lua converter '%s': cannot use yielded functions.", fcn->name);
1145 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
1146 Alert("Lua converter '%s': cannot use yielded functions.\n", fcn->name);
1147 return 0;
1148
1149 /* finished with error. */
1150 case HLUA_E_ERRMSG:
1151 /* Display log. */
1152 send_log(session->be, LOG_ERR, "Lua converter '%s': %s.", fcn->name, lua_tostring(session->hlua.T, -1));
1153 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
1154 Alert("Lua converter '%s': %s.\n", fcn->name, lua_tostring(session->hlua.T, -1));
1155 lua_pop(session->hlua.T, 1);
1156 return 0;
1157
1158 case HLUA_E_ERR:
1159 /* Display log. */
1160 send_log(session->be, LOG_ERR, "Lua converter '%s' returns an unknown error.", fcn->name);
1161 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
1162 Alert("Lua converter '%s' returns an unknown error.\n", fcn->name);
1163
1164 default:
1165 return 0;
1166 }
1167}
1168
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01001169/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
1170 * doesn't allow "yield" functions because the HAProxy engine cannot
1171 * resume sample-fetches.
1172 */
1173static int hlua_sample_fetch_wrapper(struct proxy *px, struct session *s, void *l7,
1174 unsigned int opt, const struct arg *arg_p,
1175 struct sample *smp, const char *kw, void *private)
1176{
1177 struct hlua_function *fcn = (struct hlua_function *)private;
1178
1179 /* If it is the first run, initialize the data for the call. */
1180 if (s->hlua.state == HLUA_STOP) {
1181 /* Check stack available size. */
1182 if (!lua_checkstack(s->hlua.T, 2)) {
1183 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
1184 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
1185 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
1186 return 0;
1187 }
1188
1189 /* Restore the function in the stack. */
1190 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
1191
1192 /* push arguments in the stack. */
1193 if (!hlua_txn_new(s->hlua.T, s, px, l7)) {
1194 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
1195 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
1196 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
1197 return 0;
1198 }
1199 s->hlua.nargs = 1;
1200
1201 /* push keywords in the stack. */
1202 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
1203 /* Check stack available size. */
1204 if (!lua_checkstack(s->hlua.T, 1)) {
1205 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
1206 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
1207 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
1208 return 0;
1209 }
1210 if (!lua_checkstack(s->hlua.T, 1)) {
1211 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
1212 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
1213 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
1214 return 0;
1215 }
1216 hlua_arg2lua(s->hlua.T, arg_p);
1217 s->hlua.nargs++;
1218 }
1219
1220 /* Set the currently running flag. */
1221 s->hlua.state = HLUA_RUN;
1222 }
1223
1224 /* Execute the function. */
1225 switch (hlua_ctx_resume(&s->hlua, 0)) {
1226 /* finished. */
1227 case HLUA_E_OK:
1228 /* Convert the returned value in sample. */
1229 hlua_lua2smp(s->hlua.T, -1, smp);
1230 lua_pop(s->hlua.T, 1);
1231
1232 /* Set the end of execution flag. */
1233 smp->flags &= ~SMP_F_MAY_CHANGE;
1234 return 1;
1235
1236 /* yield. */
1237 case HLUA_E_AGAIN:
1238 send_log(px, LOG_ERR, "Lua sample-fetch '%s': cannot use yielded functions.", fcn->name);
1239 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
1240 Alert("Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
1241 return 0;
1242
1243 /* finished with error. */
1244 case HLUA_E_ERRMSG:
1245 /* Display log. */
1246 send_log(px, LOG_ERR, "Lua sample-fetch '%s': %s.", fcn->name, lua_tostring(s->hlua.T, -1));
1247 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
1248 Alert("Lua sample-fetch '%s': %s.\n", fcn->name, lua_tostring(s->hlua.T, -1));
1249 lua_pop(s->hlua.T, 1);
1250 return 0;
1251
1252 case HLUA_E_ERR:
1253 /* Display log. */
1254 send_log(px, LOG_ERR, "Lua sample-fetch '%s' returns an unknown error.", fcn->name);
1255 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
1256 Alert("Lua sample-fetch '%s': returns an unknown error.\n", fcn->name);
1257
1258 default:
1259 return 0;
1260 }
1261}
1262
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01001263/* This function is an LUA binding used for registering
1264 * "sample-conv" functions. It expects a converter name used
1265 * in the haproxy configuration file, and an LUA function.
1266 */
1267__LJMP static int hlua_register_converters(lua_State *L)
1268{
1269 struct sample_conv_kw_list *sck;
1270 const char *name;
1271 int ref;
1272 int len;
1273 struct hlua_function *fcn;
1274
1275 MAY_LJMP(check_args(L, 2, "register_converters"));
1276
1277 /* First argument : converter name. */
1278 name = MAY_LJMP(luaL_checkstring(L, 1));
1279
1280 /* Second argument : lua function. */
1281 ref = MAY_LJMP(hlua_checkfunction(L, 2));
1282
1283 /* Allocate and fill the sample fetch keyword struct. */
1284 sck = malloc(sizeof(struct sample_conv_kw_list) +
1285 sizeof(struct sample_conv) * 2);
1286 if (!sck)
1287 WILL_LJMP(luaL_error(L, "lua out of memory error."));
1288 fcn = malloc(sizeof(*fcn));
1289 if (!fcn)
1290 WILL_LJMP(luaL_error(L, "lua out of memory error."));
1291
1292 /* Fill fcn. */
1293 fcn->name = strdup(name);
1294 if (!fcn->name)
1295 WILL_LJMP(luaL_error(L, "lua out of memory error."));
1296 fcn->function_ref = ref;
1297
1298 /* List head */
1299 sck->list.n = sck->list.p = NULL;
1300
1301 /* converter keyword. */
1302 len = strlen("lua.") + strlen(name) + 1;
1303 sck->kw[0].kw = malloc(len);
1304 if (!sck->kw[0].kw)
1305 WILL_LJMP(luaL_error(L, "lua out of memory error."));
1306
1307 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
1308 sck->kw[0].process = hlua_sample_conv_wrapper;
1309 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
1310 sck->kw[0].val_args = NULL;
1311 sck->kw[0].in_type = SMP_T_STR;
1312 sck->kw[0].out_type = SMP_T_STR;
1313 sck->kw[0].private = fcn;
1314
1315 /* End of array. */
1316 memset(&sck->kw[1], 0, sizeof(struct sample_conv));
1317
1318 /* Register this new converter */
1319 sample_register_convs(sck);
1320
1321 return 0;
1322}
1323
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01001324/* This fucntion is an LUA binding used for registering
1325 * "sample-fetch" functions. It expects a converter name used
1326 * in the haproxy configuration file, and an LUA function.
1327 */
1328__LJMP static int hlua_register_fetches(lua_State *L)
1329{
1330 const char *name;
1331 int ref;
1332 int len;
1333 struct sample_fetch_kw_list *sfk;
1334 struct hlua_function *fcn;
1335
1336 MAY_LJMP(check_args(L, 2, "register_fetches"));
1337
1338 /* First argument : sample-fetch name. */
1339 name = MAY_LJMP(luaL_checkstring(L, 1));
1340
1341 /* Second argument : lua function. */
1342 ref = MAY_LJMP(hlua_checkfunction(L, 2));
1343
1344 /* Allocate and fill the sample fetch keyword struct. */
1345 sfk = malloc(sizeof(struct sample_fetch_kw_list) +
1346 sizeof(struct sample_fetch) * 2);
1347 if (!sfk)
1348 WILL_LJMP(luaL_error(L, "lua out of memory error."));
1349 fcn = malloc(sizeof(*fcn));
1350 if (!fcn)
1351 WILL_LJMP(luaL_error(L, "lua out of memory error."));
1352
1353 /* Fill fcn. */
1354 fcn->name = strdup(name);
1355 if (!fcn->name)
1356 WILL_LJMP(luaL_error(L, "lua out of memory error."));
1357 fcn->function_ref = ref;
1358
1359 /* List head */
1360 sfk->list.n = sfk->list.p = NULL;
1361
1362 /* sample-fetch keyword. */
1363 len = strlen("lua.") + strlen(name) + 1;
1364 sfk->kw[0].kw = malloc(len);
1365 if (!sfk->kw[0].kw)
1366 return luaL_error(L, "lua out of memory error.");
1367
1368 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
1369 sfk->kw[0].process = hlua_sample_fetch_wrapper;
1370 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
1371 sfk->kw[0].val_args = NULL;
1372 sfk->kw[0].out_type = SMP_T_STR;
1373 sfk->kw[0].use = SMP_USE_HTTP_ANY;
1374 sfk->kw[0].val = 0;
1375 sfk->kw[0].private = fcn;
1376
1377 /* End of array. */
1378 memset(&sfk->kw[1], 0, sizeof(struct sample_fetch));
1379
1380 /* Register this new fetch. */
1381 sample_register_fetches(sfk);
1382
1383 return 0;
1384}
1385
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01001386/* This function is called by the main configuration key "lua-load". It loads and
1387 * execute an lua file during the parsing of the HAProxy configuration file. It is
1388 * the main lua entry point.
1389 *
1390 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
1391 * occured, otherwise it returns 0.
1392 *
1393 * In some error case, LUA set an error message in top of the stack. This function
1394 * returns this error message in the HAProxy logs and pop it from the stack.
1395 */
1396static int hlua_load(char **args, int section_type, struct proxy *curpx,
1397 struct proxy *defpx, const char *file, int line,
1398 char **err)
1399{
1400 int error;
1401
1402 /* Just load and compile the file. */
1403 error = luaL_loadfile(gL.T, args[1]);
1404 if (error) {
1405 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
1406 lua_pop(gL.T, 1);
1407 return -1;
1408 }
1409
1410 /* If no syntax error where detected, execute the code. */
1411 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
1412 switch (error) {
1413 case LUA_OK:
1414 break;
1415 case LUA_ERRRUN:
1416 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
1417 lua_pop(gL.T, 1);
1418 return -1;
1419 case LUA_ERRMEM:
1420 memprintf(err, "lua out of memory error\n");
1421 return -1;
1422 case LUA_ERRERR:
1423 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
1424 lua_pop(gL.T, 1);
1425 return -1;
1426 case LUA_ERRGCMM:
1427 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
1428 lua_pop(gL.T, 1);
1429 return -1;
1430 default:
1431 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
1432 lua_pop(gL.T, 1);
1433 return -1;
1434 }
1435
1436 return 0;
1437}
1438
1439/* configuration keywords declaration */
1440static struct cfg_kw_list cfg_kws = {{ },{
1441 { CFG_GLOBAL, "lua-load", hlua_load },
1442 { 0, NULL, NULL },
1443}};
1444
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01001445int hlua_post_init()
1446{
1447 struct hlua_init_function *init;
1448 const char *msg;
1449 enum hlua_exec ret;
1450
1451 list_for_each_entry(init, &hlua_init_functions, l) {
1452 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
1453 ret = hlua_ctx_resume(&gL, 0);
1454 switch (ret) {
1455 case HLUA_E_OK:
1456 lua_pop(gL.T, -1);
1457 return 1;
1458 case HLUA_E_AGAIN:
1459 Alert("lua init: yield not allowed.\n");
1460 return 0;
1461 case HLUA_E_ERRMSG:
1462 msg = lua_tostring(gL.T, -1);
1463 Alert("lua init: %s.\n", msg);
1464 return 0;
1465 case HLUA_E_ERR:
1466 default:
1467 Alert("lua init: unknown runtime error.\n");
1468 return 0;
1469 }
1470 }
1471 return 1;
1472}
1473
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01001474void hlua_init(void)
1475{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01001476 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01001477 int idx;
1478 struct sample_fetch *sf;
1479 struct hlua_sample_fetch *hsf;
1480 char *p;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01001481
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001482 /* Initialise com signals pool session. */
1483 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
1484
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01001485 /* Register configuration keywords. */
1486 cfg_register_keywords(&cfg_kws);
1487
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001488 /* Init main lua stack. */
1489 gL.Mref = LUA_REFNIL;
1490 gL.state = HLUA_STOP;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001491 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001492 gL.T = luaL_newstate();
1493 hlua_sethlua(&gL);
1494 gL.Tref = LUA_REFNIL;
1495 gL.task = NULL;
1496
1497 /* Initialise lua. */
1498 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01001499
1500 /*
1501 *
1502 * Create "core" object.
1503 *
1504 */
1505
1506 /* This integer entry is just used as base value for the object "core". */
1507 lua_pushinteger(gL.T, 0);
1508
1509 /* Create and fill the metatable. */
1510 lua_newtable(gL.T);
1511
1512 /* Create and fill the __index entry. */
1513 lua_pushstring(gL.T, "__index");
1514 lua_newtable(gL.T);
1515
1516 /* Push the loglevel constants. */
1517 for (i=0; i<NB_LOG_LEVELS; i++)
1518 hlua_class_const_int(gL.T, log_levels[i], i);
1519
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01001520 /* Register special functions. */
1521 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01001522 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01001523 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01001524 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01001525
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01001526 /* Store the table __index in the metable. */
1527 lua_settable(gL.T, -3);
1528
1529 /* Register previous table in the registry with named entry. */
1530 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
1531 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CORE); /* register class session. */
1532
1533 /* Register previous table in the registry with reference. */
1534 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
1535 class_core_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
1536
1537 /* Create new object with class Core. */
1538 lua_setmetatable(gL.T, -2);
1539 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001540
1541 /*
1542 *
1543 * Register class TXN
1544 *
1545 */
1546
1547 /* Create and fill the metatable. */
1548 lua_newtable(gL.T);
1549
1550 /* Create and fille the __index entry. */
1551 lua_pushstring(gL.T, "__index");
1552 lua_newtable(gL.T);
1553
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01001554 /* Browse existing fetches and create the associated
1555 * object method.
1556 */
1557 sf = NULL;
1558 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
1559
1560 /* Dont register the keywork if the arguments check function are
1561 * not safe during the runtime.
1562 */
1563 if ((sf->val_args != NULL) &&
1564 (sf->val_args != val_payload_lv) &&
1565 (sf->val_args != val_hdr))
1566 continue;
1567
1568 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
1569 * by an underscore.
1570 */
1571 strncpy(trash.str, sf->kw, trash.size);
1572 trash.str[trash.size - 1] = '\0';
1573 for (p = trash.str; *p; p++)
1574 if (*p == '.' || *p == '-' || *p == '+')
1575 *p = '_';
1576
1577 /* Register the function. */
1578 lua_pushstring(gL.T, trash.str);
1579 hsf = lua_newuserdata(gL.T, sizeof(struct hlua_sample_fetch));
1580 hsf->f = sf;
1581 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
1582 lua_settable(gL.T, -3);
1583 }
1584
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01001585 /* Register Lua functions. */
Thierry FOURNIER9a819e72015-02-16 20:22:55 +01001586 hlua_class_function(gL.T, "get_headers", hlua_session_getheaders);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01001587 hlua_class_function(gL.T, "set_priv", hlua_setpriv);
1588 hlua_class_function(gL.T, "get_priv", hlua_getpriv);
1589
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001590 lua_settable(gL.T, -3);
1591
1592 /* Register previous table in the registry with reference and named entry. */
1593 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
1594 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
1595 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01001596}