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