1 #include <sys/socket.h>
9 #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
10 #error "Requires Lua 5.3 or later."
15 #include <common/cfgparse.h>
17 #include <types/connection.h>
18 #include <types/hlua.h>
19 #include <types/proxy.h>
21 #include <proto/arg.h>
22 #include <proto/applet.h>
23 #include <proto/channel.h>
24 #include <proto/hdr_idx.h>
25 #include <proto/hlua.h>
26 #include <proto/map.h>
27 #include <proto/obj_type.h>
28 #include <proto/pattern.h>
29 #include <proto/payload.h>
30 #include <proto/proto_http.h>
31 #include <proto/proto_tcp.h>
32 #include <proto/raw_sock.h>
33 #include <proto/sample.h>
34 #include <proto/server.h>
35 #include <proto/session.h>
36 #include <proto/stream.h>
37 #include <proto/ssl_sock.h>
38 #include <proto/stream_interface.h>
39 #include <proto/task.h>
40 #include <proto/vars.h>
42 /* Lua uses longjmp to perform yield or throwing errors. This
43 * macro is used only for identifying the function that can
44 * not return because a longjmp is executed.
45 * __LJMP marks a prototype of hlua file that can use longjmp.
46 * WILL_LJMP() marks an lua function that will use longjmp.
47 * MAY_LJMP() marks an lua function that may use longjmp.
50 #define WILL_LJMP(func) func
51 #define MAY_LJMP(func) func
53 /* The main Lua execution context. */
56 /* This is the memory pool containing all the signal structs. These
57 * struct are used to store each requiered signal between two tasks.
59 struct pool_head *pool2_hlua_com;
61 /* Used for Socket connection. */
62 static struct proxy socket_proxy;
63 static struct server socket_tcp;
65 static struct server socket_ssl;
68 /* List head of the function called at the initialisation time. */
69 struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
71 /* The following variables contains the reference of the different
72 * Lua classes. These references are useful for identify metadata
73 * associated with an object.
75 static int class_txn_ref;
76 static int class_socket_ref;
77 static int class_channel_ref;
78 static int class_fetches_ref;
79 static int class_converters_ref;
80 static int class_http_ref;
81 static int class_map_ref;
83 /* Global Lua execution timeout. By default Lua, execution linked
84 * with stream (actions, sample-fetches and converters) have a
85 * short timeout. Lua linked with tasks doesn't have a timeout
86 * because a task may remain alive during all the haproxy execution.
88 static unsigned int hlua_timeout_session = 4000; /* session timeout. */
89 static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
91 /* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
92 * it is used for preventing infinite loops.
94 * I test the scheer with an infinite loop containing one incrementation
95 * and one test. I run this loop between 10 seconds, I raise a ceil of
96 * 710M loops from one interrupt each 9000 instructions, so I fix the value
97 * to one interrupt each 10 000 instructions.
99 * configured | Number of
100 * instructions | loops executed
101 * between two | in milions
103 * ---------------+---------------
116 static unsigned int hlua_nb_instruction = 10000;
118 /* Descriptor for the memory allocation state. If limit is not null, it will
119 * be enforced on any memory allocation.
121 struct hlua_mem_allocator {
126 static struct hlua_mem_allocator hlua_global_allocator;
128 /* These functions converts types between HAProxy internal args or
129 * sample and LUA types. Another function permits to check if the
130 * LUA stack contains arguments according with an required ARG_T
133 static int hlua_arg2lua(lua_State *L, const struct arg *arg);
134 static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
135 __LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
136 unsigned int mask, struct proxy *p);
137 static int hlua_smp2lua(lua_State *L, struct sample *smp);
138 static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
139 static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
141 /* Used to check an Lua function type in the stack. It creates and
142 * returns a reference of the function. This function throws an
143 * error if the rgument is not a "function".
145 __LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
147 if (!lua_isfunction(L, argno)) {
148 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
149 WILL_LJMP(luaL_argerror(L, argno, msg));
151 lua_pushvalue(L, argno);
152 return luaL_ref(L, LUA_REGISTRYINDEX);
155 /* The three following functions are useful for adding entries
156 * in a table. These functions takes a string and respectively an
157 * integer, a string or a function and add it to the table in the
160 * These functions throws an error if no more stack size is
163 __LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
166 if (!lua_checkstack(L, 2))
167 WILL_LJMP(luaL_error(L, "full stack"));
168 lua_pushstring(L, name);
169 lua_pushinteger(L, value);
172 __LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
175 if (!lua_checkstack(L, 2))
176 WILL_LJMP(luaL_error(L, "full stack"));
177 lua_pushstring(L, name);
178 lua_pushstring(L, value);
181 __LJMP static inline void hlua_class_function(lua_State *L, const char *name,
182 int (*function)(lua_State *L))
184 if (!lua_checkstack(L, 2))
185 WILL_LJMP(luaL_error(L, "full stack"));
186 lua_pushstring(L, name);
187 lua_pushcclosure(L, function, 0);
191 /* This function check the number of arguments available in the
192 * stack. If the number of arguments available is not the same
193 * then <nb> an error is throwed.
195 __LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
197 if (lua_gettop(L) == nb)
199 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
202 /* Return true if the data in stack[<ud>] is an object of
205 static int hlua_metaistype(lua_State *L, int ud, int class_ref)
207 if (!lua_getmetatable(L, ud))
210 lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
211 if (!lua_rawequal(L, -1, -2)) {
220 /* Return an object of the expected type, or throws an error. */
221 __LJMP static void *hlua_checkudata(lua_State *L, int ud, int class_ref)
225 /* Check if the stack entry is an array. */
226 if (!lua_istable(L, ud))
227 WILL_LJMP(luaL_argerror(L, ud, NULL));
228 /* Check if the metadata have the expected type. */
229 if (!hlua_metaistype(L, ud, class_ref))
230 WILL_LJMP(luaL_argerror(L, ud, NULL));
231 /* Push on the stack at the entry [0] of the table. */
232 lua_rawgeti(L, ud, 0);
233 /* Check if this entry is userdata. */
234 p = lua_touserdata(L, -1);
236 WILL_LJMP(luaL_argerror(L, ud, NULL));
237 /* Remove the entry returned by lua_rawgeti(). */
239 /* Return the associated struct. */
243 /* This fucntion push an error string prefixed by the file name
244 * and the line number where the error is encountered.
246 static int hlua_pusherror(lua_State *L, const char *fmt, ...)
251 lua_pushvfstring(L, fmt, argp);
257 /* This function register a new signal. "lua" is the current lua
258 * execution context. It contains a pointer to the associated task.
259 * "link" is a list head attached to an other task that must be wake
260 * the lua task if an event occurs. This is useful with external
261 * events like TCP I/O or sleep functions. This funcion allocate
262 * memory for the signal.
264 static int hlua_com_new(struct hlua *lua, struct list *link)
266 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
269 LIST_ADDQ(&lua->com, &com->purge_me);
270 LIST_ADDQ(link, &com->wake_me);
271 com->task = lua->task;
275 /* This function purge all the pending signals when the LUA execution
276 * is finished. This prevent than a coprocess try to wake a deleted
277 * task. This function remove the memory associated to the signal.
279 static void hlua_com_purge(struct hlua *lua)
281 struct hlua_com *com, *back;
283 /* Delete all pending communication signals. */
284 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
285 LIST_DEL(&com->purge_me);
286 LIST_DEL(&com->wake_me);
287 pool_free2(pool2_hlua_com, com);
291 /* This function sends signals. It wakes all the tasks attached
292 * to a list head, and remove the signal, and free the used
295 static void hlua_com_wake(struct list *wake)
297 struct hlua_com *com, *back;
299 /* Wake task and delete all pending communication signals. */
300 list_for_each_entry_safe(com, back, wake, wake_me) {
301 LIST_DEL(&com->purge_me);
302 LIST_DEL(&com->wake_me);
303 task_wakeup(com->task, TASK_WOKEN_MSG);
304 pool_free2(pool2_hlua_com, com);
308 /* This functions is used with sample fetch and converters. It
309 * converts the HAProxy configuration argument in a lua stack
312 * It takes an array of "arg", and each entry of the array is
313 * converted and pushed in the LUA stack.
315 static int hlua_arg2lua(lua_State *L, const struct arg *arg)
321 lua_pushinteger(L, arg->data.sint);
325 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
345 /* This function take one entrie in an LUA stack at the index "ud",
346 * and try to convert it in an HAProxy argument entry. This is useful
347 * with sample fetch wrappers. The input arguments are gived to the
348 * lua wrapper and converted as arg list by thi function.
350 static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
352 switch (lua_type(L, ud)) {
356 arg->type = ARGT_SINT;
357 arg->data.sint = lua_tointeger(L, ud);
361 arg->type = ARGT_STR;
362 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
370 case LUA_TLIGHTUSERDATA:
371 arg->type = ARGT_SINT;
378 /* the following functions are used to convert a struct sample
379 * in Lua type. This useful to convert the return of the
380 * fetchs or converters.
382 static int hlua_smp2lua(lua_State *L, struct sample *smp)
384 switch (smp->data.type) {
387 lua_pushinteger(L, smp->data.u.sint);
392 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
396 switch (smp->data.u.meth.meth) {
397 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
398 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
399 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
400 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
401 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
402 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
403 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
404 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
405 case HTTP_METH_OTHER:
406 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
416 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
417 if (sample_casts[smp->data.type][SMP_T_STR] &&
418 sample_casts[smp->data.type][SMP_T_STR](smp))
419 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
430 /* the following functions are used to convert a struct sample
431 * in Lua strings. This is useful to convert the return of the
432 * fetchs or converters.
434 static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
436 switch (smp->data.type) {
440 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
444 switch (smp->data.u.meth.meth) {
445 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
446 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
447 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
448 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
449 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
450 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
451 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
452 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
453 case HTTP_METH_OTHER:
454 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
457 lua_pushstring(L, "");
466 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
467 if (sample_casts[smp->data.type][SMP_T_STR] &&
468 sample_casts[smp->data.type][SMP_T_STR](smp))
469 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
471 lua_pushstring(L, "");
474 lua_pushstring(L, "");
480 /* the following functions are used to convert an Lua type in a
481 * struct sample. This is useful to provide data from a converter
484 static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
486 switch (lua_type(L, ud)) {
489 smp->data.type = SMP_T_SINT;
490 smp->data.u.sint = lua_tointeger(L, ud);
495 smp->data.type = SMP_T_BOOL;
496 smp->data.u.sint = lua_toboolean(L, ud);
500 smp->data.type = SMP_T_STR;
501 smp->flags |= SMP_F_CONST;
502 smp->data.u.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.len);
510 case LUA_TLIGHTUSERDATA:
513 smp->data.type = SMP_T_BOOL;
514 smp->data.u.sint = 0;
520 /* This function check the "argp" builded by another conversion function
521 * is in accord with the expected argp defined by the "mask". The fucntion
522 * returns true or false. It can be adjust the types if there compatibles.
524 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
527 __LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
528 unsigned int mask, struct proxy *p)
536 min_arg = ARGM(mask);
541 /* Check oversize. */
542 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
543 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
546 /* Check for mandatory arguments. */
547 if (argp[idx].type == ARGT_STOP) {
550 /* If miss other argument than the first one, we return an error. */
552 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
554 /* If first argument have a certain type, some default values
555 * may be used. See the function smp_resolve_args().
557 switch (mask & ARGT_MASK) {
560 if (!(p->cap & PR_CAP_FE))
561 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
562 argp[idx].data.prx = p;
563 argp[idx].type = ARGT_FE;
564 argp[idx+1].type = ARGT_STOP;
568 if (!(p->cap & PR_CAP_BE))
569 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
570 argp[idx].data.prx = p;
571 argp[idx].type = ARGT_BE;
572 argp[idx+1].type = ARGT_STOP;
576 argp[idx].data.prx = p;
577 argp[idx].type = ARGT_TAB;
578 argp[idx+1].type = ARGT_STOP;
582 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
589 /* Check for exceed the number of requiered argument. */
590 if ((mask & ARGT_MASK) == ARGT_STOP &&
591 argp[idx].type != ARGT_STOP) {
592 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
595 if ((mask & ARGT_MASK) == ARGT_STOP &&
596 argp[idx].type == ARGT_STOP) {
600 /* Convert some argument types. */
601 switch (mask & ARGT_MASK) {
603 if (argp[idx].type != ARGT_SINT)
604 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
605 argp[idx].type = ARGT_SINT;
609 if (argp[idx].type != ARGT_SINT)
610 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
611 argp[idx].type = ARGT_TIME;
615 if (argp[idx].type != ARGT_SINT)
616 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
617 argp[idx].type = ARGT_SIZE;
621 if (argp[idx].type != ARGT_STR)
622 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
623 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
624 trash.str[argp[idx].data.str.len] = 0;
625 argp[idx].data.prx = proxy_fe_by_name(trash.str);
626 if (!argp[idx].data.prx)
627 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
628 argp[idx].type = ARGT_FE;
632 if (argp[idx].type != ARGT_STR)
633 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
634 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
635 trash.str[argp[idx].data.str.len] = 0;
636 argp[idx].data.prx = proxy_be_by_name(trash.str);
637 if (!argp[idx].data.prx)
638 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
639 argp[idx].type = ARGT_BE;
643 if (argp[idx].type != ARGT_STR)
644 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
645 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
646 trash.str[argp[idx].data.str.len] = 0;
647 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
648 if (!argp[idx].data.prx)
649 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
650 argp[idx].type = ARGT_TAB;
654 if (argp[idx].type != ARGT_STR)
655 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
656 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
657 trash.str[argp[idx].data.str.len] = 0;
658 sname = strrchr(trash.str, '/');
662 px = proxy_be_by_name(pname);
664 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
670 argp[idx].data.srv = findserver(px, sname);
671 if (!argp[idx].data.srv)
672 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
673 argp[idx].type = ARGT_SRV;
677 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
678 trash.str[argp[idx].data.str.len] = 0;
679 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
680 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
681 argp[idx].type = ARGT_IPV4;
685 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
686 trash.str[argp[idx].data.str.len] = 0;
687 if (!str2mask(trash.str, &argp[idx].data.ipv4))
688 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
689 argp[idx].type = ARGT_MSK4;
693 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
694 trash.str[argp[idx].data.str.len] = 0;
695 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
696 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
697 argp[idx].type = ARGT_IPV6;
704 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
708 /* Check for type of argument. */
709 if ((mask & ARGT_MASK) != argp[idx].type) {
710 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
711 arg_type_names[(mask & ARGT_MASK)],
712 arg_type_names[argp[idx].type & ARGT_MASK]);
713 WILL_LJMP(luaL_argerror(L, first + idx, msg));
723 * The following functions are used to make correspondance between the the
724 * executed lua pointer and the "struct hlua *" that contain the context.
726 * - hlua_gethlua : return the hlua context associated with an lua_State.
727 * - hlua_sethlua : create the association between hlua context and lua_state.
729 static inline struct hlua *hlua_gethlua(lua_State *L)
731 struct hlua **hlua = lua_getextraspace(L);
734 static inline void hlua_sethlua(struct hlua *hlua)
736 struct hlua **hlua_store = lua_getextraspace(hlua->T);
740 /* This function is used to send logs. It try to send on screen (stderr)
741 * and on the default syslog server.
743 static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
748 /* Cleanup the log message. */
750 for (; *msg != '\0'; msg++, p++) {
751 if (p >= trash.str + trash.size - 1)
760 send_log(px, level, "%s", trash.str);
761 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
762 get_localtime(date.tv_sec, &tm);
763 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
764 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
765 (int)getpid(), trash.str);
770 /* This function just ensure that the yield will be always
771 * returned with a timeout and permit to set some flags
773 __LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
774 lua_KFunction k, int timeout, unsigned int flags)
776 struct hlua *hlua = hlua_gethlua(L);
778 /* Set the wake timeout. If timeout is required, we set
779 * the expiration time.
781 hlua->wake_time = tick_first(timeout, hlua->expire);
783 hlua->flags |= flags;
785 /* Process the yield. */
786 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
789 /* This function initialises the Lua environment stored in the stream.
790 * It must be called at the start of the stream. This function creates
791 * an LUA coroutine. It can not be use to crete the main LUA context.
793 int hlua_ctx_init(struct hlua *lua, struct task *task)
795 lua->Mref = LUA_REFNIL;
797 LIST_INIT(&lua->com);
798 lua->T = lua_newthread(gL.T);
800 lua->Tref = LUA_REFNIL;
804 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
809 /* Used to destroy the Lua coroutine when the attached stream or task
810 * is destroyed. The destroy also the memory context. The struct "lua"
813 void hlua_ctx_destroy(struct hlua *lua)
818 /* Purge all the pending signals. */
821 /* The thread is garbage collected by Lua. */
822 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
823 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
826 /* This function is used to restore the Lua context when a coroutine
827 * fails. This function copy the common memory between old coroutine
828 * and the new coroutine. The old coroutine is destroyed, and its
829 * replaced by the new coroutine.
830 * If the flag "keep_msg" is set, the last entry of the old is assumed
831 * as string error message and it is copied in the new stack.
833 static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
838 /* Renew the main LUA stack doesn't have sense. */
842 /* New Lua coroutine. */
843 T = lua_newthread(gL.T);
847 /* Copy last error message. */
849 lua_xmove(lua->T, T, 1);
851 /* Copy data between the coroutines. */
852 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
853 lua_xmove(lua->T, T, 1);
854 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
856 /* Destroy old data. */
857 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
859 /* The thread is garbage collected by Lua. */
860 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
862 /* Fill the struct with the new coroutine values. */
865 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
873 void hlua_hook(lua_State *L, lua_Debug *ar)
875 struct hlua *hlua = hlua_gethlua(L);
877 /* Lua cannot yield when its returning from a function,
878 * so, we can fix the interrupt hook to 1 instruction,
879 * expecting that the function is finnished.
881 if (lua_gethookmask(L) & LUA_MASKRET) {
882 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
886 /* restore the interrupt condition. */
887 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
889 /* If we interrupt the Lua processing in yieldable state, we yield.
890 * If the state is not yieldable, trying yield causes an error.
892 if (lua_isyieldable(L))
893 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
895 /* If we cannot yield, update the clock and check the timeout. */
896 tv_update_date(0, 1);
897 if (tick_is_expired(hlua->expire, now_ms)) {
898 lua_pushfstring(L, "execution timeout");
899 WILL_LJMP(lua_error(L));
902 /* Try to interrupt the process at the end of the current
903 * unyieldable function.
905 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
908 /* This function start or resumes the Lua stack execution. If the flag
909 * "yield_allowed" if no set and the LUA stack execution returns a yield
910 * The function return an error.
912 * The function can returns 4 values:
913 * - HLUA_E_OK : The execution is terminated without any errors.
914 * - HLUA_E_AGAIN : The execution must continue at the next associated
916 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
917 * the top of the stack.
918 * - HLUA_E_ERR : An error has occured without error message.
920 * If an error occured, the stack is renewed and it is ready to run new
923 static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
930 /* If we want to resume the task, then check first the execution timeout.
931 * if it is reached, we can interrupt the Lua processing.
933 if (tick_is_expired(lua->expire, now_ms))
934 goto timeout_reached;
938 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
939 * instructions. it is used for preventing infinite loops.
941 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
943 /* Remove all flags except the running flags. */
944 lua->flags = HLUA_RUN;
946 /* Call the function. */
947 ret = lua_resume(lua->T, gL.T, lua->nargs);
955 /* Check if the execution timeout is expired. It it is the case, we
956 * break the Lua execution.
958 if (tick_is_expired(lua->expire, now_ms)) {
962 lua_settop(lua->T, 0); /* Empty the stack. */
963 if (!lua_checkstack(lua->T, 1)) {
967 lua_pushfstring(lua->T, "execution timeout");
971 /* Process the forced yield. if the general yield is not allowed or
972 * if no task were associated this the current Lua execution
973 * coroutine, we resume the execution. Else we want to return in the
974 * scheduler and we want to be waked up again, to continue the
975 * current Lua execution. So we schedule our own task.
977 if (HLUA_IS_CTRLYIELDING(lua)) {
978 if (!yield_allowed || !lua->task)
979 goto resume_execution;
980 task_wakeup(lua->task, TASK_WOKEN_MSG);
982 if (!yield_allowed) {
983 lua_settop(lua->T, 0); /* Empty the stack. */
984 if (!lua_checkstack(lua->T, 1)) {
988 lua_pushfstring(lua->T, "yield not allowed");
997 /* Special exit case. The traditionnal exit is returned as an error
998 * because the errors ares the only one mean to return immediately
999 * from and lua execution.
1001 if (lua->flags & HLUA_EXIT) {
1003 hlua_ctx_renew(lua, 0);
1007 lua->wake_time = TICK_ETERNITY;
1008 if (!lua_checkstack(lua->T, 1)) {
1012 msg = lua_tostring(lua->T, -1);
1013 lua_settop(lua->T, 0); /* Empty the stack. */
1016 lua_pushfstring(lua->T, "runtime error: %s", msg);
1018 lua_pushfstring(lua->T, "unknown runtime error");
1019 ret = HLUA_E_ERRMSG;
1023 lua->wake_time = TICK_ETERNITY;
1024 lua_settop(lua->T, 0); /* Empty the stack. */
1025 if (!lua_checkstack(lua->T, 1)) {
1029 lua_pushfstring(lua->T, "out of memory error");
1030 ret = HLUA_E_ERRMSG;
1034 lua->wake_time = TICK_ETERNITY;
1035 if (!lua_checkstack(lua->T, 1)) {
1039 msg = lua_tostring(lua->T, -1);
1040 lua_settop(lua->T, 0); /* Empty the stack. */
1043 lua_pushfstring(lua->T, "message handler error: %s", msg);
1045 lua_pushfstring(lua->T, "message handler error");
1046 ret = HLUA_E_ERRMSG;
1050 lua->wake_time = TICK_ETERNITY;
1051 lua_settop(lua->T, 0); /* Empty the stack. */
1052 if (!lua_checkstack(lua->T, 1)) {
1056 lua_pushfstring(lua->T, "unknonwn error");
1057 ret = HLUA_E_ERRMSG;
1066 hlua_com_purge(lua);
1067 hlua_ctx_renew(lua, 1);
1073 hlua_com_purge(lua);
1074 hlua_ctx_renew(lua, 0);
1079 hlua_com_purge(lua);
1086 /* This function exit the current code. */
1087 __LJMP static int hlua_done(lua_State *L)
1089 struct hlua *hlua = hlua_gethlua(L);
1091 hlua->flags |= HLUA_EXIT;
1092 WILL_LJMP(lua_error(L));
1097 /* This function is an LUA binding. It provides a function
1098 * for deleting ACL from a referenced ACL file.
1100 __LJMP static int hlua_del_acl(lua_State *L)
1104 struct pat_ref *ref;
1106 MAY_LJMP(check_args(L, 2, "del_acl"));
1108 name = MAY_LJMP(luaL_checkstring(L, 1));
1109 key = MAY_LJMP(luaL_checkstring(L, 2));
1111 ref = pat_ref_lookup(name);
1113 WILL_LJMP(luaL_error(L, "'del_acl': unkown acl file '%s'", name));
1115 pat_ref_delete(ref, key);
1119 /* This function is an LUA binding. It provides a function
1120 * for deleting map entry from a referenced map file.
1122 static int hlua_del_map(lua_State *L)
1126 struct pat_ref *ref;
1128 MAY_LJMP(check_args(L, 2, "del_map"));
1130 name = MAY_LJMP(luaL_checkstring(L, 1));
1131 key = MAY_LJMP(luaL_checkstring(L, 2));
1133 ref = pat_ref_lookup(name);
1135 WILL_LJMP(luaL_error(L, "'del_map': unkown acl file '%s'", name));
1137 pat_ref_delete(ref, key);
1141 /* This function is an LUA binding. It provides a function
1142 * for adding ACL pattern from a referenced ACL file.
1144 static int hlua_add_acl(lua_State *L)
1148 struct pat_ref *ref;
1150 MAY_LJMP(check_args(L, 2, "add_acl"));
1152 name = MAY_LJMP(luaL_checkstring(L, 1));
1153 key = MAY_LJMP(luaL_checkstring(L, 2));
1155 ref = pat_ref_lookup(name);
1157 WILL_LJMP(luaL_error(L, "'add_acl': unkown acl file '%s'", name));
1159 if (pat_ref_find_elt(ref, key) == NULL)
1160 pat_ref_add(ref, key, NULL, NULL);
1164 /* This function is an LUA binding. It provides a function
1165 * for setting map pattern and sample from a referenced map
1168 static int hlua_set_map(lua_State *L)
1173 struct pat_ref *ref;
1175 MAY_LJMP(check_args(L, 3, "set_map"));
1177 name = MAY_LJMP(luaL_checkstring(L, 1));
1178 key = MAY_LJMP(luaL_checkstring(L, 2));
1179 value = MAY_LJMP(luaL_checkstring(L, 3));
1181 ref = pat_ref_lookup(name);
1183 WILL_LJMP(luaL_error(L, "'set_map': unkown map file '%s'", name));
1185 if (pat_ref_find_elt(ref, key) != NULL)
1186 pat_ref_set(ref, key, value, NULL);
1188 pat_ref_add(ref, key, value, NULL);
1192 /* A class is a lot of memory that contain data. This data can be a table,
1193 * an integer or user data. This data is associated with a metatable. This
1194 * metatable have an original version registred in the global context with
1195 * the name of the object (_G[<name>] = <metable> ).
1197 * A metable is a table that modify the standard behavior of a standard
1198 * access to the associated data. The entries of this new metatable are
1201 * http://lua-users.org/wiki/MetatableEvents
1205 * we access an absent field in a table, the result is nil. This is
1206 * true, but it is not the whole truth. Actually, such access triggers
1207 * the interpreter to look for an __index metamethod: If there is no
1208 * such method, as usually happens, then the access results in nil;
1209 * otherwise, the metamethod will provide the result.
1211 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1212 * the key does not appear in the table, but the metatable has an __index
1215 * - if the value is a function, the function is called, passing in the
1216 * table and the key; the return value of that function is returned as
1219 * - if the value is another table, the value of the key in that table is
1220 * asked for and returned (and if it doesn't exist in that table, but that
1221 * table's metatable has an __index property, then it continues on up)
1223 * - Use "rawget(myTable,key)" to skip this metamethod.
1225 * http://www.lua.org/pil/13.4.1.html
1229 * Like __index, but control property assignment.
1231 * __mode - Control weak references. A string value with one or both
1232 * of the characters 'k' and 'v' which specifies that the the
1233 * keys and/or values in the table are weak references.
1235 * __call - Treat a table like a function. When a table is followed by
1236 * parenthesis such as "myTable( 'foo' )" and the metatable has
1237 * a __call key pointing to a function, that function is invoked
1238 * (passing any specified arguments) and the return value is
1241 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1242 * called, if the metatable for myTable has a __metatable
1243 * key, the value of that key is returned instead of the
1246 * __tostring - Control string representation. When the builtin
1247 * "tostring( myTable )" function is called, if the metatable
1248 * for myTable has a __tostring property set to a function,
1249 * that function is invoked (passing myTable to it) and the
1250 * return value is used as the string representation.
1252 * __len - Control table length. When the table length is requested using
1253 * the length operator ( '#' ), if the metatable for myTable has
1254 * a __len key pointing to a function, that function is invoked
1255 * (passing myTable to it) and the return value used as the value
1258 * __gc - Userdata finalizer code. When userdata is set to be garbage
1259 * collected, if the metatable has a __gc field pointing to a
1260 * function, that function is first invoked, passing the userdata
1261 * to it. The __gc metamethod is not called for tables.
1262 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1264 * Special metamethods for redefining standard operators:
1265 * http://www.lua.org/pil/13.1.html
1275 * Special methods for redfining standar relations
1276 * http://www.lua.org/pil/13.2.html
1291 /* Returns a struct hlua_map if the stack entry "ud" is
1292 * a class session, otherwise it throws an error.
1294 __LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1296 return (struct map_descriptor *)MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
1299 /* This function is the map constructor. It don't need
1300 * the class Map object. It creates and return a new Map
1301 * object. It must be called only during "body" or "init"
1302 * context because it process some filesystem accesses.
1304 __LJMP static int hlua_map_new(struct lua_State *L)
1307 int match = PAT_MATCH_STR;
1308 struct sample_conv conv;
1309 const char *file = "";
1315 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1316 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1318 fn = MAY_LJMP(luaL_checkstring(L, 1));
1320 if (lua_gettop(L) >= 2) {
1321 match = MAY_LJMP(luaL_checkinteger(L, 2));
1322 if (match < 0 || match >= PAT_MATCH_NUM)
1323 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1326 /* Get Lua filename and line number. */
1327 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1328 lua_getinfo(L, "Sl", &ar); /* get info about it */
1329 if (ar.currentline > 0) { /* is there info? */
1330 file = ar.short_src;
1331 line = ar.currentline;
1335 /* fill fake sample_conv struct. */
1336 conv.kw = ""; /* unused. */
1337 conv.process = NULL; /* unused. */
1338 conv.arg_mask = 0; /* unused. */
1339 conv.val_args = NULL; /* unused. */
1340 conv.out_type = SMP_T_STR;
1341 conv.private = (void *)(long)match;
1343 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1344 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1345 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1346 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1347 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1348 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1349 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
1350 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
1351 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1353 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1356 /* fill fake args. */
1357 args[0].type = ARGT_STR;
1358 args[0].data.str.str = (char *)fn;
1359 args[1].type = ARGT_STOP;
1362 if (!sample_load_map(args, &conv, file, line, &err)) {
1363 /* error case: we cant use luaL_error because we must
1364 * free the err variable.
1367 lua_pushfstring(L, "'new': %s.", err);
1370 WILL_LJMP(lua_error(L));
1373 /* create the lua object. */
1375 lua_pushlightuserdata(L, args[0].data.map);
1376 lua_rawseti(L, -2, 0);
1378 /* Pop a class Map metatable and affect it to the userdata. */
1379 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1380 lua_setmetatable(L, -2);
1386 __LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1388 struct map_descriptor *desc;
1389 struct pattern *pat;
1392 MAY_LJMP(check_args(L, 2, "lookup"));
1393 desc = MAY_LJMP(hlua_checkmap(L, 1));
1394 if (desc->pat.expect_type == SMP_T_SINT) {
1395 smp.data.type = SMP_T_SINT;
1396 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
1399 smp.data.type = SMP_T_STR;
1400 smp.flags = SMP_F_CONST;
1401 smp.data.u.str.str = (char *)MAY_LJMP(luaL_checklstring(L, 2, (size_t *)&smp.data.u.str.len));
1404 pat = pattern_exec_match(&desc->pat, &smp, 1);
1405 if (!pat || !pat->data) {
1407 lua_pushstring(L, "");
1413 /* The Lua pattern must return a string, so we can't check the returned type */
1414 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
1418 __LJMP static int hlua_map_lookup(struct lua_State *L)
1420 return _hlua_map_lookup(L, 0);
1423 __LJMP static int hlua_map_slookup(struct lua_State *L)
1425 return _hlua_map_lookup(L, 1);
1436 __LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1438 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1441 /* This function is the handler called for each I/O on the established
1442 * connection. It is used for notify space avalaible to send or data
1445 static void hlua_socket_handler(struct appctx *appctx)
1447 struct stream_interface *si = appctx->owner;
1448 struct connection *c = objt_conn(si_opposite(si)->end);
1450 /* Wakeup the main stream if the client connection is closed. */
1451 if (!c || channel_output_closed(si_ic(si)) || channel_input_closed(si_oc(si))) {
1452 if (appctx->ctx.hlua.socket) {
1453 appctx->ctx.hlua.socket->s = NULL;
1454 appctx->ctx.hlua.socket = NULL;
1458 si_ic(si)->flags |= CF_READ_NULL;
1459 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1460 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1464 /* if the connection is not estabkished, inform the stream that we want
1465 * to be notified whenever the connection completes.
1467 if (!(c->flags & CO_FL_CONNECTED)) {
1468 si_applet_cant_get(si);
1469 si_applet_cant_put(si);
1473 /* This function is called after the connect. */
1474 appctx->ctx.hlua.connected = 1;
1476 /* Wake the tasks which wants to write if the buffer have avalaible space. */
1477 if (channel_may_recv(si_oc(si)))
1478 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1480 /* Wake the tasks which wants to read if the buffer contains data. */
1481 if (channel_is_empty(si_ic(si)))
1482 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1485 /* This function is called when the "struct stream" is destroyed.
1486 * Remove the link from the object to this stream.
1487 * Wake all the pending signals.
1489 static void hlua_socket_release(struct appctx *appctx)
1491 /* Remove my link in the original object. */
1492 if (appctx->ctx.hlua.socket)
1493 appctx->ctx.hlua.socket->s = NULL;
1495 /* Wake all the task waiting for me. */
1496 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1497 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1500 /* If the garbage collectio of the object is launch, nobody
1501 * uses this object. If the stream does not exists, just quit.
1502 * Send the shutdown signal to the stream. In some cases,
1503 * pending signal can rest in the read and write lists. destroy
1506 __LJMP static int hlua_socket_gc(lua_State *L)
1508 struct hlua_socket *socket;
1509 struct appctx *appctx;
1511 MAY_LJMP(check_args(L, 1, "__gc"));
1513 socket = MAY_LJMP(hlua_checksocket(L, 1));
1517 /* Remove all reference between the Lua stack and the coroutine stream. */
1518 appctx = objt_appctx(socket->s->si[0].end);
1519 stream_shutdown(socket->s, SF_ERR_KILLED);
1521 appctx->ctx.hlua.socket = NULL;
1526 /* The close function send shutdown signal and break the
1527 * links between the stream and the object.
1529 __LJMP static int hlua_socket_close(lua_State *L)
1531 struct hlua_socket *socket;
1532 struct appctx *appctx;
1534 MAY_LJMP(check_args(L, 1, "close"));
1536 socket = MAY_LJMP(hlua_checksocket(L, 1));
1540 /* Close the stream and remove the associated stop task. */
1541 stream_shutdown(socket->s, SF_ERR_KILLED);
1542 appctx = objt_appctx(socket->s->si[0].end);
1543 appctx->ctx.hlua.socket = NULL;
1549 /* This Lua function assumes that the stack contain three parameters.
1550 * 1 - USERDATA containing a struct socket
1551 * 2 - INTEGER with values of the macro defined below
1552 * If the integer is -1, we must read at most one line.
1553 * If the integer is -2, we ust read all the data until the
1554 * end of the stream.
1555 * If the integer is positive value, we must read a number of
1556 * bytes corresponding to this value.
1558 #define HLSR_READ_LINE (-1)
1559 #define HLSR_READ_ALL (-2)
1560 __LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
1562 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1563 int wanted = lua_tointeger(L, 2);
1564 struct hlua *hlua = hlua_gethlua(L);
1565 struct appctx *appctx;
1572 int skip_at_end = 0;
1575 /* Check if this lua stack is schedulable. */
1576 if (!hlua || !hlua->task)
1577 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1578 "'frontend', 'backend' or 'task'"));
1580 /* check for connection closed. If some data where read, return it. */
1582 goto connection_closed;
1584 oc = &socket->s->res;
1585 if (wanted == HLSR_READ_LINE) {
1587 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
1588 if (nblk < 0) /* Connection close. */
1589 goto connection_closed;
1590 if (nblk == 0) /* No data avalaible. */
1591 goto connection_empty;
1593 /* remove final \r\n. */
1595 if (blk1[len1-1] == '\n') {
1598 if (blk1[len1-1] == '\r') {
1605 if (blk2[len2-1] == '\n') {
1608 if (blk2[len2-1] == '\r') {
1616 else if (wanted == HLSR_READ_ALL) {
1617 /* Read all the available data. */
1618 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
1619 if (nblk < 0) /* Connection close. */
1620 goto connection_closed;
1621 if (nblk == 0) /* No data avalaible. */
1622 goto connection_empty;
1626 /* Read a block of data. */
1627 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
1628 if (nblk < 0) /* Connection close. */
1629 goto connection_closed;
1630 if (nblk == 0) /* No data avalaible. */
1631 goto connection_empty;
1633 if (len1 > wanted) {
1636 } if (nblk == 2 && len1 + len2 > wanted)
1637 len2 = wanted - len1;
1642 luaL_addlstring(&socket->b, blk1, len1);
1645 luaL_addlstring(&socket->b, blk2, len2);
1649 bo_skip(oc, len + skip_at_end);
1651 /* Don't wait anything. */
1652 si_applet_done(&socket->s->si[0]);
1654 /* If the pattern reclaim to read all the data
1655 * in the connection, got out.
1657 if (wanted == HLSR_READ_ALL)
1658 goto connection_empty;
1659 else if (wanted >= 0 && len < wanted)
1660 goto connection_empty;
1662 /* Return result. */
1663 luaL_pushresult(&socket->b);
1668 /* If the buffer containds data. */
1669 if (socket->b.n > 0) {
1670 luaL_pushresult(&socket->b);
1674 lua_pushstring(L, "connection closed.");
1679 appctx = objt_appctx(socket->s->si[0].end);
1680 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1681 WILL_LJMP(luaL_error(L, "out of memory"));
1682 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
1686 /* This Lus function gets two parameters. The first one can be string
1687 * or a number. If the string is "*l", the user require one line. If
1688 * the string is "*a", the user require all the content of the stream.
1689 * If the value is a number, the user require a number of bytes equal
1690 * to the value. The default value is "*l" (a line).
1692 * This paraeter with a variable type is converted in integer. This
1693 * integer takes this values:
1695 * -2 : read all the stream
1696 * >0 : amount if bytes.
1698 * The second parameter is optinal. It contains a string that must be
1699 * concatenated with the read data.
1701 __LJMP static int hlua_socket_receive(struct lua_State *L)
1703 int wanted = HLSR_READ_LINE;
1704 const char *pattern;
1708 struct hlua_socket *socket;
1710 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1711 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1713 socket = MAY_LJMP(hlua_checksocket(L, 1));
1715 /* check for pattern. */
1716 if (lua_gettop(L) >= 2) {
1717 type = lua_type(L, 2);
1718 if (type == LUA_TSTRING) {
1719 pattern = lua_tostring(L, 2);
1720 if (strcmp(pattern, "*a") == 0)
1721 wanted = HLSR_READ_ALL;
1722 else if (strcmp(pattern, "*l") == 0)
1723 wanted = HLSR_READ_LINE;
1725 wanted = strtoll(pattern, &error, 10);
1727 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1730 else if (type == LUA_TNUMBER) {
1731 wanted = lua_tointeger(L, 2);
1733 WILL_LJMP(luaL_error(L, "Unsupported size."));
1738 lua_pushinteger(L, wanted);
1741 /* init bufffer, and fiil it wih prefix. */
1742 luaL_buffinit(L, &socket->b);
1745 if (lua_gettop(L) >= 3) {
1746 if (lua_type(L, 3) != LUA_TSTRING)
1747 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1748 pattern = lua_tolstring(L, 3, &len);
1749 luaL_addlstring(&socket->b, pattern, len);
1752 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
1755 /* Write the Lua input string in the output buffer.
1756 * This fucntion returns a yield if no space are available.
1758 static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
1760 struct hlua_socket *socket;
1761 struct hlua *hlua = hlua_gethlua(L);
1762 struct appctx *appctx;
1769 /* Check if this lua stack is schedulable. */
1770 if (!hlua || !hlua->task)
1771 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1772 "'frontend', 'backend' or 'task'"));
1775 socket = MAY_LJMP(hlua_checksocket(L, 1));
1776 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1777 sent = MAY_LJMP(luaL_checkinteger(L, 3));
1779 /* Check for connection close. */
1780 if (!socket->s || channel_output_closed(&socket->s->req)) {
1781 lua_pushinteger(L, -1);
1785 /* Update the input buffer data. */
1787 send_len = buf_len - sent;
1789 /* All the data are sent. */
1790 if (sent >= buf_len)
1791 return 1; /* Implicitly return the length sent. */
1793 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1794 * the request buffer if its not required.
1796 if (socket->s->req.buf->size == 0) {
1797 if (!stream_alloc_recv_buffer(&socket->s->req)) {
1798 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
1799 goto hlua_socket_write_yield_return;
1803 /* Check for avalaible space. */
1804 len = buffer_total_space(socket->s->req.buf);
1806 goto hlua_socket_write_yield_return;
1811 len = bi_putblk(&socket->s->req, buf+sent, send_len);
1813 /* "Not enough space" (-1), "Buffer too little to contain
1814 * the data" (-2) are not expected because the available length
1816 * Other unknown error are also not expected.
1820 socket->s->req.flags |= CF_WAKE_WRITE;
1822 MAY_LJMP(hlua_socket_close(L));
1824 lua_pushinteger(L, -1);
1828 /* update buffers. */
1829 si_applet_done(&socket->s->si[0]);
1830 socket->s->req.rex = TICK_ETERNITY;
1831 socket->s->res.wex = TICK_ETERNITY;
1833 /* Update length sent. */
1835 lua_pushinteger(L, sent + len);
1837 /* All the data buffer is sent ? */
1838 if (sent + len >= buf_len)
1841 hlua_socket_write_yield_return:
1842 appctx = objt_appctx(socket->s->si[0].end);
1843 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1844 WILL_LJMP(luaL_error(L, "out of memory"));
1845 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
1849 /* This function initiate the send of data. It just check the input
1850 * parameters and push an integer in the Lua stack that contain the
1851 * amount of data writed in the buffer. This is used by the function
1852 * "hlua_socket_write_yield" that can yield.
1854 * The Lua function gets between 3 and 4 parameters. The first one is
1855 * the associated object. The second is a string buffer. The third is
1856 * a facultative integer that represents where is the buffer position
1857 * of the start of the data that can send. The first byte is the
1858 * position "1". The default value is "1". The fourth argument is a
1859 * facultative integer that represents where is the buffer position
1860 * of the end of the data that can send. The default is the last byte.
1862 static int hlua_socket_send(struct lua_State *L)
1869 /* Check number of arguments. */
1870 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1871 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1873 /* Get the string. */
1874 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1876 /* Get and check j. */
1877 if (lua_gettop(L) == 4) {
1878 j = MAY_LJMP(luaL_checkinteger(L, 4));
1880 j = buf_len + j + 1;
1888 /* Get and check i. */
1889 if (lua_gettop(L) == 3) {
1890 i = MAY_LJMP(luaL_checkinteger(L, 3));
1892 i = buf_len + i + 1;
1899 /* Check bth i and j. */
1901 lua_pushinteger(L, 0);
1904 if (i == 0 && j == 0) {
1905 lua_pushinteger(L, 0);
1913 /* Pop the string. */
1916 /* Update the buffer length. */
1918 buf_len = j - i + 1;
1919 lua_pushlstring(L, buf, buf_len);
1921 /* This unsigned is used to remember the amount of sent data. */
1922 lua_pushinteger(L, 0);
1924 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
1927 #define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
1928 __LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
1930 static char buffer[SOCKET_INFO_MAX_LEN];
1935 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
1941 if (ret == AF_UNIX) {
1942 lua_pushstring(L, buffer+1);
1945 else if (ret == AF_INET6) {
1947 len = strlen(buffer);
1954 else if (ret == AF_INET) {
1965 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
1970 lua_pushstring(L, p);
1974 /* Returns information about the peer of the connection. */
1975 __LJMP static int hlua_socket_getpeername(struct lua_State *L)
1977 struct hlua_socket *socket;
1978 struct connection *conn;
1980 MAY_LJMP(check_args(L, 1, "getpeername"));
1982 socket = MAY_LJMP(hlua_checksocket(L, 1));
1984 /* Check if the tcp object is avalaible. */
1990 conn = objt_conn(socket->s->si[1].end);
1996 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
1997 unsigned int salen = sizeof(conn->addr.to);
1998 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
2002 conn->flags |= CO_FL_ADDR_TO_SET;
2005 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2008 /* Returns information about my connection side. */
2009 static int hlua_socket_getsockname(struct lua_State *L)
2011 struct hlua_socket *socket;
2012 struct connection *conn;
2014 MAY_LJMP(check_args(L, 1, "getsockname"));
2016 socket = MAY_LJMP(hlua_checksocket(L, 1));
2018 /* Check if the tcp object is avalaible. */
2024 conn = objt_conn(socket->s->si[1].end);
2030 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
2031 unsigned int salen = sizeof(conn->addr.from);
2032 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
2036 conn->flags |= CO_FL_ADDR_FROM_SET;
2039 return hlua_socket_info(L, &conn->addr.from);
2042 /* This struct define the applet. */
2043 static struct applet update_applet = {
2044 .obj_type = OBJ_TYPE_APPLET,
2045 .name = "<LUA_TCP>",
2046 .fct = hlua_socket_handler,
2047 .release = hlua_socket_release,
2050 __LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
2052 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2053 struct hlua *hlua = hlua_gethlua(L);
2054 struct appctx *appctx;
2056 /* Check for connection close. */
2057 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
2059 lua_pushstring(L, "Can't connect");
2063 appctx = objt_appctx(socket->s->si[0].end);
2065 /* Check for connection established. */
2066 if (appctx->ctx.hlua.connected) {
2067 lua_pushinteger(L, 1);
2071 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2072 WILL_LJMP(luaL_error(L, "out of memory error"));
2073 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
2077 /* This function fail or initite the connection. */
2078 __LJMP static int hlua_socket_connect(struct lua_State *L)
2080 struct hlua_socket *socket;
2083 struct connection *conn;
2085 struct appctx *appctx;
2087 MAY_LJMP(check_args(L, 3, "connect"));
2090 socket = MAY_LJMP(hlua_checksocket(L, 1));
2091 ip = MAY_LJMP(luaL_checkstring(L, 2));
2092 port = MAY_LJMP(luaL_checkinteger(L, 3));
2094 conn = si_alloc_conn(&socket->s->si[1]);
2096 WILL_LJMP(luaL_error(L, "connect: internal error"));
2098 /* Parse ip address. */
2099 conn->addr.to.ss_family = AF_UNSPEC;
2100 if (!str2ip2(ip, &conn->addr.to, 0))
2101 WILL_LJMP(luaL_error(L, "connect: cannot parse ip address '%s'", ip));
2104 if (conn->addr.to.ss_family == AF_INET)
2105 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2106 else if (conn->addr.to.ss_family == AF_INET6)
2107 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2109 /* it is important not to call the wakeup function directly but to
2110 * pass through task_wakeup(), because this one knows how to apply
2111 * priorities to tasks.
2113 task_wakeup(socket->s->task, TASK_WOKEN_INIT);
2115 hlua = hlua_gethlua(L);
2116 appctx = objt_appctx(socket->s->si[0].end);
2118 /* inform the stream that we want to be notified whenever the
2119 * connection completes.
2121 si_applet_cant_get(&socket->s->si[0]);
2122 si_applet_cant_put(&socket->s->si[0]);
2124 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2125 WILL_LJMP(luaL_error(L, "out of memory"));
2126 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
2132 __LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2134 struct hlua_socket *socket;
2136 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2137 socket = MAY_LJMP(hlua_checksocket(L, 1));
2138 socket->s->target = &socket_ssl.obj_type;
2139 return MAY_LJMP(hlua_socket_connect(L));
2143 __LJMP static int hlua_socket_setoption(struct lua_State *L)
2148 __LJMP static int hlua_socket_settimeout(struct lua_State *L)
2150 struct hlua_socket *socket;
2153 MAY_LJMP(check_args(L, 2, "settimeout"));
2155 socket = MAY_LJMP(hlua_checksocket(L, 1));
2156 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
2158 socket->s->req.rto = tmout;
2159 socket->s->req.wto = tmout;
2160 socket->s->res.rto = tmout;
2161 socket->s->res.wto = tmout;
2166 __LJMP static int hlua_socket_new(lua_State *L)
2168 struct hlua_socket *socket;
2169 struct appctx *appctx;
2170 struct session *sess;
2171 struct stream *strm;
2174 /* Check stack size. */
2175 if (!lua_checkstack(L, 3)) {
2176 hlua_pusherror(L, "socket: full stack");
2180 /* Create the object: obj[0] = userdata. */
2182 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
2183 lua_rawseti(L, -2, 0);
2184 memset(socket, 0, sizeof(*socket));
2186 /* Check if the various memory pools are intialized. */
2187 if (!pool2_stream || !pool2_buffer) {
2188 hlua_pusherror(L, "socket: uninitialized pools.");
2192 /* Pop a class stream metatable and affect it to the userdata. */
2193 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2194 lua_setmetatable(L, -2);
2196 /* Create the applet context */
2197 appctx = appctx_new(&update_applet);
2199 hlua_pusherror(L, "socket: out of memory");
2203 appctx->ctx.hlua.socket = socket;
2204 appctx->ctx.hlua.connected = 0;
2205 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2206 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
2208 /* Now create a session, task and stream for this applet */
2209 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2211 hlua_pusherror(L, "socket: out of memory");
2217 hlua_pusherror(L, "socket: out of memory");
2222 strm = stream_new(sess, task, &appctx->obj_type);
2224 hlua_pusherror(L, "socket: out of memory");
2225 goto out_fail_stream;
2228 /* Configure an empty Lua for the stream. */
2230 strm->hlua.T = NULL;
2231 strm->hlua.Tref = LUA_REFNIL;
2232 strm->hlua.Mref = LUA_REFNIL;
2233 strm->hlua.nargs = 0;
2234 strm->hlua.flags = 0;
2235 LIST_INIT(&strm->hlua.com);
2237 /* Configure "right" stream interface. this "si" is used to connect
2238 * and retrieve data from the server. The connection is initialized
2239 * with the "struct server".
2241 si_set_state(&strm->si[1], SI_ST_ASS);
2243 /* Force destination server. */
2244 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2245 strm->target = &socket_tcp.obj_type;
2247 /* Update statistics counters. */
2248 socket_proxy.feconn++; /* beconn will be increased later */
2252 /* Return yield waiting for connection. */
2260 appctx_free(appctx);
2262 WILL_LJMP(lua_error(L));
2274 /* Returns the struct hlua_channel join to the class channel in the
2275 * stack entry "ud" or throws an argument error.
2277 __LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
2279 return (struct channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
2282 /* Pushes the channel onto the top of the stack. If the stask does not have a
2283 * free slots, the function fails and returns 0;
2285 static int hlua_channel_new(lua_State *L, struct channel *channel)
2287 /* Check stack size. */
2288 if (!lua_checkstack(L, 3))
2292 lua_pushlightuserdata(L, channel);
2293 lua_rawseti(L, -2, 0);
2295 /* Pop a class sesison metatable and affect it to the userdata. */
2296 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2297 lua_setmetatable(L, -2);
2301 /* Duplicate all the data present in the input channel and put it
2302 * in a string LUA variables. Returns -1 and push a nil value in
2303 * the stack if the channel is closed and all the data are consumed,
2304 * returns 0 if no data are available, otherwise it returns the length
2305 * of the builded string.
2307 static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
2316 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
2317 if (unlikely(ret == 0))
2320 if (unlikely(ret < 0)) {
2325 luaL_buffinit(L, &b);
2326 luaL_addlstring(&b, blk1, len1);
2327 if (unlikely(ret == 2))
2328 luaL_addlstring(&b, blk2, len2);
2329 luaL_pushresult(&b);
2331 if (unlikely(ret == 2))
2336 /* "_hlua_channel_dup" wrapper. If no data are available, it returns
2337 * a yield. This function keep the data in the buffer.
2339 __LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
2341 struct channel *chn;
2343 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2345 if (_hlua_channel_dup(chn, L) == 0)
2346 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
2350 /* Check arguments for the function "hlua_channel_dup_yield". */
2351 __LJMP static int hlua_channel_dup(lua_State *L)
2353 MAY_LJMP(check_args(L, 1, "dup"));
2354 MAY_LJMP(hlua_checkchannel(L, 1));
2355 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2358 /* "_hlua_channel_dup" wrapper. If no data are available, it returns
2359 * a yield. This function consumes the data in the buffer. It returns
2360 * a string containing the data or a nil pointer if no data are available
2361 * and the channel is closed.
2363 __LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
2365 struct channel *chn;
2368 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2370 ret = _hlua_channel_dup(chn, L);
2371 if (unlikely(ret == 0))
2372 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
2374 if (unlikely(ret == -1))
2381 /* Check arguments for the fucntion "hlua_channel_get_yield". */
2382 __LJMP static int hlua_channel_get(lua_State *L)
2384 MAY_LJMP(check_args(L, 1, "get"));
2385 MAY_LJMP(hlua_checkchannel(L, 1));
2386 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2389 /* This functions consumes and returns one line. If the channel is closed,
2390 * and the last data does not contains a final '\n', the data are returned
2391 * without the final '\n'. When no more data are avalaible, it returns nil
2394 __LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
2401 struct channel *chn;
2405 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2407 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
2409 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
2416 luaL_buffinit(L, &b);
2417 luaL_addlstring(&b, blk1, len1);
2419 if (unlikely(ret == 2)) {
2420 luaL_addlstring(&b, blk2, len2);
2423 luaL_pushresult(&b);
2424 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
2428 /* Check arguments for the fucntion "hlua_channel_getline_yield". */
2429 __LJMP static int hlua_channel_getline(lua_State *L)
2431 MAY_LJMP(check_args(L, 1, "getline"));
2432 MAY_LJMP(hlua_checkchannel(L, 1));
2433 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2436 /* This function takes a string as input, and append it at the
2437 * input side of channel. If the data is too big, but a space
2438 * is probably available after sending some data, the function
2439 * yield. If the data is bigger than the buffer, or if the
2440 * channel is closed, it returns -1. otherwise, it returns the
2441 * amount of data writed.
2443 __LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
2445 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
2447 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2448 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2452 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2456 ret = bi_putblk(chn, str + l, max);
2457 if (ret == -2 || ret == -3) {
2458 lua_pushinteger(L, -1);
2462 chn->flags |= CF_WAKE_WRITE;
2463 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
2467 lua_pushinteger(L, l);
2469 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2470 if (max == 0 && chn->buf->o == 0) {
2471 /* There are no space avalaible, and the output buffer is empty.
2472 * in this case, we cannot add more data, so we cannot yield,
2473 * we return the amount of copyied data.
2478 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
2482 /* just a wrapper of "hlua_channel_append_yield". It returns the length
2483 * of the writed string, or -1 if the channel is closed or if the
2484 * buffer size is too little for the data.
2486 __LJMP static int hlua_channel_append(lua_State *L)
2490 MAY_LJMP(check_args(L, 2, "append"));
2491 MAY_LJMP(hlua_checkchannel(L, 1));
2492 MAY_LJMP(luaL_checklstring(L, 2, &len));
2493 MAY_LJMP(luaL_checkinteger(L, 3));
2494 lua_pushinteger(L, 0);
2496 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
2499 /* just a wrapper of "hlua_channel_append_yield". This wrapper starts
2500 * his process by cleaning the buffer. The result is a replacement
2501 * of the current data. It returns the length of the writed string,
2502 * or -1 if the channel is closed or if the buffer size is too
2503 * little for the data.
2505 __LJMP static int hlua_channel_set(lua_State *L)
2507 struct channel *chn;
2509 MAY_LJMP(check_args(L, 2, "set"));
2510 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2511 lua_pushinteger(L, 0);
2515 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
2518 /* Append data in the output side of the buffer. This data is immediatly
2519 * sent. The fcuntion returns the ammount of data writed. If the buffer
2520 * cannot contains the data, the function yield. The function returns -1
2521 * if the channel is closed.
2523 __LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
2525 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
2527 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2528 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2530 struct hlua *hlua = hlua_gethlua(L);
2532 if (unlikely(channel_output_closed(chn))) {
2533 lua_pushinteger(L, -1);
2537 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2538 * the request buffer if its not required.
2540 if (chn->buf->size == 0) {
2541 if (!stream_alloc_recv_buffer(chn)) {
2542 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
2543 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
2547 /* the writed data will be immediatly sent, so we can check
2548 * the avalaible space without taking in account the reserve.
2549 * The reserve is guaranted for the processing of incoming
2550 * data, because the buffer will be flushed.
2552 max = chn->buf->size - buffer_len(chn->buf);
2554 /* If there are no space avalaible, and the output buffer is empty.
2555 * in this case, we cannot add more data, so we cannot yield,
2556 * we return the amount of copyied data.
2558 if (max == 0 && chn->buf->o == 0)
2561 /* Adjust the real required length. */
2565 /* The buffer avalaible size may be not contiguous. This test
2566 * detects a non contiguous buffer and realign it.
2568 if (bi_space_for_replace(chn->buf) < max)
2569 buffer_slow_realign(chn->buf);
2571 /* Copy input data in the buffer. */
2572 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
2574 /* buffer replace considers that the input part is filled.
2575 * so, I must forward these new data in the output part.
2577 b_adv(chn->buf, max);
2581 lua_pushinteger(L, l);
2583 /* If there are no space avalaible, and the output buffer is empty.
2584 * in this case, we cannot add more data, so we cannot yield,
2585 * we return the amount of copyied data.
2587 max = chn->buf->size - buffer_len(chn->buf);
2588 if (max == 0 && chn->buf->o == 0)
2592 /* If we are waiting for space in the response buffer, we
2593 * must set the flag WAKERESWR. This flag required the task
2594 * wake up if any activity is detected on the response buffer.
2596 if (chn->flags & CF_ISRESP)
2597 HLUA_SET_WAKERESWR(hlua);
2599 HLUA_SET_WAKEREQWR(hlua);
2600 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
2606 /* Just a wraper of "_hlua_channel_send". This wrapper permits
2607 * yield the LUA process, and resume it without checking the
2610 __LJMP static int hlua_channel_send(lua_State *L)
2612 MAY_LJMP(check_args(L, 2, "send"));
2613 lua_pushinteger(L, 0);
2615 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
2618 /* This function forward and amount of butes. The data pass from
2619 * the input side of the buffer to the output side, and can be
2620 * forwarded. This function never fails.
2622 * The Lua function takes an amount of bytes to be forwarded in
2623 * imput. It returns the number of bytes forwarded.
2625 __LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
2627 struct channel *chn;
2631 struct hlua *hlua = hlua_gethlua(L);
2633 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2634 len = MAY_LJMP(luaL_checkinteger(L, 2));
2635 l = MAY_LJMP(luaL_checkinteger(L, -1));
2638 if (max > chn->buf->i)
2640 channel_forward(chn, max);
2644 lua_pushinteger(L, l);
2646 /* Check if it miss bytes to forward. */
2648 /* The the input channel or the output channel are closed, we
2649 * must return the amount of data forwarded.
2651 if (channel_input_closed(chn) || channel_output_closed(chn))
2654 /* If we are waiting for space data in the response buffer, we
2655 * must set the flag WAKERESWR. This flag required the task
2656 * wake up if any activity is detected on the response buffer.
2658 if (chn->flags & CF_ISRESP)
2659 HLUA_SET_WAKERESWR(hlua);
2661 HLUA_SET_WAKEREQWR(hlua);
2663 /* Otherwise, we can yield waiting for new data in the inpout side. */
2664 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
2670 /* Just check the input and prepare the stack for the previous
2671 * function "hlua_channel_forward_yield"
2673 __LJMP static int hlua_channel_forward(lua_State *L)
2675 MAY_LJMP(check_args(L, 2, "forward"));
2676 MAY_LJMP(hlua_checkchannel(L, 1));
2677 MAY_LJMP(luaL_checkinteger(L, 2));
2679 lua_pushinteger(L, 0);
2680 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
2683 /* Just returns the number of bytes available in the input
2684 * side of the buffer. This function never fails.
2686 __LJMP static int hlua_channel_get_in_len(lua_State *L)
2688 struct channel *chn;
2690 MAY_LJMP(check_args(L, 1, "get_in_len"));
2691 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2692 lua_pushinteger(L, chn->buf->i);
2696 /* Just returns the number of bytes available in the output
2697 * side of the buffer. This function never fails.
2699 __LJMP static int hlua_channel_get_out_len(lua_State *L)
2701 struct channel *chn;
2703 MAY_LJMP(check_args(L, 1, "get_out_len"));
2704 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2705 lua_pushinteger(L, chn->buf->o);
2717 /* Returns a struct hlua_session if the stack entry "ud" is
2718 * a class stream, otherwise it throws an error.
2720 __LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
2722 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
2725 /* This function creates and push in the stack a fetch object according
2726 * with a current TXN.
2728 static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
2730 struct hlua_smp *hsmp;
2732 /* Check stack size. */
2733 if (!lua_checkstack(L, 3))
2736 /* Create the object: obj[0] = userdata.
2737 * Note that the base of the Fetches object is the
2738 * transaction object.
2741 hsmp = lua_newuserdata(L, sizeof(*hsmp));
2742 lua_rawseti(L, -2, 0);
2746 hsmp->stringsafe = stringsafe;
2748 /* Pop a class sesison metatable and affect it to the userdata. */
2749 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2750 lua_setmetatable(L, -2);
2755 /* This function is an LUA binding. It is called with each sample-fetch.
2756 * It uses closure argument to store the associated sample-fetch. It
2757 * returns only one argument or throws an error. An error is thrown
2758 * only if an error is encountered during the argument parsing. If
2759 * the "sample-fetch" function fails, nil is returned.
2761 __LJMP static int hlua_run_sample_fetch(lua_State *L)
2763 struct hlua_smp *hsmp;
2764 struct sample_fetch *f;
2765 struct arg args[ARGM_NBARGS + 1];
2769 /* Get closure arguments. */
2770 f = (struct sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
2772 /* Get traditionnal arguments. */
2773 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
2775 /* Get extra arguments. */
2776 for (i = 0; i < lua_gettop(L) - 1; i++) {
2777 if (i >= ARGM_NBARGS)
2779 hlua_lua2arg(L, i + 2, &args[i]);
2781 args[i].type = ARGT_STOP;
2783 /* Check arguments. */
2784 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
2786 /* Run the special args checker. */
2787 if (f->val_args && !f->val_args(args, NULL)) {
2788 lua_pushfstring(L, "error in arguments");
2789 WILL_LJMP(lua_error(L));
2792 /* Initialise the sample. */
2793 memset(&smp, 0, sizeof(smp));
2795 /* Run the sample fetch process. */
2797 smp.sess = hsmp->s->sess;
2800 if (!f->process(args, &smp, f->kw, f->private)) {
2801 if (hsmp->stringsafe)
2802 lua_pushstring(L, "");
2808 /* Convert the returned sample in lua value. */
2809 if (hsmp->stringsafe)
2810 hlua_smp2lua_str(L, &smp);
2812 hlua_smp2lua(L, &smp);
2824 /* Returns a struct hlua_session if the stack entry "ud" is
2825 * a class stream, otherwise it throws an error.
2827 __LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
2829 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
2832 /* This function creates and push in the stack a Converters object
2833 * according with a current TXN.
2835 static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
2837 struct hlua_smp *hsmp;
2839 /* Check stack size. */
2840 if (!lua_checkstack(L, 3))
2843 /* Create the object: obj[0] = userdata.
2844 * Note that the base of the Converters object is the
2845 * same than the TXN object.
2848 hsmp = lua_newuserdata(L, sizeof(*hsmp));
2849 lua_rawseti(L, -2, 0);
2853 hsmp->stringsafe = stringsafe;
2855 /* Pop a class stream metatable and affect it to the table. */
2856 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
2857 lua_setmetatable(L, -2);
2862 /* This function is an LUA binding. It is called with each converter.
2863 * It uses closure argument to store the associated converter. It
2864 * returns only one argument or throws an error. An error is thrown
2865 * only if an error is encountered during the argument parsing. If
2866 * the converter function function fails, nil is returned.
2868 __LJMP static int hlua_run_sample_conv(lua_State *L)
2870 struct hlua_smp *hsmp;
2871 struct sample_conv *conv;
2872 struct arg args[ARGM_NBARGS + 1];
2876 /* Get closure arguments. */
2877 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
2879 /* Get traditionnal arguments. */
2880 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
2882 /* Get extra arguments. */
2883 for (i = 0; i < lua_gettop(L) - 2; i++) {
2884 if (i >= ARGM_NBARGS)
2886 hlua_lua2arg(L, i + 3, &args[i]);
2888 args[i].type = ARGT_STOP;
2890 /* Check arguments. */
2891 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
2893 /* Run the special args checker. */
2894 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
2895 hlua_pusherror(L, "error in arguments");
2896 WILL_LJMP(lua_error(L));
2899 /* Initialise the sample. */
2900 if (!hlua_lua2smp(L, 2, &smp)) {
2901 hlua_pusherror(L, "error in the input argument");
2902 WILL_LJMP(lua_error(L));
2905 /* Apply expected cast. */
2906 if (!sample_casts[smp.data.type][conv->in_type]) {
2907 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
2908 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
2909 WILL_LJMP(lua_error(L));
2911 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
2912 !sample_casts[smp.data.type][conv->in_type](&smp)) {
2913 hlua_pusherror(L, "error during the input argument casting");
2914 WILL_LJMP(lua_error(L));
2917 /* Run the sample conversion process. */
2919 smp.sess = hsmp->s->sess;
2922 if (!conv->process(args, &smp, conv->private)) {
2923 if (hsmp->stringsafe)
2924 lua_pushstring(L, "");
2930 /* Convert the returned sample in lua value. */
2931 if (hsmp->stringsafe)
2932 hlua_smp2lua_str(L, &smp);
2934 hlua_smp2lua(L, &smp);
2946 /* Returns a struct hlua_txn if the stack entry "ud" is
2947 * a class stream, otherwise it throws an error.
2949 __LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
2951 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
2954 /* This function creates and push in the stack a HTTP object
2955 * according with a current TXN.
2957 static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
2959 struct hlua_txn *htxn;
2961 /* Check stack size. */
2962 if (!lua_checkstack(L, 3))
2965 /* Create the object: obj[0] = userdata.
2966 * Note that the base of the Converters object is the
2967 * same than the TXN object.
2970 htxn = lua_newuserdata(L, sizeof(*htxn));
2971 lua_rawseti(L, -2, 0);
2976 /* Pop a class stream metatable and affect it to the table. */
2977 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
2978 lua_setmetatable(L, -2);
2983 /* This function creates ans returns an array of HTTP headers.
2984 * This function does not fails. It is used as wrapper with the
2985 * 2 following functions.
2987 __LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
2989 const char *cur_ptr, *cur_next, *p;
2990 int old_idx, cur_idx;
2991 struct hdr_idx_elem *cur_hdr;
2992 const char *hn, *hv;
2999 /* Create the table. */
3005 /* Build array of headers. */
3007 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
3010 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
3015 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
3017 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
3019 /* Now we have one full header at cur_ptr of len cur_hdr->len,
3020 * and the next header starts at cur_next. We'll check
3021 * this header in the list as well as against the default
3025 /* look for ': *'. */
3027 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
3028 if (p >= cur_ptr+cur_hdr->len)
3032 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
3034 if (p >= cur_ptr+cur_hdr->len)
3037 hvl = cur_ptr+cur_hdr->len-p;
3039 /* Lowercase the key. Don't check the size of trash, it have
3040 * the size of one buffer and the input data contains in one
3044 for (in=hn; in<hn+hnl; in++, out++)
3045 *out = tolower(*in);
3048 /* Check for existing entry:
3049 * assume that the table is on the top of the stack, and
3050 * push the key in the stack, the function lua_gettable()
3051 * perform the lookup.
3053 lua_pushlstring(L, trash.str, hnl);
3054 lua_gettable(L, -2);
3055 type = lua_type(L, -1);
3059 /* Table not found, create it. */
3060 lua_pop(L, 1); /* remove the nil value. */
3061 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
3062 lua_newtable(L); /* create and push empty table. */
3063 lua_pushlstring(L, hv, hvl); /* push header value. */
3064 lua_rawseti(L, -2, 0); /* index header value (pop it). */
3065 lua_rawset(L, -3); /* index new table with header name (pop the values). */
3069 /* Entry found: push the value in the table. */
3070 len = lua_rawlen(L, -1);
3071 lua_pushlstring(L, hv, hvl); /* push header value. */
3072 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
3073 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
3077 /* Other cases are errors. */
3078 hlua_pusherror(L, "internal error during the parsing of headers.");
3079 WILL_LJMP(lua_error(L));
3086 __LJMP static int hlua_http_req_get_headers(lua_State *L)
3088 struct hlua_txn *htxn;
3090 MAY_LJMP(check_args(L, 1, "req_get_headers"));
3091 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3093 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
3096 __LJMP static int hlua_http_res_get_headers(lua_State *L)
3098 struct hlua_txn *htxn;
3100 MAY_LJMP(check_args(L, 1, "res_get_headers"));
3101 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3103 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
3106 /* This function replace full header, or just a value in
3107 * the request or in the response. It is a wrapper fir the
3108 * 4 following functions.
3110 __LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
3111 struct http_msg *msg, int action)
3114 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3115 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
3116 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
3119 if (!regex_comp(reg, &re, 1, 1, NULL))
3120 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
3122 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
3127 __LJMP static int hlua_http_req_rep_hdr(lua_State *L)
3129 struct hlua_txn *htxn;
3131 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3132 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3134 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
3137 __LJMP static int hlua_http_res_rep_hdr(lua_State *L)
3139 struct hlua_txn *htxn;
3141 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
3142 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3144 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
3147 __LJMP static int hlua_http_req_rep_val(lua_State *L)
3149 struct hlua_txn *htxn;
3151 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3152 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3154 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
3157 __LJMP static int hlua_http_res_rep_val(lua_State *L)
3159 struct hlua_txn *htxn;
3161 MAY_LJMP(check_args(L, 4, "res_rep_val"));
3162 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3164 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
3167 /* This function deletes all the occurences of an header.
3168 * It is a wrapper for the 2 following functions.
3170 __LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3173 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3175 struct http_txn *txn = htxn->s->txn;
3178 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
3179 http_remove_header2(msg, &txn->hdr_idx, &ctx);
3183 __LJMP static int hlua_http_req_del_hdr(lua_State *L)
3185 struct hlua_txn *htxn;
3187 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3188 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3190 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
3193 __LJMP static int hlua_http_res_del_hdr(lua_State *L)
3195 struct hlua_txn *htxn;
3197 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3198 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3200 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
3203 /* This function adds an header. It is a wrapper used by
3204 * the 2 following functions.
3206 __LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3209 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3211 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
3215 trash.len = value_len + name_len + 2;
3216 if (trash.len > trash.size)
3219 /* Creates the header string. */
3221 memcpy(p, name, name_len);
3227 memcpy(p, value, value_len);
3229 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
3230 trash.str, trash.len) != 0);
3235 __LJMP static int hlua_http_req_add_hdr(lua_State *L)
3237 struct hlua_txn *htxn;
3239 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
3240 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3242 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
3245 __LJMP static int hlua_http_res_add_hdr(lua_State *L)
3247 struct hlua_txn *htxn;
3249 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
3250 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3252 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
3255 static int hlua_http_req_set_hdr(lua_State *L)
3257 struct hlua_txn *htxn;
3259 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
3260 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3262 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
3263 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
3266 static int hlua_http_res_set_hdr(lua_State *L)
3268 struct hlua_txn *htxn;
3270 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
3271 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3273 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
3274 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
3277 /* This function set the method. */
3278 static int hlua_http_req_set_meth(lua_State *L)
3280 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3282 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3284 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
3288 /* This function set the method. */
3289 static int hlua_http_req_set_path(lua_State *L)
3291 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3293 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3294 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
3298 /* This function set the query-string. */
3299 static int hlua_http_req_set_query(lua_State *L)
3301 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3303 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3306 if (name_len > trash.size - 1) {
3307 lua_pushboolean(L, 0);
3311 /* Add the mark question as prefix. */
3312 chunk_reset(&trash);
3313 trash.str[trash.len++] = '?';
3314 memcpy(trash.str + trash.len, name, name_len);
3315 trash.len += name_len;
3317 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
3321 /* This function set the uri. */
3322 static int hlua_http_req_set_uri(lua_State *L)
3324 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3326 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3328 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
3332 /* This function set the response code. */
3333 static int hlua_http_res_set_status(lua_State *L)
3335 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3336 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
3338 http_set_status(code, htxn->s);
3350 /* Returns a struct hlua_session if the stack entry "ud" is
3351 * a class stream, otherwise it throws an error.
3353 __LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
3355 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
3358 __LJMP static int hlua_set_var(lua_State *L)
3360 struct hlua_txn *htxn;
3365 MAY_LJMP(check_args(L, 3, "set_var"));
3367 /* It is useles to retrieve the stream, but this function
3368 * runs only in a stream context.
3370 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3371 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3373 /* Converts the third argument in a sample. */
3374 hlua_lua2smp(L, 3, &smp);
3376 /* Store the sample in a variable. */
3377 vars_set_by_name(name, len, htxn->s, &smp);
3381 __LJMP static int hlua_get_var(lua_State *L)
3383 struct hlua_txn *htxn;
3388 MAY_LJMP(check_args(L, 2, "get_var"));
3390 /* It is useles to retrieve the stream, but this function
3391 * runs only in a stream context.
3393 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3394 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3396 if (!vars_get_by_name(name, len, htxn->s, &smp)) {
3401 return hlua_smp2lua(L, &smp);
3404 __LJMP static int hlua_set_priv(lua_State *L)
3408 MAY_LJMP(check_args(L, 2, "set_priv"));
3410 /* It is useles to retrieve the stream, but this function
3411 * runs only in a stream context.
3413 MAY_LJMP(hlua_checktxn(L, 1));
3414 hlua = hlua_gethlua(L);
3416 /* Remove previous value. */
3417 if (hlua->Mref != -1)
3418 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3420 /* Get and store new value. */
3421 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3422 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3427 __LJMP static int hlua_get_priv(lua_State *L)
3431 MAY_LJMP(check_args(L, 1, "get_priv"));
3433 /* It is useles to retrieve the stream, but this function
3434 * runs only in a stream context.
3436 MAY_LJMP(hlua_checktxn(L, 1));
3437 hlua = hlua_gethlua(L);
3439 /* Push configuration index in the stack. */
3440 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3445 /* Create stack entry containing a class TXN. This function
3446 * return 0 if the stack does not contains free slots,
3447 * otherwise it returns 1.
3449 static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p)
3451 struct hlua_txn *htxn;
3453 /* Check stack size. */
3454 if (!lua_checkstack(L, 3))
3457 /* NOTE: The allocation never fails. The failure
3458 * throw an error, and the function never returns.
3459 * if the throw is not avalaible, the process is aborted.
3461 /* Create the object: obj[0] = userdata. */
3463 htxn = lua_newuserdata(L, sizeof(*htxn));
3464 lua_rawseti(L, -2, 0);
3469 /* Create the "f" field that contains a list of fetches. */
3470 lua_pushstring(L, "f");
3471 if (!hlua_fetches_new(L, htxn, 0))
3473 lua_settable(L, -3);
3475 /* Create the "sf" field that contains a list of stringsafe fetches. */
3476 lua_pushstring(L, "sf");
3477 if (!hlua_fetches_new(L, htxn, 1))
3479 lua_settable(L, -3);
3481 /* Create the "c" field that contains a list of converters. */
3482 lua_pushstring(L, "c");
3483 if (!hlua_converters_new(L, htxn, 0))
3485 lua_settable(L, -3);
3487 /* Create the "sc" field that contains a list of stringsafe converters. */
3488 lua_pushstring(L, "sc");
3489 if (!hlua_converters_new(L, htxn, 1))
3491 lua_settable(L, -3);
3493 /* Create the "req" field that contains the request channel object. */
3494 lua_pushstring(L, "req");
3495 if (!hlua_channel_new(L, &s->req))
3497 lua_settable(L, -3);
3499 /* Create the "res" field that contains the response channel object. */
3500 lua_pushstring(L, "res");
3501 if (!hlua_channel_new(L, &s->res))
3503 lua_settable(L, -3);
3505 /* Creates the HTTP object is the current proxy allows http. */
3506 lua_pushstring(L, "http");
3507 if (p->mode == PR_MODE_HTTP) {
3508 if (!hlua_http_new(L, htxn))
3513 lua_settable(L, -3);
3515 /* Pop a class sesison metatable and affect it to the userdata. */
3516 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
3517 lua_setmetatable(L, -2);
3522 __LJMP static int hlua_txn_deflog(lua_State *L)
3525 struct hlua_txn *htxn;
3527 MAY_LJMP(check_args(L, 2, "deflog"));
3528 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3529 msg = MAY_LJMP(luaL_checkstring(L, 2));
3531 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
3535 __LJMP static int hlua_txn_log(lua_State *L)
3539 struct hlua_txn *htxn;
3541 MAY_LJMP(check_args(L, 3, "log"));
3542 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3543 level = MAY_LJMP(luaL_checkinteger(L, 2));
3544 msg = MAY_LJMP(luaL_checkstring(L, 3));
3546 if (level < 0 || level >= NB_LOG_LEVELS)
3547 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3549 hlua_sendlog(htxn->s->be, level, msg);
3553 __LJMP static int hlua_txn_log_debug(lua_State *L)
3556 struct hlua_txn *htxn;
3558 MAY_LJMP(check_args(L, 2, "Debug"));
3559 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3560 msg = MAY_LJMP(luaL_checkstring(L, 2));
3561 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
3565 __LJMP static int hlua_txn_log_info(lua_State *L)
3568 struct hlua_txn *htxn;
3570 MAY_LJMP(check_args(L, 2, "Info"));
3571 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3572 msg = MAY_LJMP(luaL_checkstring(L, 2));
3573 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
3577 __LJMP static int hlua_txn_log_warning(lua_State *L)
3580 struct hlua_txn *htxn;
3582 MAY_LJMP(check_args(L, 2, "Warning"));
3583 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3584 msg = MAY_LJMP(luaL_checkstring(L, 2));
3585 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
3589 __LJMP static int hlua_txn_log_alert(lua_State *L)
3592 struct hlua_txn *htxn;
3594 MAY_LJMP(check_args(L, 2, "Alert"));
3595 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3596 msg = MAY_LJMP(luaL_checkstring(L, 2));
3597 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
3601 __LJMP static int hlua_txn_set_loglevel(lua_State *L)
3603 struct hlua_txn *htxn;
3606 MAY_LJMP(check_args(L, 2, "set_loglevel"));
3607 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3608 ll = MAY_LJMP(luaL_checkinteger(L, 2));
3610 if (ll < 0 || ll > 7)
3611 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
3613 htxn->s->logs.level = ll;
3617 __LJMP static int hlua_txn_set_tos(lua_State *L)
3619 struct hlua_txn *htxn;
3620 struct connection *cli_conn;
3623 MAY_LJMP(check_args(L, 2, "set_tos"));
3624 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3625 tos = MAY_LJMP(luaL_checkinteger(L, 2));
3627 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
3628 inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, tos);
3633 __LJMP static int hlua_txn_set_mark(lua_State *L)
3636 struct hlua_txn *htxn;
3637 struct connection *cli_conn;
3640 MAY_LJMP(check_args(L, 2, "set_mark"));
3641 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3642 mark = MAY_LJMP(luaL_checkinteger(L, 2));
3644 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
3645 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
3650 /* This function is an Lua binding that send pending data
3651 * to the client, and close the stream interface.
3653 __LJMP static int hlua_txn_done(lua_State *L)
3655 struct hlua_txn *htxn;
3656 struct channel *ic, *oc;
3658 MAY_LJMP(check_args(L, 1, "close"));
3659 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3665 /* HTTP mode, let's stay in sync with the stream */
3666 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
3667 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
3668 htxn->s->txn->req.sov = 0;
3669 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
3670 oc->analysers = AN_RES_HTTP_XFER_BODY;
3671 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
3672 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
3674 /* Trim any possible response */
3676 htxn->s->txn->rsp.next = htxn->s->txn->rsp.sov = 0;
3678 /* Note that if we want to support keep-alive, we need
3679 * to bypass the close/shutr_now calls below, but that
3680 * may only be done if the HTTP request was already
3681 * processed and the connection header is known (ie
3682 * not during TCP rules).
3686 channel_auto_read(ic);
3688 channel_auto_close(ic);
3691 oc->wex = tick_add_ifset(now_ms, oc->wto);
3692 channel_auto_read(oc);
3693 channel_auto_close(oc);
3694 channel_shutr_now(oc);
3698 WILL_LJMP(hlua_done(L));
3702 __LJMP static int hlua_log(lua_State *L)
3707 MAY_LJMP(check_args(L, 2, "log"));
3708 level = MAY_LJMP(luaL_checkinteger(L, 1));
3709 msg = MAY_LJMP(luaL_checkstring(L, 2));
3711 if (level < 0 || level >= NB_LOG_LEVELS)
3712 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3714 hlua_sendlog(NULL, level, msg);
3718 __LJMP static int hlua_log_debug(lua_State *L)
3722 MAY_LJMP(check_args(L, 1, "debug"));
3723 msg = MAY_LJMP(luaL_checkstring(L, 1));
3724 hlua_sendlog(NULL, LOG_DEBUG, msg);
3728 __LJMP static int hlua_log_info(lua_State *L)
3732 MAY_LJMP(check_args(L, 1, "info"));
3733 msg = MAY_LJMP(luaL_checkstring(L, 1));
3734 hlua_sendlog(NULL, LOG_INFO, msg);
3738 __LJMP static int hlua_log_warning(lua_State *L)
3742 MAY_LJMP(check_args(L, 1, "warning"));
3743 msg = MAY_LJMP(luaL_checkstring(L, 1));
3744 hlua_sendlog(NULL, LOG_WARNING, msg);
3748 __LJMP static int hlua_log_alert(lua_State *L)
3752 MAY_LJMP(check_args(L, 1, "alert"));
3753 msg = MAY_LJMP(luaL_checkstring(L, 1));
3754 hlua_sendlog(NULL, LOG_ALERT, msg);
3758 __LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
3760 int wakeup_ms = lua_tointeger(L, -1);
3761 if (now_ms < wakeup_ms)
3762 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3766 __LJMP static int hlua_sleep(lua_State *L)
3769 unsigned int wakeup_ms;
3771 MAY_LJMP(check_args(L, 1, "sleep"));
3773 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
3774 wakeup_ms = tick_add(now_ms, delay);
3775 lua_pushinteger(L, wakeup_ms);
3777 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3781 __LJMP static int hlua_msleep(lua_State *L)
3784 unsigned int wakeup_ms;
3786 MAY_LJMP(check_args(L, 1, "msleep"));
3788 delay = MAY_LJMP(luaL_checkinteger(L, 1));
3789 wakeup_ms = tick_add(now_ms, delay);
3790 lua_pushinteger(L, wakeup_ms);
3792 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3796 /* This functionis an LUA binding. it permits to give back
3797 * the hand at the HAProxy scheduler. It is used when the
3798 * LUA processing consumes a lot of time.
3800 __LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
3805 __LJMP static int hlua_yield(lua_State *L)
3807 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
3811 /* This function change the nice of the currently executed
3812 * task. It is used set low or high priority at the current
3815 __LJMP static int hlua_set_nice(lua_State *L)
3820 MAY_LJMP(check_args(L, 1, "set_nice"));
3821 hlua = hlua_gethlua(L);
3822 nice = MAY_LJMP(luaL_checkinteger(L, 1));
3824 /* If he task is not set, I'm in a start mode. */
3825 if (!hlua || !hlua->task)
3830 else if (nice > 1024)
3833 hlua->task->nice = nice;
3837 /* This function is used as a calback of a task. It is called by the
3838 * HAProxy task subsystem when the task is awaked. The LUA runtime can
3839 * return an E_AGAIN signal, the emmiter of this signal must set a
3840 * signal to wake the task.
3842 static struct task *hlua_process_task(struct task *task)
3844 struct hlua *hlua = task->context;
3845 enum hlua_exec status;
3847 /* We need to remove the task from the wait queue before executing
3848 * the Lua code because we don't know if it needs to wait for
3849 * another timer or not in the case of E_AGAIN.
3853 /* If it is the first call to the task, we must initialize the
3854 * execution timeouts.
3856 if (!HLUA_IS_RUNNING(hlua))
3857 hlua->expire = tick_add_ifset(now_ms, hlua_timeout_task);
3859 /* Execute the Lua code. */
3860 status = hlua_ctx_resume(hlua, 1);
3863 /* finished or yield */
3865 hlua_ctx_destroy(hlua);
3870 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
3871 if (hlua->wake_time != TICK_ETERNITY)
3872 task_schedule(task, hlua->wake_time);
3875 /* finished with error. */
3877 send_log(NULL, LOG_ERR, "Lua task: %s.", lua_tostring(hlua->T, -1));
3878 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3879 Alert("Lua task: %s.\n", lua_tostring(hlua->T, -1));
3880 hlua_ctx_destroy(hlua);
3887 send_log(NULL, LOG_ERR, "Lua task: unknown error.");
3888 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3889 Alert("Lua task: unknown error.\n");
3890 hlua_ctx_destroy(hlua);
3898 /* This function is an LUA binding that register LUA function to be
3899 * executed after the HAProxy configuration parsing and before the
3900 * HAProxy scheduler starts. This function expect only one LUA
3901 * argument that is a function. This function returns nothing, but
3902 * throws if an error is encountered.
3904 __LJMP static int hlua_register_init(lua_State *L)
3906 struct hlua_init_function *init;
3909 MAY_LJMP(check_args(L, 1, "register_init"));
3911 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3913 init = malloc(sizeof(*init));
3915 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3917 init->function_ref = ref;
3918 LIST_ADDQ(&hlua_init_functions, &init->l);
3922 /* This functio is an LUA binding. It permits to register a task
3923 * executed in parallel of the main HAroxy activity. The task is
3924 * created and it is set in the HAProxy scheduler. It can be called
3925 * from the "init" section, "post init" or during the runtime.
3929 * <none> core.register_task(<function>)
3931 static int hlua_register_task(lua_State *L)
3937 MAY_LJMP(check_args(L, 1, "register_task"));
3939 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3941 hlua = malloc(sizeof(*hlua));
3943 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3946 task->context = hlua;
3947 task->process = hlua_process_task;
3949 if (!hlua_ctx_init(hlua, task))
3950 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3952 /* Restore the function in the stack. */
3953 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
3956 /* Schedule task. */
3957 task_schedule(task, now_ms);
3962 /* Wrapper called by HAProxy to execute an LUA converter. This wrapper
3963 * doesn't allow "yield" functions because the HAProxy engine cannot
3964 * resume converters.
3966 static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
3968 struct hlua_function *fcn = (struct hlua_function *)private;
3969 struct stream *stream = smp->strm;
3971 /* In the execution wrappers linked with a stream, the
3972 * Lua context can be not initialized. This behavior
3973 * permits to save performances because a systematic
3974 * Lua initialization cause 5% performances loss.
3976 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
3977 send_log(stream->be, LOG_ERR, "Lua converter '%s': can't initialize Lua context.", fcn->name);
3978 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3979 Alert("Lua converter '%s': can't initialize Lua context.\n", fcn->name);
3983 /* If it is the first run, initialize the data for the call. */
3984 if (!HLUA_IS_RUNNING(&stream->hlua)) {
3985 /* Check stack available size. */
3986 if (!lua_checkstack(stream->hlua.T, 1)) {
3987 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
3988 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3989 Alert("Lua converter '%s': full stack.\n", fcn->name);
3993 /* Restore the function in the stack. */
3994 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
3996 /* convert input sample and pust-it in the stack. */
3997 if (!lua_checkstack(stream->hlua.T, 1)) {
3998 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
3999 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4000 Alert("Lua converter '%s': full stack.\n", fcn->name);
4003 hlua_smp2lua(stream->hlua.T, smp);
4004 stream->hlua.nargs = 2;
4006 /* push keywords in the stack. */
4008 for (; arg_p->type != ARGT_STOP; arg_p++) {
4009 if (!lua_checkstack(stream->hlua.T, 1)) {
4010 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
4011 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4012 Alert("Lua converter '%s': full stack.\n", fcn->name);
4015 hlua_arg2lua(stream->hlua.T, arg_p);
4016 stream->hlua.nargs++;
4020 /* We must initialize the execution timeouts. */
4021 stream->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
4023 /* Set the currently running flag. */
4024 HLUA_SET_RUN(&stream->hlua);
4027 /* Execute the function. */
4028 switch (hlua_ctx_resume(&stream->hlua, 0)) {
4031 /* Convert the returned value in sample. */
4032 hlua_lua2smp(stream->hlua.T, -1, smp);
4033 lua_pop(stream->hlua.T, 1);
4038 send_log(stream->be, LOG_ERR, "Lua converter '%s': cannot use yielded functions.", fcn->name);
4039 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4040 Alert("Lua converter '%s': cannot use yielded functions.\n", fcn->name);
4043 /* finished with error. */
4046 send_log(stream->be, LOG_ERR, "Lua converter '%s': %s.", fcn->name, lua_tostring(stream->hlua.T, -1));
4047 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4048 Alert("Lua converter '%s': %s.\n", fcn->name, lua_tostring(stream->hlua.T, -1));
4049 lua_pop(stream->hlua.T, 1);
4054 send_log(stream->be, LOG_ERR, "Lua converter '%s' returns an unknown error.", fcn->name);
4055 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4056 Alert("Lua converter '%s' returns an unknown error.\n", fcn->name);
4063 /* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
4064 * doesn't allow "yield" functions because the HAProxy engine cannot
4065 * resume sample-fetches.
4067 static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
4068 const char *kw, void *private)
4070 struct hlua_function *fcn = (struct hlua_function *)private;
4071 struct stream *stream = smp->strm;
4073 /* In the execution wrappers linked with a stream, the
4074 * Lua context can be not initialized. This behavior
4075 * permits to save performances because a systematic
4076 * Lua initialization cause 5% performances loss.
4078 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
4079 send_log(stream->be, LOG_ERR, "Lua sample-fetch '%s': can't initialize Lua context.", fcn->name);
4080 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4081 Alert("Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
4085 /* If it is the first run, initialize the data for the call. */
4086 if (!HLUA_IS_RUNNING(&stream->hlua)) {
4087 /* Check stack available size. */
4088 if (!lua_checkstack(stream->hlua.T, 2)) {
4089 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
4090 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4091 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4095 /* Restore the function in the stack. */
4096 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
4098 /* push arguments in the stack. */
4099 if (!hlua_txn_new(stream->hlua.T, stream, smp->px)) {
4100 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
4101 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4102 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4105 stream->hlua.nargs = 1;
4107 /* push keywords in the stack. */
4108 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
4109 /* Check stack available size. */
4110 if (!lua_checkstack(stream->hlua.T, 1)) {
4111 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
4112 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4113 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4116 if (!lua_checkstack(stream->hlua.T, 1)) {
4117 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
4118 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4119 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4122 hlua_arg2lua(stream->hlua.T, arg_p);
4123 stream->hlua.nargs++;
4126 /* We must initialize the execution timeouts. */
4127 stream->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
4129 /* Set the currently running flag. */
4130 HLUA_SET_RUN(&stream->hlua);
4133 /* Execute the function. */
4134 switch (hlua_ctx_resume(&stream->hlua, 0)) {
4137 /* Convert the returned value in sample. */
4138 hlua_lua2smp(stream->hlua.T, -1, smp);
4139 lua_pop(stream->hlua.T, 1);
4141 /* Set the end of execution flag. */
4142 smp->flags &= ~SMP_F_MAY_CHANGE;
4147 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': cannot use yielded functions.", fcn->name);
4148 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4149 Alert("Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
4152 /* finished with error. */
4155 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': %s.", fcn->name, lua_tostring(stream->hlua.T, -1));
4156 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4157 Alert("Lua sample-fetch '%s': %s.\n", fcn->name, lua_tostring(stream->hlua.T, -1));
4158 lua_pop(stream->hlua.T, 1);
4163 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s' returns an unknown error.", fcn->name);
4164 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4165 Alert("Lua sample-fetch '%s': returns an unknown error.\n", fcn->name);
4172 /* This function is an LUA binding used for registering
4173 * "sample-conv" functions. It expects a converter name used
4174 * in the haproxy configuration file, and an LUA function.
4176 __LJMP static int hlua_register_converters(lua_State *L)
4178 struct sample_conv_kw_list *sck;
4182 struct hlua_function *fcn;
4184 MAY_LJMP(check_args(L, 2, "register_converters"));
4186 /* First argument : converter name. */
4187 name = MAY_LJMP(luaL_checkstring(L, 1));
4189 /* Second argument : lua function. */
4190 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4192 /* Allocate and fill the sample fetch keyword struct. */
4193 sck = malloc(sizeof(*sck) + sizeof(struct sample_conv) * 2);
4195 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4196 fcn = malloc(sizeof(*fcn));
4198 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4201 fcn->name = strdup(name);
4203 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4204 fcn->function_ref = ref;
4207 sck->list.n = sck->list.p = NULL;
4209 /* converter keyword. */
4210 len = strlen("lua.") + strlen(name) + 1;
4211 sck->kw[0].kw = malloc(len);
4213 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4215 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
4216 sck->kw[0].process = hlua_sample_conv_wrapper;
4217 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4218 sck->kw[0].val_args = NULL;
4219 sck->kw[0].in_type = SMP_T_STR;
4220 sck->kw[0].out_type = SMP_T_STR;
4221 sck->kw[0].private = fcn;
4224 memset(&sck->kw[1], 0, sizeof(struct sample_conv));
4226 /* Register this new converter */
4227 sample_register_convs(sck);
4232 /* This fucntion is an LUA binding used for registering
4233 * "sample-fetch" functions. It expects a converter name used
4234 * in the haproxy configuration file, and an LUA function.
4236 __LJMP static int hlua_register_fetches(lua_State *L)
4241 struct sample_fetch_kw_list *sfk;
4242 struct hlua_function *fcn;
4244 MAY_LJMP(check_args(L, 2, "register_fetches"));
4246 /* First argument : sample-fetch name. */
4247 name = MAY_LJMP(luaL_checkstring(L, 1));
4249 /* Second argument : lua function. */
4250 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4252 /* Allocate and fill the sample fetch keyword struct. */
4253 sfk = malloc(sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
4255 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4256 fcn = malloc(sizeof(*fcn));
4258 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4261 fcn->name = strdup(name);
4263 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4264 fcn->function_ref = ref;
4267 sfk->list.n = sfk->list.p = NULL;
4269 /* sample-fetch keyword. */
4270 len = strlen("lua.") + strlen(name) + 1;
4271 sfk->kw[0].kw = malloc(len);
4273 return luaL_error(L, "lua out of memory error.");
4275 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
4276 sfk->kw[0].process = hlua_sample_fetch_wrapper;
4277 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4278 sfk->kw[0].val_args = NULL;
4279 sfk->kw[0].out_type = SMP_T_STR;
4280 sfk->kw[0].use = SMP_USE_HTTP_ANY;
4282 sfk->kw[0].private = fcn;
4285 memset(&sfk->kw[1], 0, sizeof(struct sample_fetch));
4287 /* Register this new fetch. */
4288 sample_register_fetches(sfk);
4293 /* This function is a wrapper to execute each LUA function declared
4294 * as an action wrapper during the initialisation period. This function
4295 * return ACT_RET_CONT if the processing is finished (with or without
4296 * error) and return ACT_RET_YIELD if the function must be called again
4297 * because the LUA returns a yield.
4299 static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
4300 struct session *sess, struct stream *s)
4303 unsigned int analyzer;
4305 switch (rule->from) {
4306 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; break;
4307 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; break;
4308 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; break;
4309 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; break;
4311 send_log(px, LOG_ERR, "Lua: internal error while execute action.");
4312 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4313 Alert("Lua: internal error while execute action.\n");
4314 return ACT_RET_CONT;
4317 /* In the execution wrappers linked with a stream, the
4318 * Lua context can be not initialized. This behavior
4319 * permits to save performances because a systematic
4320 * Lua initialization cause 5% performances loss.
4322 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
4323 send_log(px, LOG_ERR, "Lua action '%s': can't initialize Lua context.",
4324 rule->arg.hlua_rule->fcn.name);
4325 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4326 Alert("Lua action '%s': can't initialize Lua context.\n",
4327 rule->arg.hlua_rule->fcn.name);
4328 return ACT_RET_CONT;
4331 /* If it is the first run, initialize the data for the call. */
4332 if (!HLUA_IS_RUNNING(&s->hlua)) {
4333 /* Check stack available size. */
4334 if (!lua_checkstack(s->hlua.T, 1)) {
4335 send_log(px, LOG_ERR, "Lua function '%s': full stack.",
4336 rule->arg.hlua_rule->fcn.name);
4337 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4338 Alert("Lua function '%s': full stack.\n",
4339 rule->arg.hlua_rule->fcn.name);
4340 return ACT_RET_CONT;
4343 /* Restore the function in the stack. */
4344 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
4346 /* Create and and push object stream in the stack. */
4347 if (!hlua_txn_new(s->hlua.T, s, px)) {
4348 send_log(px, LOG_ERR, "Lua function '%s': full stack.",
4349 rule->arg.hlua_rule->fcn.name);
4350 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4351 Alert("Lua function '%s': full stack.\n",
4352 rule->arg.hlua_rule->fcn.name);
4353 return ACT_RET_CONT;
4357 /* push keywords in the stack. */
4358 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
4359 if (!lua_checkstack(s->hlua.T, 1)) {
4360 send_log(px, LOG_ERR, "Lua function '%s': full stack.",
4361 rule->arg.hlua_rule->fcn.name);
4362 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4363 Alert("Lua function '%s': full stack.\n",
4364 rule->arg.hlua_rule->fcn.name);
4365 return ACT_RET_CONT;
4367 lua_pushstring(s->hlua.T, *arg);
4371 /* We must initialize the execution timeouts. */
4372 s->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
4374 /* Set the currently running flag. */
4375 HLUA_SET_RUN(&s->hlua);
4378 /* Execute the function. */
4379 switch (hlua_ctx_resume(&s->hlua, 1)) {
4382 return ACT_RET_CONT;
4386 /* Set timeout in the required channel. */
4387 if (s->hlua.wake_time != TICK_ETERNITY) {
4388 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
4389 s->req.analyse_exp = s->hlua.wake_time;
4390 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
4391 s->res.analyse_exp = s->hlua.wake_time;
4393 /* Some actions can be wake up when a "write" event
4394 * is detected on a response channel. This is useful
4395 * only for actions targetted on the requests.
4397 if (HLUA_IS_WAKERESWR(&s->hlua)) {
4398 s->res.flags |= CF_WAKE_WRITE;
4399 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
4400 s->res.analysers |= analyzer;
4402 if (HLUA_IS_WAKEREQWR(&s->hlua))
4403 s->req.flags |= CF_WAKE_WRITE;
4404 return ACT_RET_YIELD;
4406 /* finished with error. */
4409 send_log(px, LOG_ERR, "Lua function '%s': %s.",
4410 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
4411 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4412 Alert("Lua function '%s': %s.\n",
4413 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
4414 lua_pop(s->hlua.T, 1);
4415 return ACT_RET_CONT;
4419 send_log(px, LOG_ERR, "Lua function '%s' return an unknown error.",
4420 rule->arg.hlua_rule->fcn.name);
4421 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4422 Alert("Lua function '%s' return an unknown error.\n",
4423 rule->arg.hlua_rule->fcn.name);
4426 return ACT_RET_CONT;
4430 /* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
4431 * succes case, else return ACT_RET_PRS_ERR.
4433 static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4434 struct act_rule *rule, char **err)
4436 /* Memory for the rule. */
4437 rule->arg.hlua_rule = malloc(sizeof(*rule->arg.hlua_rule));
4438 if (!rule->arg.hlua_rule) {
4439 memprintf(err, "out of memory error");
4440 return ACT_RET_PRS_ERR;
4443 /* The requiered arg is a function name. */
4444 if (!args[*cur_arg]) {
4445 memprintf(err, "expect Lua function name");
4446 return ACT_RET_PRS_ERR;
4449 /* Lookup for the symbol, and check if it is a function. */
4450 lua_getglobal(gL.T, args[*cur_arg]);
4451 if (lua_isnil(gL.T, -1)) {
4453 memprintf(err, "Lua function '%s' not found", args[*cur_arg]);
4454 return ACT_RET_PRS_ERR;
4456 if (!lua_isfunction(gL.T, -1)) {
4458 memprintf(err, "'%s' is not a function", args[*cur_arg]);
4459 return ACT_RET_PRS_ERR;
4462 /* Reference the Lua function and store the reference. */
4463 rule->arg.hlua_rule->fcn.function_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
4464 rule->arg.hlua_rule->fcn.name = strdup(args[*cur_arg]);
4465 if (!rule->arg.hlua_rule->fcn.name) {
4466 memprintf(err, "out of memory error.");
4467 return ACT_RET_PRS_ERR;
4471 /* TODO: later accept arguments. */
4472 rule->arg.hlua_rule->args = NULL;
4474 rule->action = ACT_CUSTOM;
4475 rule->action_ptr = hlua_action;
4476 return ACT_RET_PRS_OK;
4479 static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
4480 struct proxy *defpx, const char *file, int line,
4481 char **err, unsigned int *timeout)
4485 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
4486 if (error && *error != '\0') {
4487 memprintf(err, "%s: invalid timeout", args[0]);
4493 static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
4494 struct proxy *defpx, const char *file, int line,
4497 return hlua_read_timeout(args, section_type, curpx, defpx,
4498 file, line, err, &hlua_timeout_session);
4501 static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
4502 struct proxy *defpx, const char *file, int line,
4505 return hlua_read_timeout(args, section_type, curpx, defpx,
4506 file, line, err, &hlua_timeout_task);
4509 static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
4510 struct proxy *defpx, const char *file, int line,
4515 hlua_nb_instruction = strtoll(args[1], &error, 10);
4516 if (*error != '\0') {
4517 memprintf(err, "%s: invalid number", args[0]);
4523 static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
4524 struct proxy *defpx, const char *file, int line,
4529 if (*(args[1]) == 0) {
4530 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
4533 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
4534 if (*error != '\0') {
4535 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
4542 /* This function is called by the main configuration key "lua-load". It loads and
4543 * execute an lua file during the parsing of the HAProxy configuration file. It is
4544 * the main lua entry point.
4546 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
4547 * occured, otherwise it returns 0.
4549 * In some error case, LUA set an error message in top of the stack. This function
4550 * returns this error message in the HAProxy logs and pop it from the stack.
4552 static int hlua_load(char **args, int section_type, struct proxy *curpx,
4553 struct proxy *defpx, const char *file, int line,
4558 /* Just load and compile the file. */
4559 error = luaL_loadfile(gL.T, args[1]);
4561 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
4566 /* If no syntax error where detected, execute the code. */
4567 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
4572 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
4576 memprintf(err, "lua out of memory error\n");
4579 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
4583 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
4587 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
4595 /* configuration keywords declaration */
4596 static struct cfg_kw_list cfg_kws = {{ },{
4597 { CFG_GLOBAL, "lua-load", hlua_load },
4598 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
4599 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
4600 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
4601 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
4605 static struct action_kw_list http_req_kws = { { }, {
4606 { "lua", action_register_lua },
4610 static struct action_kw_list http_res_kws = { { }, {
4611 { "lua", action_register_lua },
4615 static struct action_kw_list tcp_req_cont_kws = { { }, {
4616 { "lua", action_register_lua },
4620 static struct action_kw_list tcp_res_cont_kws = { { }, {
4621 { "lua", action_register_lua },
4625 int hlua_post_init()
4627 struct hlua_init_function *init;
4631 list_for_each_entry(init, &hlua_init_functions, l) {
4632 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
4633 ret = hlua_ctx_resume(&gL, 0);
4639 Alert("lua init: yield not allowed.\n");
4642 msg = lua_tostring(gL.T, -1);
4643 Alert("lua init: %s.\n", msg);
4647 Alert("lua init: unknown runtime error.\n");
4654 /* The memory allocator used by the Lua stack. <ud> is a pointer to the
4655 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
4656 * is the previously allocated size or the kind of object in case of a new
4657 * allocation. <nsize> is the requested new size.
4659 static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
4661 struct hlua_mem_allocator *zone = ud;
4666 zone->allocated -= osize;
4672 /* it's a new allocation */
4673 if (zone->limit && zone->allocated + nsize > zone->limit)
4676 ptr = malloc(nsize);
4678 zone->allocated += nsize;
4682 /* it's a realloc */
4683 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
4686 ptr = realloc(ptr, nsize);
4688 zone->allocated += nsize - osize;
4692 void hlua_init(void)
4696 struct sample_fetch *sf;
4697 struct sample_conv *sc;
4703 char *args[] = { /* SSL client configuration. */
4712 /* Initialise com signals pool */
4713 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
4715 /* Register configuration keywords. */
4716 cfg_register_keywords(&cfg_kws);
4718 /* Register custom HTTP rules. */
4719 http_req_keywords_register(&http_req_kws);
4720 http_res_keywords_register(&http_res_kws);
4721 tcp_req_cont_keywords_register(&tcp_req_cont_kws);
4722 tcp_res_cont_keywords_register(&tcp_res_cont_kws);
4724 /* Init main lua stack. */
4725 gL.Mref = LUA_REFNIL;
4728 gL.T = luaL_newstate();
4730 gL.Tref = LUA_REFNIL;
4733 /* change the memory allocators to track memory usage */
4734 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
4736 /* Initialise lua. */
4737 luaL_openlibs(gL.T);
4741 * Create "core" object.
4745 /* This table entry is the object "core" base. */
4748 /* Push the loglevel constants. */
4749 for (i = 0; i < NB_LOG_LEVELS; i++)
4750 hlua_class_const_int(gL.T, log_levels[i], i);
4752 /* Register special functions. */
4753 hlua_class_function(gL.T, "register_init", hlua_register_init);
4754 hlua_class_function(gL.T, "register_task", hlua_register_task);
4755 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
4756 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
4757 hlua_class_function(gL.T, "yield", hlua_yield);
4758 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
4759 hlua_class_function(gL.T, "sleep", hlua_sleep);
4760 hlua_class_function(gL.T, "msleep", hlua_msleep);
4761 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
4762 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
4763 hlua_class_function(gL.T, "set_map", hlua_set_map);
4764 hlua_class_function(gL.T, "del_map", hlua_del_map);
4765 hlua_class_function(gL.T, "tcp", hlua_socket_new);
4766 hlua_class_function(gL.T, "log", hlua_log);
4767 hlua_class_function(gL.T, "Debug", hlua_log_debug);
4768 hlua_class_function(gL.T, "Info", hlua_log_info);
4769 hlua_class_function(gL.T, "Warning", hlua_log_warning);
4770 hlua_class_function(gL.T, "Alert", hlua_log_alert);
4771 hlua_class_function(gL.T, "done", hlua_done);
4773 lua_setglobal(gL.T, "core");
4777 * Register class Map
4781 /* This table entry is the object "Map" base. */
4784 /* register pattern types. */
4785 for (i=0; i<PAT_MATCH_NUM; i++)
4786 hlua_class_const_int(gL.T, pat_match_names[i], i);
4788 /* register constructor. */
4789 hlua_class_function(gL.T, "new", hlua_map_new);
4791 /* Create and fill the metatable. */
4794 /* Create and fille the __index entry. */
4795 lua_pushstring(gL.T, "__index");
4799 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
4800 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
4802 lua_settable(gL.T, -3);
4804 /* Register previous table in the registry with reference and named entry. */
4805 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4806 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4807 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_MAP); /* register class session. */
4808 class_map_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4810 /* Assign the metatable to the mai Map object. */
4811 lua_setmetatable(gL.T, -2);
4813 /* Set a name to the table. */
4814 lua_setglobal(gL.T, "Map");
4818 * Register class Channel
4822 /* Create and fill the metatable. */
4825 /* Create and fille the __index entry. */
4826 lua_pushstring(gL.T, "__index");
4830 hlua_class_function(gL.T, "get", hlua_channel_get);
4831 hlua_class_function(gL.T, "dup", hlua_channel_dup);
4832 hlua_class_function(gL.T, "getline", hlua_channel_getline);
4833 hlua_class_function(gL.T, "set", hlua_channel_set);
4834 hlua_class_function(gL.T, "append", hlua_channel_append);
4835 hlua_class_function(gL.T, "send", hlua_channel_send);
4836 hlua_class_function(gL.T, "forward", hlua_channel_forward);
4837 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
4838 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
4840 lua_settable(gL.T, -3);
4842 /* Register previous table in the registry with reference and named entry. */
4843 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4844 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
4845 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4849 * Register class Fetches
4853 /* Create and fill the metatable. */
4856 /* Create and fille the __index entry. */
4857 lua_pushstring(gL.T, "__index");
4860 /* Browse existing fetches and create the associated
4864 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
4866 /* Dont register the keywork if the arguments check function are
4867 * not safe during the runtime.
4869 if ((sf->val_args != NULL) &&
4870 (sf->val_args != val_payload_lv) &&
4871 (sf->val_args != val_hdr))
4874 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4877 strncpy(trash.str, sf->kw, trash.size);
4878 trash.str[trash.size - 1] = '\0';
4879 for (p = trash.str; *p; p++)
4880 if (*p == '.' || *p == '-' || *p == '+')
4883 /* Register the function. */
4884 lua_pushstring(gL.T, trash.str);
4885 lua_pushlightuserdata(gL.T, sf);
4886 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
4887 lua_settable(gL.T, -3);
4890 lua_settable(gL.T, -3);
4892 /* Register previous table in the registry with reference and named entry. */
4893 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4894 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
4895 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4899 * Register class Converters
4903 /* Create and fill the metatable. */
4906 /* Create and fill the __index entry. */
4907 lua_pushstring(gL.T, "__index");
4910 /* Browse existing converters and create the associated
4914 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
4915 /* Dont register the keywork if the arguments check function are
4916 * not safe during the runtime.
4918 if (sc->val_args != NULL)
4921 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4924 strncpy(trash.str, sc->kw, trash.size);
4925 trash.str[trash.size - 1] = '\0';
4926 for (p = trash.str; *p; p++)
4927 if (*p == '.' || *p == '-' || *p == '+')
4930 /* Register the function. */
4931 lua_pushstring(gL.T, trash.str);
4932 lua_pushlightuserdata(gL.T, sc);
4933 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
4934 lua_settable(gL.T, -3);
4937 lua_settable(gL.T, -3);
4939 /* Register previous table in the registry with reference and named entry. */
4940 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4941 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
4942 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4946 * Register class HTTP
4950 /* Create and fill the metatable. */
4953 /* Create and fille the __index entry. */
4954 lua_pushstring(gL.T, "__index");
4957 /* Register Lua functions. */
4958 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
4959 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
4960 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
4961 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
4962 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
4963 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
4964 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
4965 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
4966 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
4967 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
4969 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
4970 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
4971 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
4972 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
4973 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
4974 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
4975 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
4977 lua_settable(gL.T, -3);
4979 /* Register previous table in the registry with reference and named entry. */
4980 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4981 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_HTTP); /* register class session. */
4982 class_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4986 * Register class TXN
4990 /* Create and fill the metatable. */
4993 /* Create and fille the __index entry. */
4994 lua_pushstring(gL.T, "__index");
4997 /* Register Lua functions. */
4998 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
4999 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
5000 hlua_class_function(gL.T, "set_var", hlua_set_var);
5001 hlua_class_function(gL.T, "get_var", hlua_get_var);
5002 hlua_class_function(gL.T, "done", hlua_txn_done);
5003 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
5004 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
5005 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
5006 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
5007 hlua_class_function(gL.T, "log", hlua_txn_log);
5008 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
5009 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
5010 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
5011 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
5013 lua_settable(gL.T, -3);
5015 /* Register previous table in the registry with reference and named entry. */
5016 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5017 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
5018 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
5022 * Register class Socket
5026 /* Create and fill the metatable. */
5029 /* Create and fille the __index entry. */
5030 lua_pushstring(gL.T, "__index");
5034 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
5036 hlua_class_function(gL.T, "connect", hlua_socket_connect);
5037 hlua_class_function(gL.T, "send", hlua_socket_send);
5038 hlua_class_function(gL.T, "receive", hlua_socket_receive);
5039 hlua_class_function(gL.T, "close", hlua_socket_close);
5040 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
5041 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
5042 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
5043 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
5045 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
5047 /* Register the garbage collector entry. */
5048 lua_pushstring(gL.T, "__gc");
5049 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
5050 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
5052 /* Register previous table in the registry with reference and named entry. */
5053 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5054 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5055 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
5056 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
5058 /* Proxy and server configuration initialisation. */
5059 memset(&socket_proxy, 0, sizeof(socket_proxy));
5060 init_new_proxy(&socket_proxy);
5061 socket_proxy.parent = NULL;
5062 socket_proxy.last_change = now.tv_sec;
5063 socket_proxy.id = "LUA-SOCKET";
5064 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
5065 socket_proxy.maxconn = 0;
5066 socket_proxy.accept = NULL;
5067 socket_proxy.options2 |= PR_O2_INDEPSTR;
5068 socket_proxy.srv = NULL;
5069 socket_proxy.conn_retries = 0;
5070 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
5072 /* Init TCP server: unchanged parameters */
5073 memset(&socket_tcp, 0, sizeof(socket_tcp));
5074 socket_tcp.next = NULL;
5075 socket_tcp.proxy = &socket_proxy;
5076 socket_tcp.obj_type = OBJ_TYPE_SERVER;
5077 LIST_INIT(&socket_tcp.actconns);
5078 LIST_INIT(&socket_tcp.pendconns);
5079 LIST_INIT(&socket_tcp.priv_conns);
5080 LIST_INIT(&socket_tcp.idle_conns);
5081 LIST_INIT(&socket_tcp.safe_conns);
5082 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
5083 socket_tcp.last_change = 0;
5084 socket_tcp.id = "LUA-TCP-CONN";
5085 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5086 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5087 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
5089 /* XXX: Copy default parameter from default server,
5090 * but the default server is not initialized.
5092 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
5093 socket_tcp.minconn = socket_proxy.defsrv.minconn;
5094 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
5095 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
5096 socket_tcp.onerror = socket_proxy.defsrv.onerror;
5097 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5098 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
5099 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5100 socket_tcp.uweight = socket_proxy.defsrv.iweight;
5101 socket_tcp.iweight = socket_proxy.defsrv.iweight;
5103 socket_tcp.check.status = HCHK_STATUS_INI;
5104 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
5105 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
5106 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
5107 socket_tcp.check.server = &socket_tcp;
5109 socket_tcp.agent.status = HCHK_STATUS_INI;
5110 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
5111 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
5112 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
5113 socket_tcp.agent.server = &socket_tcp;
5115 socket_tcp.xprt = &raw_sock;
5118 /* Init TCP server: unchanged parameters */
5119 memset(&socket_ssl, 0, sizeof(socket_ssl));
5120 socket_ssl.next = NULL;
5121 socket_ssl.proxy = &socket_proxy;
5122 socket_ssl.obj_type = OBJ_TYPE_SERVER;
5123 LIST_INIT(&socket_ssl.actconns);
5124 LIST_INIT(&socket_ssl.pendconns);
5125 LIST_INIT(&socket_ssl.priv_conns);
5126 LIST_INIT(&socket_ssl.idle_conns);
5127 LIST_INIT(&socket_ssl.safe_conns);
5128 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
5129 socket_ssl.last_change = 0;
5130 socket_ssl.id = "LUA-SSL-CONN";
5131 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5132 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5133 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
5135 /* XXX: Copy default parameter from default server,
5136 * but the default server is not initialized.
5138 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
5139 socket_ssl.minconn = socket_proxy.defsrv.minconn;
5140 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
5141 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
5142 socket_ssl.onerror = socket_proxy.defsrv.onerror;
5143 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5144 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
5145 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5146 socket_ssl.uweight = socket_proxy.defsrv.iweight;
5147 socket_ssl.iweight = socket_proxy.defsrv.iweight;
5149 socket_ssl.check.status = HCHK_STATUS_INI;
5150 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
5151 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
5152 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
5153 socket_ssl.check.server = &socket_ssl;
5155 socket_ssl.agent.status = HCHK_STATUS_INI;
5156 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
5157 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
5158 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
5159 socket_ssl.agent.server = &socket_ssl;
5161 socket_ssl.use_ssl = 1;
5162 socket_ssl.xprt = &ssl_sock;
5164 for (idx = 0; args[idx] != NULL; idx++) {
5165 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
5168 * If the keyword is not known, we can search in the registered
5169 * server keywords. This is usefull to configure special SSL
5170 * features like client certificates and ssl_verify.
5173 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
5174 if (tmp_error != 0) {
5175 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
5176 abort(); /* This must be never arrives because the command line
5177 not editable by the user. */
5183 /* Initialize SSL server. */
5184 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);