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