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