blob: bf3ed29f14998c571fd6e858a9bfa3d3b8ec57bd [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 FOURNIERd0fa5382015-02-16 20:14:51 +010014#include <proto/payload.h>
15#include <proto/proto_http.h>
16#include <proto/sample.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010017#include <proto/task.h>
18
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010019/* Lua uses longjmp to perform yield or throwing errors. This
20 * macro is used only for identifying the function that can
21 * not return because a longjmp is executed.
22 * __LJMP marks a prototype of hlua file that can use longjmp.
23 * WILL_LJMP() marks an lua function that will use longjmp.
24 * MAY_LJMP() marks an lua function that may use longjmp.
25 */
26#define __LJMP
27#define WILL_LJMP(func) func
28#define MAY_LJMP(func) func
29
Thierry FOURNIER380d0932015-01-23 14:27:52 +010030/* The main Lua execution context. */
31struct hlua gL;
32
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010033/* This is the memory pool containing all the signal structs. These
34 * struct are used to store each requiered signal between two tasks.
35 */
36struct pool_head *pool2_hlua_com;
37
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010038/* List head of the function called at the initialisation time. */
39struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
40
Thierry FOURNIER380d0932015-01-23 14:27:52 +010041/* Store the fast lua context for coroutines. This tree uses the
42 * Lua stack pointer value as indexed entry, and store the associated
43 * hlua context.
44 */
45struct eb_root hlua_ctx = EB_ROOT_UNIQUE;
46
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010047/* The following variables contains the reference of the different
48 * Lua classes. These references are useful for identify metadata
49 * associated with an object.
50 */
51static int class_core_ref;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010052static int class_txn_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010053
Thierry FOURNIER55da1652015-01-23 11:36:30 +010054/* These functions converts types between HAProxy internal args or
55 * sample and LUA types. Another function permits to check if the
56 * LUA stack contains arguments according with an required ARG_T
57 * format.
58 */
59static int hlua_arg2lua(lua_State *L, const struct arg *arg);
60static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
61__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp, unsigned int mask);
62static int hlua_smp2lua(lua_State *L, const struct sample *smp);
63static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
64
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +010065/* Used to check an Lua function type in the stack. It creates and
66 * returns a reference of the function. This function throws an
67 * error if the rgument is not a "function".
68 */
69__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
70{
71 if (!lua_isfunction(L, argno)) {
72 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
73 WILL_LJMP(luaL_argerror(L, argno, msg));
74 }
75 lua_pushvalue(L, argno);
76 return luaL_ref(L, LUA_REGISTRYINDEX);
77}
78
79/* The three following functions are useful for adding entries
80 * in a table. These functions takes a string and respectively an
81 * integer, a string or a function and add it to the table in the
82 * top of the stack.
83 *
84 * These functions throws an error if no more stack size is
85 * available.
86 */
87__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
88 unsigned int value)
89{
90 if (!lua_checkstack(L, 2))
91 WILL_LJMP(luaL_error(L, "full stack"));
92 lua_pushstring(L, name);
93 lua_pushunsigned(L, value);
94 lua_settable(L, -3);
95}
96__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
97 const char *value)
98{
99 if (!lua_checkstack(L, 2))
100 WILL_LJMP(luaL_error(L, "full stack"));
101 lua_pushstring(L, name);
102 lua_pushstring(L, value);
103 lua_settable(L, -3);
104}
105__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
106 int (*function)(lua_State *L))
107{
108 if (!lua_checkstack(L, 2))
109 WILL_LJMP(luaL_error(L, "full stack"));
110 lua_pushstring(L, name);
111 lua_pushcclosure(L, function, 0);
112 lua_settable(L, -3);
113}
114
115/* This function check the number of arguments available in the
116 * stack. If the number of arguments available is not the same
117 * then <nb> an error is throwed.
118 */
119__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
120{
121 if (lua_gettop(L) == nb)
122 return;
123 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
124}
125
126/* Return true if the data in stack[<ud>] is an object of
127 * type <class_ref>.
128 */
129static int hlua_udataistype(lua_State *L, int ud, int class_ref)
130{
131 void *p = lua_touserdata(L, ud);
132 if (!p)
133 return 0;
134
135 if (!lua_getmetatable(L, ud))
136 return 0;
137
138 lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
139 if (!lua_rawequal(L, -1, -2)) {
140 lua_pop(L, 2);
141 return 0;
142 }
143
144 lua_pop(L, 2);
145 return 1;
146}
147
148/* Return an object of the expected type, or throws an error. */
149__LJMP static void *hlua_checkudata(lua_State *L, int ud, int class_ref)
150{
151 if (!hlua_udataistype(L, ud, class_ref))
152 WILL_LJMP(luaL_argerror(L, 1, NULL));
153 return lua_touserdata(L, ud);
154}
155
156/* This fucntion push an error string prefixed by the file name
157 * and the line number where the error is encountered.
158 */
159static int hlua_pusherror(lua_State *L, const char *fmt, ...)
160{
161 va_list argp;
162 va_start(argp, fmt);
163 luaL_where(L, 1);
164 lua_pushvfstring(L, fmt, argp);
165 va_end(argp);
166 lua_concat(L, 2);
167 return 1;
168}
169
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100170/* This function register a new signal. "lua" is the current lua
171 * execution context. It contains a pointer to the associated task.
172 * "link" is a list head attached to an other task that must be wake
173 * the lua task if an event occurs. This is useful with external
174 * events like TCP I/O or sleep functions. This funcion allocate
175 * memory for the signal.
176 */
177static int hlua_com_new(struct hlua *lua, struct list *link)
178{
179 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
180 if (!com)
181 return 0;
182 LIST_ADDQ(&lua->com, &com->purge_me);
183 LIST_ADDQ(link, &com->wake_me);
184 com->task = lua->task;
185 return 1;
186}
187
188/* This function purge all the pending signals when the LUA execution
189 * is finished. This prevent than a coprocess try to wake a deleted
190 * task. This function remove the memory associated to the signal.
191 */
192static void hlua_com_purge(struct hlua *lua)
193{
194 struct hlua_com *com, *back;
195
196 /* Delete all pending communication signals. */
197 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
198 LIST_DEL(&com->purge_me);
199 LIST_DEL(&com->wake_me);
200 pool_free2(pool2_hlua_com, com);
201 }
202}
203
204/* This function sends signals. It wakes all the tasks attached
205 * to a list head, and remove the signal, and free the used
206 * memory.
207 */
208static void hlua_com_wake(struct list *wake)
209{
210 struct hlua_com *com, *back;
211
212 /* Wake task and delete all pending communication signals. */
213 list_for_each_entry_safe(com, back, wake, wake_me) {
214 LIST_DEL(&com->purge_me);
215 LIST_DEL(&com->wake_me);
216 task_wakeup(com->task, TASK_WOKEN_MSG);
217 pool_free2(pool2_hlua_com, com);
218 }
219}
220
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100221/* This functions is used with sample fetch and converters. It
222 * converts the HAProxy configuration argument in a lua stack
223 * values.
224 *
225 * It takes an array of "arg", and each entry of the array is
226 * converted and pushed in the LUA stack.
227 */
228static int hlua_arg2lua(lua_State *L, const struct arg *arg)
229{
230 switch (arg->type) {
231 case ARGT_SINT:
232 lua_pushinteger(L, arg->data.sint);
233 break;
234
235 case ARGT_UINT:
236 case ARGT_TIME:
237 case ARGT_SIZE:
238 lua_pushunsigned(L, arg->data.sint);
239 break;
240
241 case ARGT_STR:
242 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
243 break;
244
245 case ARGT_IPV4:
246 case ARGT_IPV6:
247 case ARGT_MSK4:
248 case ARGT_MSK6:
249 case ARGT_FE:
250 case ARGT_BE:
251 case ARGT_TAB:
252 case ARGT_SRV:
253 case ARGT_USR:
254 case ARGT_MAP:
255 default:
256 lua_pushnil(L);
257 break;
258 }
259 return 1;
260}
261
262/* This function take one entrie in an LUA stack at the index "ud",
263 * and try to convert it in an HAProxy argument entry. This is useful
264 * with sample fetch wrappers. The input arguments are gived to the
265 * lua wrapper and converted as arg list by thi function.
266 */
267static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
268{
269 switch (lua_type(L, ud)) {
270
271 case LUA_TNUMBER:
272 case LUA_TBOOLEAN:
273 arg->type = ARGT_SINT;
274 arg->data.sint = lua_tointeger(L, ud);
275 break;
276
277 case LUA_TSTRING:
278 arg->type = ARGT_STR;
279 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
280 break;
281
282 case LUA_TUSERDATA:
283 case LUA_TNIL:
284 case LUA_TTABLE:
285 case LUA_TFUNCTION:
286 case LUA_TTHREAD:
287 case LUA_TLIGHTUSERDATA:
288 arg->type = ARGT_SINT;
289 arg->data.uint = 0;
290 break;
291 }
292 return 1;
293}
294
295/* the following functions are used to convert a struct sample
296 * in Lua type. This useful to convert the return of the
297 * fetchs or converters.
298 */
299static int hlua_smp2lua(lua_State *L, const struct sample *smp)
300{
301 switch (smp->type) {
302 case SMP_T_SINT:
303 lua_pushinteger(L, smp->data.sint);
304 break;
305
306 case SMP_T_BOOL:
307 case SMP_T_UINT:
308 lua_pushunsigned(L, smp->data.uint);
309 break;
310
311 case SMP_T_BIN:
312 case SMP_T_STR:
313 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
314 break;
315
316 case SMP_T_METH:
317 switch (smp->data.meth.meth) {
318 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
319 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
320 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
321 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
322 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
323 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
324 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
325 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
326 case HTTP_METH_OTHER:
327 lua_pushlstring(L, smp->data.meth.str.str, smp->data.meth.str.len);
328 break;
329 default:
330 lua_pushnil(L);
331 break;
332 }
333 break;
334
335 case SMP_T_IPV4:
336 case SMP_T_IPV6:
337 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
338 default:
339 lua_pushnil(L);
340 break;
341 }
342 return 1;
343}
344
345/* the following functions are used to convert an Lua type in a
346 * struct sample. This is useful to provide data from a converter
347 * to the LUA code.
348 */
349static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
350{
351 switch (lua_type(L, ud)) {
352
353 case LUA_TNUMBER:
354 smp->type = SMP_T_SINT;
355 smp->data.sint = lua_tointeger(L, ud);
356 break;
357
358
359 case LUA_TBOOLEAN:
360 smp->type = SMP_T_BOOL;
361 smp->data.uint = lua_toboolean(L, ud);
362 break;
363
364 case LUA_TSTRING:
365 smp->type = SMP_T_STR;
366 smp->flags |= SMP_F_CONST;
367 smp->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.str.len);
368 break;
369
370 case LUA_TUSERDATA:
371 case LUA_TNIL:
372 case LUA_TTABLE:
373 case LUA_TFUNCTION:
374 case LUA_TTHREAD:
375 case LUA_TLIGHTUSERDATA:
376 smp->type = SMP_T_BOOL;
377 smp->data.uint = 0;
378 break;
379 }
380 return 1;
381}
382
383/* This function check the "argp" builded by another conversion function
384 * is in accord with the expected argp defined by the "mask". The fucntion
385 * returns true or false. It can be adjust the types if there compatibles.
386 */
387__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp, unsigned int mask)
388{
389 int min_arg;
390 int idx;
391
392 idx = 0;
393 min_arg = ARGM(mask);
394 mask >>= ARGM_BITS;
395
396 while (1) {
397
398 /* Check oversize. */
399 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
400 WILL_LJMP(luaL_argerror(L, first + idx, "Malformad argument mask"));
401 }
402
403 /* Check for mandatory arguments. */
404 if (argp[idx].type == ARGT_STOP) {
405 if (idx + 1 < min_arg)
406 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
407 return 0;
408 }
409
410 /* Check for exceed the number of requiered argument. */
411 if ((mask & ARGT_MASK) == ARGT_STOP &&
412 argp[idx].type != ARGT_STOP) {
413 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
414 }
415
416 if ((mask & ARGT_MASK) == ARGT_STOP &&
417 argp[idx].type == ARGT_STOP) {
418 return 0;
419 }
420
421 /* Compatibility mask. */
422 switch (argp[idx].type) {
423 case ARGT_SINT:
424 switch (mask & ARGT_MASK) {
425 case ARGT_UINT: argp[idx].type = mask & ARGT_MASK; break;
426 case ARGT_TIME: argp[idx].type = mask & ARGT_MASK; break;
427 case ARGT_SIZE: argp[idx].type = mask & ARGT_MASK; break;
428 }
429 break;
430 }
431
432 /* Check for type of argument. */
433 if ((mask & ARGT_MASK) != argp[idx].type) {
434 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
435 arg_type_names[(mask & ARGT_MASK)],
436 arg_type_names[argp[idx].type & ARGT_MASK]);
437 WILL_LJMP(luaL_argerror(L, first + idx, msg));
438 }
439
440 /* Next argument. */
441 mask >>= ARGT_BITS;
442 idx++;
443 }
444}
445
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100446/*
447 * The following functions are used to make correspondance between the the
448 * executed lua pointer and the "struct hlua *" that contain the context.
449 * They run with the tree head "hlua_ctx", they just perform lookup in the
450 * tree.
451 *
452 * - hlua_gethlua : return the hlua context associated with an lua_State.
453 * - hlua_delhlua : remove the association between hlua context and lua_state.
454 * - hlua_sethlua : create the association between hlua context and lua_state.
455 */
456static inline struct hlua *hlua_gethlua(lua_State *L)
457{
458 struct ebpt_node *node;
459
460 node = ebpt_lookup(&hlua_ctx, L);
461 if (!node)
462 return NULL;
463 return ebpt_entry(node, struct hlua, node);
464}
465static inline void hlua_delhlua(struct hlua *hlua)
466{
467 if (hlua->node.key)
468 ebpt_delete(&hlua->node);
469}
470static inline void hlua_sethlua(struct hlua *hlua)
471{
472 hlua->node.key = hlua->T;
473 ebpt_insert(&hlua_ctx, &hlua->node);
474}
475
476/* This function initialises the Lua environment stored in the session.
477 * It must be called at the start of the session. This function creates
478 * an LUA coroutine. It can not be use to crete the main LUA context.
479 */
480int hlua_ctx_init(struct hlua *lua, struct task *task)
481{
482 lua->Mref = LUA_REFNIL;
483 lua->state = HLUA_STOP;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100484 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100485 lua->T = lua_newthread(gL.T);
486 if (!lua->T) {
487 lua->Tref = LUA_REFNIL;
488 return 0;
489 }
490 hlua_sethlua(lua);
491 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
492 lua->task = task;
493 return 1;
494}
495
496/* Used to destroy the Lua coroutine when the attached session or task
497 * is destroyed. The destroy also the memory context. The struct "lua"
498 * is not freed.
499 */
500void hlua_ctx_destroy(struct hlua *lua)
501{
502 /* Remove context. */
503 hlua_delhlua(lua);
504
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100505 /* Purge all the pending signals. */
506 hlua_com_purge(lua);
507
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100508 /* The thread is garbage collected by Lua. */
509 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
510 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
511}
512
513/* This function is used to restore the Lua context when a coroutine
514 * fails. This function copy the common memory between old coroutine
515 * and the new coroutine. The old coroutine is destroyed, and its
516 * replaced by the new coroutine.
517 * If the flag "keep_msg" is set, the last entry of the old is assumed
518 * as string error message and it is copied in the new stack.
519 */
520static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
521{
522 lua_State *T;
523 int new_ref;
524
525 /* Renew the main LUA stack doesn't have sense. */
526 if (lua == &gL)
527 return 0;
528
529 /* Remove context. */
530 hlua_delhlua(lua);
531
532 /* New Lua coroutine. */
533 T = lua_newthread(gL.T);
534 if (!T)
535 return 0;
536
537 /* Copy last error message. */
538 if (keep_msg)
539 lua_xmove(lua->T, T, 1);
540
541 /* Copy data between the coroutines. */
542 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
543 lua_xmove(lua->T, T, 1);
544 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
545
546 /* Destroy old data. */
547 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
548
549 /* The thread is garbage collected by Lua. */
550 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
551
552 /* Fill the struct with the new coroutine values. */
553 lua->Mref = new_ref;
554 lua->T = T;
555 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
556
557 /* Set context. */
558 hlua_sethlua(lua);
559
560 return 1;
561}
562
563/* This function start or resumes the Lua stack execution. If the flag
564 * "yield_allowed" if no set and the LUA stack execution returns a yield
565 * The function return an error.
566 *
567 * The function can returns 4 values:
568 * - HLUA_E_OK : The execution is terminated without any errors.
569 * - HLUA_E_AGAIN : The execution must continue at the next associated
570 * task wakeup.
571 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
572 * the top of the stack.
573 * - HLUA_E_ERR : An error has occured without error message.
574 *
575 * If an error occured, the stack is renewed and it is ready to run new
576 * LUA code.
577 */
578static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
579{
580 int ret;
581 const char *msg;
582
583 lua->state = HLUA_RUN;
584
585 /* Call the function. */
586 ret = lua_resume(lua->T, gL.T, lua->nargs);
587 switch (ret) {
588
589 case LUA_OK:
590 ret = HLUA_E_OK;
591 break;
592
593 case LUA_YIELD:
594 if (!yield_allowed) {
595 lua_settop(lua->T, 0); /* Empty the stack. */
596 if (!lua_checkstack(lua->T, 1)) {
597 ret = HLUA_E_ERR;
598 break;
599 }
600 lua_pushfstring(lua->T, "yield not allowed");
601 ret = HLUA_E_ERRMSG;
602 break;
603 }
604 ret = HLUA_E_AGAIN;
605 break;
606
607 case LUA_ERRRUN:
608 if (!lua_checkstack(lua->T, 1)) {
609 ret = HLUA_E_ERR;
610 break;
611 }
612 msg = lua_tostring(lua->T, -1);
613 lua_settop(lua->T, 0); /* Empty the stack. */
614 lua_pop(lua->T, 1);
615 if (msg)
616 lua_pushfstring(lua->T, "runtime error: %s", msg);
617 else
618 lua_pushfstring(lua->T, "unknown runtime error");
619 ret = HLUA_E_ERRMSG;
620 break;
621
622 case LUA_ERRMEM:
623 lua_settop(lua->T, 0); /* Empty the stack. */
624 if (!lua_checkstack(lua->T, 1)) {
625 ret = HLUA_E_ERR;
626 break;
627 }
628 lua_pushfstring(lua->T, "out of memory error");
629 ret = HLUA_E_ERRMSG;
630 break;
631
632 case LUA_ERRERR:
633 if (!lua_checkstack(lua->T, 1)) {
634 ret = HLUA_E_ERR;
635 break;
636 }
637 msg = lua_tostring(lua->T, -1);
638 lua_settop(lua->T, 0); /* Empty the stack. */
639 lua_pop(lua->T, 1);
640 if (msg)
641 lua_pushfstring(lua->T, "message handler error: %s", msg);
642 else
643 lua_pushfstring(lua->T, "message handler error");
644 ret = HLUA_E_ERRMSG;
645 break;
646
647 default:
648 lua_settop(lua->T, 0); /* Empty the stack. */
649 if (!lua_checkstack(lua->T, 1)) {
650 ret = HLUA_E_ERR;
651 break;
652 }
653 lua_pushfstring(lua->T, "unknonwn error");
654 ret = HLUA_E_ERRMSG;
655 break;
656 }
657
658 switch (ret) {
659 case HLUA_E_AGAIN:
660 break;
661
662 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100663 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100664 hlua_ctx_renew(lua, 1);
665 lua->state = HLUA_STOP;
666 break;
667
668 case HLUA_E_ERR:
669 lua->state = HLUA_STOP;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100670 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100671 hlua_ctx_renew(lua, 0);
672 break;
673
674 case HLUA_E_OK:
675 lua->state = HLUA_STOP;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100676 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100677 break;
678 }
679
680 return ret;
681}
682
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100683/* A class is a lot of memory that contain data. This data can be a table,
684 * an integer or user data. This data is associated with a metatable. This
685 * metatable have an original version registred in the global context with
686 * the name of the object (_G[<name>] = <metable> ).
687 *
688 * A metable is a table that modify the standard behavior of a standard
689 * access to the associated data. The entries of this new metatable are
690 * defined as is:
691 *
692 * http://lua-users.org/wiki/MetatableEvents
693 *
694 * __index
695 *
696 * we access an absent field in a table, the result is nil. This is
697 * true, but it is not the whole truth. Actually, such access triggers
698 * the interpreter to look for an __index metamethod: If there is no
699 * such method, as usually happens, then the access results in nil;
700 * otherwise, the metamethod will provide the result.
701 *
702 * Control 'prototype' inheritance. When accessing "myTable[key]" and
703 * the key does not appear in the table, but the metatable has an __index
704 * property:
705 *
706 * - if the value is a function, the function is called, passing in the
707 * table and the key; the return value of that function is returned as
708 * the result.
709 *
710 * - if the value is another table, the value of the key in that table is
711 * asked for and returned (and if it doesn't exist in that table, but that
712 * table's metatable has an __index property, then it continues on up)
713 *
714 * - Use "rawget(myTable,key)" to skip this metamethod.
715 *
716 * http://www.lua.org/pil/13.4.1.html
717 *
718 * __newindex
719 *
720 * Like __index, but control property assignment.
721 *
722 * __mode - Control weak references. A string value with one or both
723 * of the characters 'k' and 'v' which specifies that the the
724 * keys and/or values in the table are weak references.
725 *
726 * __call - Treat a table like a function. When a table is followed by
727 * parenthesis such as "myTable( 'foo' )" and the metatable has
728 * a __call key pointing to a function, that function is invoked
729 * (passing any specified arguments) and the return value is
730 * returned.
731 *
732 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
733 * called, if the metatable for myTable has a __metatable
734 * key, the value of that key is returned instead of the
735 * actual metatable.
736 *
737 * __tostring - Control string representation. When the builtin
738 * "tostring( myTable )" function is called, if the metatable
739 * for myTable has a __tostring property set to a function,
740 * that function is invoked (passing myTable to it) and the
741 * return value is used as the string representation.
742 *
743 * __len - Control table length. When the table length is requested using
744 * the length operator ( '#' ), if the metatable for myTable has
745 * a __len key pointing to a function, that function is invoked
746 * (passing myTable to it) and the return value used as the value
747 * of "#myTable".
748 *
749 * __gc - Userdata finalizer code. When userdata is set to be garbage
750 * collected, if the metatable has a __gc field pointing to a
751 * function, that function is first invoked, passing the userdata
752 * to it. The __gc metamethod is not called for tables.
753 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
754 *
755 * Special metamethods for redefining standard operators:
756 * http://www.lua.org/pil/13.1.html
757 *
758 * __add "+"
759 * __sub "-"
760 * __mul "*"
761 * __div "/"
762 * __unm "!"
763 * __pow "^"
764 * __concat ".."
765 *
766 * Special methods for redfining standar relations
767 * http://www.lua.org/pil/13.2.html
768 *
769 * __eq "=="
770 * __lt "<"
771 * __le "<="
772 */
773
774/*
775 *
776 *
777 * Class TXN
778 *
779 *
780 */
781
782/* Returns a struct hlua_session if the stack entry "ud" is
783 * a class session, otherwise it throws an error.
784 */
785__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
786{
787 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
788}
789
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +0100790__LJMP static int hlua_setpriv(lua_State *L)
791{
792 MAY_LJMP(check_args(L, 2, "set_priv"));
793
794 /* It is useles to retrieve the session, but this function
795 * runs only in a session context.
796 */
797 MAY_LJMP(hlua_checktxn(L, 1));
798 struct hlua *hlua = hlua_gethlua(L);
799
800 /* Remove previous value. */
801 if (hlua->Mref != -1)
802 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
803
804 /* Get and store new value. */
805 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
806 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
807
808 return 0;
809}
810
811__LJMP static int hlua_getpriv(lua_State *L)
812{
813 MAY_LJMP(check_args(L, 1, "get_priv"));
814
815 /* It is useles to retrieve the session, but this function
816 * runs only in a session context.
817 */
818 MAY_LJMP(hlua_checktxn(L, 1));
819 struct hlua *hlua = hlua_gethlua(L);
820
821 /* Push configuration index in the stack. */
822 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
823
824 return 1;
825}
826
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100827/* Create stack entry containing a class TXN. This function
828 * return 0 if the stack does not contains free slots,
829 * otherwise it returns 1.
830 */
831static int hlua_txn_new(lua_State *L, struct session *s, struct proxy *p, void *l7)
832{
833 struct hlua_txn *hs;
834
835 /* Check stack size. */
836 if (!lua_checkstack(L, 2))
837 return 0;
838
839 /* NOTE: The allocation never fails. The failure
840 * throw an error, and the function never returns.
841 * if the throw is not avalaible, the process is aborted.
842 */
843 hs = lua_newuserdata(L, sizeof(struct hlua_txn));
844 hs->s = s;
845 hs->p = p;
846 hs->l7 = l7;
847
848 /* Pop a class sesison metatable and affect it to the userdata. */
849 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
850 lua_setmetatable(L, -2);
851
852 return 1;
853}
854
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +0100855/* This function is an LUA binding. It is called with each sample-fetch.
856 * It uses closure argument to store the associated sample-fetch. It
857 * returns only one argument or throws an error. An error is throwed
858 * only if an error is encoutered during the argument parsing. If
859 * the "sample-fetch" function fails, nil is returned.
860 */
861__LJMP static int hlua_run_sample_fetch(lua_State *L)
862{
863 struct hlua_txn *s;
864 struct hlua_sample_fetch *f;
865 struct arg args[ARGM_NBARGS];
866 int i;
867 struct sample smp;
868
869 /* Get closure arguments. */
870 f = (struct hlua_sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
871
872 /* Get traditionnal arguments. */
873 s = MAY_LJMP(hlua_checktxn(L, 1));
874
875 /* Get extra arguments. */
876 for (i = 0; i <= lua_gettop(L); i++) {
877 if (i >= ARGM_NBARGS)
878 break;
879 hlua_lua2arg(L, i + 2, &args[i]);
880 }
881 args[i].type = ARGT_STOP;
882
883 /* Check arguments. */
884 MAY_LJMP(hlua_lua2arg_check(L, 1, args, f->f->arg_mask));
885
886 /* Run the special args cehcker. */
887 if (!f->f->val_args(args, NULL)) {
888 lua_pushfstring(L, "error in arguments");
889 WILL_LJMP(lua_error(L));
890 }
891
892 /* Initialise the sample. */
893 memset(&smp, 0, sizeof(smp));
894
895 /* Run the sample fetch process. */
896 if (!f->f->process(s->p, s->s, s->l7, 0, args, &smp, f->f->kw, f->f->private)) {
897 lua_pushnil(L);
898 return 1;
899 }
900
901 /* Convert the returned sample in lua value. */
902 hlua_smp2lua(L, &smp);
903 return 1;
904}
905
Thierry FOURNIER24f33532015-01-23 12:13:00 +0100906/* This function is used as a calback of a task. It is called by the
907 * HAProxy task subsystem when the task is awaked. The LUA runtime can
908 * return an E_AGAIN signal, the emmiter of this signal must set a
909 * signal to wake the task.
910 */
911static struct task *hlua_process_task(struct task *task)
912{
913 struct hlua *hlua = task->context;
914 enum hlua_exec status;
915
916 /* We need to remove the task from the wait queue before executing
917 * the Lua code because we don't know if it needs to wait for
918 * another timer or not in the case of E_AGAIN.
919 */
920 task_delete(task);
921
922 /* Execute the Lua code. */
923 status = hlua_ctx_resume(hlua, 1);
924
925 switch (status) {
926 /* finished or yield */
927 case HLUA_E_OK:
928 hlua_ctx_destroy(hlua);
929 task_delete(task);
930 task_free(task);
931 break;
932
933 case HLUA_E_AGAIN: /* co process wake me later. */
934 break;
935
936 /* finished with error. */
937 case HLUA_E_ERRMSG:
938 send_log(NULL, LOG_ERR, "Lua task: %s.", lua_tostring(hlua->T, -1));
939 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
940 Alert("Lua task: %s.\n", lua_tostring(hlua->T, -1));
941 hlua_ctx_destroy(hlua);
942 task_delete(task);
943 task_free(task);
944 break;
945
946 case HLUA_E_ERR:
947 default:
948 send_log(NULL, LOG_ERR, "Lua task: unknown error.");
949 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
950 Alert("Lua task: unknown error.\n");
951 hlua_ctx_destroy(hlua);
952 task_delete(task);
953 task_free(task);
954 break;
955 }
956 return NULL;
957}
958
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100959/* This function is an LUA binding that register LUA function to be
960 * executed after the HAProxy configuration parsing and before the
961 * HAProxy scheduler starts. This function expect only one LUA
962 * argument that is a function. This function returns nothing, but
963 * throws if an error is encountered.
964 */
965__LJMP static int hlua_register_init(lua_State *L)
966{
967 struct hlua_init_function *init;
968 int ref;
969
970 MAY_LJMP(check_args(L, 1, "register_init"));
971
972 ref = MAY_LJMP(hlua_checkfunction(L, 1));
973
974 init = malloc(sizeof(*init));
975 if (!init)
976 WILL_LJMP(luaL_error(L, "lua out of memory error."));
977
978 init->function_ref = ref;
979 LIST_ADDQ(&hlua_init_functions, &init->l);
980 return 0;
981}
982
Thierry FOURNIER24f33532015-01-23 12:13:00 +0100983/* This functio is an LUA binding. It permits to register a task
984 * executed in parallel of the main HAroxy activity. The task is
985 * created and it is set in the HAProxy scheduler. It can be called
986 * from the "init" section, "post init" or during the runtime.
987 *
988 * Lua prototype:
989 *
990 * <none> core.register_task(<function>)
991 */
992static int hlua_register_task(lua_State *L)
993{
994 struct hlua *hlua;
995 struct task *task;
996 int ref;
997
998 MAY_LJMP(check_args(L, 1, "register_task"));
999
1000 ref = MAY_LJMP(hlua_checkfunction(L, 1));
1001
1002 hlua = malloc(sizeof(*hlua));
1003 if (!hlua)
1004 WILL_LJMP(luaL_error(L, "lua out of memory error."));
1005
1006 task = task_new();
1007 task->context = hlua;
1008 task->process = hlua_process_task;
1009
1010 if (!hlua_ctx_init(hlua, task))
1011 WILL_LJMP(luaL_error(L, "lua out of memory error."));
1012
1013 /* Restore the function in the stack. */
1014 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
1015 hlua->nargs = 0;
1016
1017 /* Schedule task. */
1018 task_schedule(task, now_ms);
1019
1020 return 0;
1021}
1022
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01001023/* This function is called by the main configuration key "lua-load". It loads and
1024 * execute an lua file during the parsing of the HAProxy configuration file. It is
1025 * the main lua entry point.
1026 *
1027 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
1028 * occured, otherwise it returns 0.
1029 *
1030 * In some error case, LUA set an error message in top of the stack. This function
1031 * returns this error message in the HAProxy logs and pop it from the stack.
1032 */
1033static int hlua_load(char **args, int section_type, struct proxy *curpx,
1034 struct proxy *defpx, const char *file, int line,
1035 char **err)
1036{
1037 int error;
1038
1039 /* Just load and compile the file. */
1040 error = luaL_loadfile(gL.T, args[1]);
1041 if (error) {
1042 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
1043 lua_pop(gL.T, 1);
1044 return -1;
1045 }
1046
1047 /* If no syntax error where detected, execute the code. */
1048 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
1049 switch (error) {
1050 case LUA_OK:
1051 break;
1052 case LUA_ERRRUN:
1053 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
1054 lua_pop(gL.T, 1);
1055 return -1;
1056 case LUA_ERRMEM:
1057 memprintf(err, "lua out of memory error\n");
1058 return -1;
1059 case LUA_ERRERR:
1060 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
1061 lua_pop(gL.T, 1);
1062 return -1;
1063 case LUA_ERRGCMM:
1064 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
1065 lua_pop(gL.T, 1);
1066 return -1;
1067 default:
1068 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
1069 lua_pop(gL.T, 1);
1070 return -1;
1071 }
1072
1073 return 0;
1074}
1075
1076/* configuration keywords declaration */
1077static struct cfg_kw_list cfg_kws = {{ },{
1078 { CFG_GLOBAL, "lua-load", hlua_load },
1079 { 0, NULL, NULL },
1080}};
1081
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01001082int hlua_post_init()
1083{
1084 struct hlua_init_function *init;
1085 const char *msg;
1086 enum hlua_exec ret;
1087
1088 list_for_each_entry(init, &hlua_init_functions, l) {
1089 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
1090 ret = hlua_ctx_resume(&gL, 0);
1091 switch (ret) {
1092 case HLUA_E_OK:
1093 lua_pop(gL.T, -1);
1094 return 1;
1095 case HLUA_E_AGAIN:
1096 Alert("lua init: yield not allowed.\n");
1097 return 0;
1098 case HLUA_E_ERRMSG:
1099 msg = lua_tostring(gL.T, -1);
1100 Alert("lua init: %s.\n", msg);
1101 return 0;
1102 case HLUA_E_ERR:
1103 default:
1104 Alert("lua init: unknown runtime error.\n");
1105 return 0;
1106 }
1107 }
1108 return 1;
1109}
1110
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01001111void hlua_init(void)
1112{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01001113 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01001114 int idx;
1115 struct sample_fetch *sf;
1116 struct hlua_sample_fetch *hsf;
1117 char *p;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01001118
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001119 /* Initialise com signals pool session. */
1120 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
1121
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01001122 /* Register configuration keywords. */
1123 cfg_register_keywords(&cfg_kws);
1124
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001125 /* Init main lua stack. */
1126 gL.Mref = LUA_REFNIL;
1127 gL.state = HLUA_STOP;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001128 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001129 gL.T = luaL_newstate();
1130 hlua_sethlua(&gL);
1131 gL.Tref = LUA_REFNIL;
1132 gL.task = NULL;
1133
1134 /* Initialise lua. */
1135 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01001136
1137 /*
1138 *
1139 * Create "core" object.
1140 *
1141 */
1142
1143 /* This integer entry is just used as base value for the object "core". */
1144 lua_pushinteger(gL.T, 0);
1145
1146 /* Create and fill the metatable. */
1147 lua_newtable(gL.T);
1148
1149 /* Create and fill the __index entry. */
1150 lua_pushstring(gL.T, "__index");
1151 lua_newtable(gL.T);
1152
1153 /* Push the loglevel constants. */
1154 for (i=0; i<NB_LOG_LEVELS; i++)
1155 hlua_class_const_int(gL.T, log_levels[i], i);
1156
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01001157 /* Register special functions. */
1158 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01001159 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01001160
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01001161 /* Store the table __index in the metable. */
1162 lua_settable(gL.T, -3);
1163
1164 /* Register previous table in the registry with named entry. */
1165 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
1166 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CORE); /* register class session. */
1167
1168 /* Register previous table in the registry with reference. */
1169 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
1170 class_core_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
1171
1172 /* Create new object with class Core. */
1173 lua_setmetatable(gL.T, -2);
1174 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001175
1176 /*
1177 *
1178 * Register class TXN
1179 *
1180 */
1181
1182 /* Create and fill the metatable. */
1183 lua_newtable(gL.T);
1184
1185 /* Create and fille the __index entry. */
1186 lua_pushstring(gL.T, "__index");
1187 lua_newtable(gL.T);
1188
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01001189 /* Browse existing fetches and create the associated
1190 * object method.
1191 */
1192 sf = NULL;
1193 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
1194
1195 /* Dont register the keywork if the arguments check function are
1196 * not safe during the runtime.
1197 */
1198 if ((sf->val_args != NULL) &&
1199 (sf->val_args != val_payload_lv) &&
1200 (sf->val_args != val_hdr))
1201 continue;
1202
1203 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
1204 * by an underscore.
1205 */
1206 strncpy(trash.str, sf->kw, trash.size);
1207 trash.str[trash.size - 1] = '\0';
1208 for (p = trash.str; *p; p++)
1209 if (*p == '.' || *p == '-' || *p == '+')
1210 *p = '_';
1211
1212 /* Register the function. */
1213 lua_pushstring(gL.T, trash.str);
1214 hsf = lua_newuserdata(gL.T, sizeof(struct hlua_sample_fetch));
1215 hsf->f = sf;
1216 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
1217 lua_settable(gL.T, -3);
1218 }
1219
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01001220 /* Register Lua functions. */
1221 hlua_class_function(gL.T, "set_priv", hlua_setpriv);
1222 hlua_class_function(gL.T, "get_priv", hlua_getpriv);
1223
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001224 lua_settable(gL.T, -3);
1225
1226 /* Register previous table in the registry with reference and named entry. */
1227 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
1228 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
1229 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01001230}