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