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