blob: 18c901c98b51eb2f2ddd9af12a70dc8ff35f7f16 [file] [log] [blame]
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001#include <sys/socket.h>
2
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01003#include <lauxlib.h>
4#include <lua.h>
5#include <lualib.h>
6
Thierry FOURNIER463119c2015-03-10 00:35:36 +01007#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
8#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +01009#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 FOURNIER2ba18a22015-01-23 14:07:08 +010067/* The following variables contains the reference of the different
68 * Lua classes. These references are useful for identify metadata
69 * associated with an object.
70 */
71static int class_core_ref;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010072static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010073static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010074static int class_channel_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010075
Thierry FOURNIERbd413492015-03-03 16:52:26 +010076/* Global Lua execution timeout. By default Lua, execution linked
77 * with session (actions, sample-fetches and converters) have a
78 * short timeout. Lua linked with tasks doesn't have a timeout
79 * because a task may remain alive during all the haproxy execution.
80 */
81static unsigned int hlua_timeout_session = 4000; /* session timeout. */
82static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
83
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010084/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
85 * it is used for preventing infinite loops.
86 *
87 * I test the scheer with an infinite loop containing one incrementation
88 * and one test. I run this loop between 10 seconds, I raise a ceil of
89 * 710M loops from one interrupt each 9000 instructions, so I fix the value
90 * to one interrupt each 10 000 instructions.
91 *
92 * configured | Number of
93 * instructions | loops executed
94 * between two | in milions
95 * forced yields |
96 * ---------------+---------------
97 * 10 | 160
98 * 500 | 670
99 * 1000 | 680
100 * 5000 | 700
101 * 7000 | 700
102 * 8000 | 700
103 * 9000 | 710 <- ceil
104 * 10000 | 710
105 * 100000 | 710
106 * 1000000 | 710
107 *
108 */
109static unsigned int hlua_nb_instruction = 10000;
110
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100111/* These functions converts types between HAProxy internal args or
112 * sample and LUA types. Another function permits to check if the
113 * LUA stack contains arguments according with an required ARG_T
114 * format.
115 */
116static int hlua_arg2lua(lua_State *L, const struct arg *arg);
117static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
118__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp, unsigned int mask);
119static int hlua_smp2lua(lua_State *L, const struct sample *smp);
120static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
121
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100122/* Used to check an Lua function type in the stack. It creates and
123 * returns a reference of the function. This function throws an
124 * error if the rgument is not a "function".
125 */
126__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
127{
128 if (!lua_isfunction(L, argno)) {
129 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
130 WILL_LJMP(luaL_argerror(L, argno, msg));
131 }
132 lua_pushvalue(L, argno);
133 return luaL_ref(L, LUA_REGISTRYINDEX);
134}
135
136/* The three following functions are useful for adding entries
137 * in a table. These functions takes a string and respectively an
138 * integer, a string or a function and add it to the table in the
139 * top of the stack.
140 *
141 * These functions throws an error if no more stack size is
142 * available.
143 */
144__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100145 int value)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100146{
147 if (!lua_checkstack(L, 2))
148 WILL_LJMP(luaL_error(L, "full stack"));
149 lua_pushstring(L, name);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100150 lua_pushinteger(L, value);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100151 lua_settable(L, -3);
152}
153__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
154 const char *value)
155{
156 if (!lua_checkstack(L, 2))
157 WILL_LJMP(luaL_error(L, "full stack"));
158 lua_pushstring(L, name);
159 lua_pushstring(L, value);
160 lua_settable(L, -3);
161}
162__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
163 int (*function)(lua_State *L))
164{
165 if (!lua_checkstack(L, 2))
166 WILL_LJMP(luaL_error(L, "full stack"));
167 lua_pushstring(L, name);
168 lua_pushcclosure(L, function, 0);
169 lua_settable(L, -3);
170}
171
172/* This function check the number of arguments available in the
173 * stack. If the number of arguments available is not the same
174 * then <nb> an error is throwed.
175 */
176__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
177{
178 if (lua_gettop(L) == nb)
179 return;
180 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
181}
182
183/* Return true if the data in stack[<ud>] is an object of
184 * type <class_ref>.
185 */
186static int hlua_udataistype(lua_State *L, int ud, int class_ref)
187{
188 void *p = lua_touserdata(L, ud);
189 if (!p)
190 return 0;
191
192 if (!lua_getmetatable(L, ud))
193 return 0;
194
195 lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
196 if (!lua_rawequal(L, -1, -2)) {
197 lua_pop(L, 2);
198 return 0;
199 }
200
201 lua_pop(L, 2);
202 return 1;
203}
204
205/* Return an object of the expected type, or throws an error. */
206__LJMP static void *hlua_checkudata(lua_State *L, int ud, int class_ref)
207{
208 if (!hlua_udataistype(L, ud, class_ref))
209 WILL_LJMP(luaL_argerror(L, 1, NULL));
210 return lua_touserdata(L, ud);
211}
212
213/* This fucntion push an error string prefixed by the file name
214 * and the line number where the error is encountered.
215 */
216static int hlua_pusherror(lua_State *L, const char *fmt, ...)
217{
218 va_list argp;
219 va_start(argp, fmt);
220 luaL_where(L, 1);
221 lua_pushvfstring(L, fmt, argp);
222 va_end(argp);
223 lua_concat(L, 2);
224 return 1;
225}
226
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100227/* This function register a new signal. "lua" is the current lua
228 * execution context. It contains a pointer to the associated task.
229 * "link" is a list head attached to an other task that must be wake
230 * the lua task if an event occurs. This is useful with external
231 * events like TCP I/O or sleep functions. This funcion allocate
232 * memory for the signal.
233 */
234static int hlua_com_new(struct hlua *lua, struct list *link)
235{
236 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
237 if (!com)
238 return 0;
239 LIST_ADDQ(&lua->com, &com->purge_me);
240 LIST_ADDQ(link, &com->wake_me);
241 com->task = lua->task;
242 return 1;
243}
244
245/* This function purge all the pending signals when the LUA execution
246 * is finished. This prevent than a coprocess try to wake a deleted
247 * task. This function remove the memory associated to the signal.
248 */
249static void hlua_com_purge(struct hlua *lua)
250{
251 struct hlua_com *com, *back;
252
253 /* Delete all pending communication signals. */
254 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
255 LIST_DEL(&com->purge_me);
256 LIST_DEL(&com->wake_me);
257 pool_free2(pool2_hlua_com, com);
258 }
259}
260
261/* This function sends signals. It wakes all the tasks attached
262 * to a list head, and remove the signal, and free the used
263 * memory.
264 */
265static void hlua_com_wake(struct list *wake)
266{
267 struct hlua_com *com, *back;
268
269 /* Wake task and delete all pending communication signals. */
270 list_for_each_entry_safe(com, back, wake, wake_me) {
271 LIST_DEL(&com->purge_me);
272 LIST_DEL(&com->wake_me);
273 task_wakeup(com->task, TASK_WOKEN_MSG);
274 pool_free2(pool2_hlua_com, com);
275 }
276}
277
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100278/* This functions is used with sample fetch and converters. It
279 * converts the HAProxy configuration argument in a lua stack
280 * values.
281 *
282 * It takes an array of "arg", and each entry of the array is
283 * converted and pushed in the LUA stack.
284 */
285static int hlua_arg2lua(lua_State *L, const struct arg *arg)
286{
287 switch (arg->type) {
288 case ARGT_SINT:
289 lua_pushinteger(L, arg->data.sint);
290 break;
291
292 case ARGT_UINT:
293 case ARGT_TIME:
294 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100295 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100296 break;
297
298 case ARGT_STR:
299 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
300 break;
301
302 case ARGT_IPV4:
303 case ARGT_IPV6:
304 case ARGT_MSK4:
305 case ARGT_MSK6:
306 case ARGT_FE:
307 case ARGT_BE:
308 case ARGT_TAB:
309 case ARGT_SRV:
310 case ARGT_USR:
311 case ARGT_MAP:
312 default:
313 lua_pushnil(L);
314 break;
315 }
316 return 1;
317}
318
319/* This function take one entrie in an LUA stack at the index "ud",
320 * and try to convert it in an HAProxy argument entry. This is useful
321 * with sample fetch wrappers. The input arguments are gived to the
322 * lua wrapper and converted as arg list by thi function.
323 */
324static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
325{
326 switch (lua_type(L, ud)) {
327
328 case LUA_TNUMBER:
329 case LUA_TBOOLEAN:
330 arg->type = ARGT_SINT;
331 arg->data.sint = lua_tointeger(L, ud);
332 break;
333
334 case LUA_TSTRING:
335 arg->type = ARGT_STR;
336 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
337 break;
338
339 case LUA_TUSERDATA:
340 case LUA_TNIL:
341 case LUA_TTABLE:
342 case LUA_TFUNCTION:
343 case LUA_TTHREAD:
344 case LUA_TLIGHTUSERDATA:
345 arg->type = ARGT_SINT;
346 arg->data.uint = 0;
347 break;
348 }
349 return 1;
350}
351
352/* the following functions are used to convert a struct sample
353 * in Lua type. This useful to convert the return of the
354 * fetchs or converters.
355 */
356static int hlua_smp2lua(lua_State *L, const struct sample *smp)
357{
358 switch (smp->type) {
359 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100360 case SMP_T_BOOL:
361 case SMP_T_UINT:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100362 lua_pushinteger(L, smp->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100363 break;
364
365 case SMP_T_BIN:
366 case SMP_T_STR:
367 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
368 break;
369
370 case SMP_T_METH:
371 switch (smp->data.meth.meth) {
372 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
373 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
374 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
375 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
376 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
377 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
378 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
379 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
380 case HTTP_METH_OTHER:
381 lua_pushlstring(L, smp->data.meth.str.str, smp->data.meth.str.len);
382 break;
383 default:
384 lua_pushnil(L);
385 break;
386 }
387 break;
388
389 case SMP_T_IPV4:
390 case SMP_T_IPV6:
391 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
392 default:
393 lua_pushnil(L);
394 break;
395 }
396 return 1;
397}
398
399/* the following functions are used to convert an Lua type in a
400 * struct sample. This is useful to provide data from a converter
401 * to the LUA code.
402 */
403static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
404{
405 switch (lua_type(L, ud)) {
406
407 case LUA_TNUMBER:
408 smp->type = SMP_T_SINT;
409 smp->data.sint = lua_tointeger(L, ud);
410 break;
411
412
413 case LUA_TBOOLEAN:
414 smp->type = SMP_T_BOOL;
415 smp->data.uint = lua_toboolean(L, ud);
416 break;
417
418 case LUA_TSTRING:
419 smp->type = SMP_T_STR;
420 smp->flags |= SMP_F_CONST;
421 smp->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.str.len);
422 break;
423
424 case LUA_TUSERDATA:
425 case LUA_TNIL:
426 case LUA_TTABLE:
427 case LUA_TFUNCTION:
428 case LUA_TTHREAD:
429 case LUA_TLIGHTUSERDATA:
430 smp->type = SMP_T_BOOL;
431 smp->data.uint = 0;
432 break;
433 }
434 return 1;
435}
436
437/* This function check the "argp" builded by another conversion function
438 * is in accord with the expected argp defined by the "mask". The fucntion
439 * returns true or false. It can be adjust the types if there compatibles.
440 */
441__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp, unsigned int mask)
442{
443 int min_arg;
444 int idx;
445
446 idx = 0;
447 min_arg = ARGM(mask);
448 mask >>= ARGM_BITS;
449
450 while (1) {
451
452 /* Check oversize. */
453 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100454 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100455 }
456
457 /* Check for mandatory arguments. */
458 if (argp[idx].type == ARGT_STOP) {
459 if (idx + 1 < min_arg)
460 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
461 return 0;
462 }
463
464 /* Check for exceed the number of requiered argument. */
465 if ((mask & ARGT_MASK) == ARGT_STOP &&
466 argp[idx].type != ARGT_STOP) {
467 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
468 }
469
470 if ((mask & ARGT_MASK) == ARGT_STOP &&
471 argp[idx].type == ARGT_STOP) {
472 return 0;
473 }
474
475 /* Compatibility mask. */
476 switch (argp[idx].type) {
477 case ARGT_SINT:
478 switch (mask & ARGT_MASK) {
479 case ARGT_UINT: argp[idx].type = mask & ARGT_MASK; break;
480 case ARGT_TIME: argp[idx].type = mask & ARGT_MASK; break;
481 case ARGT_SIZE: argp[idx].type = mask & ARGT_MASK; break;
482 }
483 break;
484 }
485
486 /* Check for type of argument. */
487 if ((mask & ARGT_MASK) != argp[idx].type) {
488 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
489 arg_type_names[(mask & ARGT_MASK)],
490 arg_type_names[argp[idx].type & ARGT_MASK]);
491 WILL_LJMP(luaL_argerror(L, first + idx, msg));
492 }
493
494 /* Next argument. */
495 mask >>= ARGT_BITS;
496 idx++;
497 }
498}
499
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100500/*
501 * The following functions are used to make correspondance between the the
502 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100503 *
504 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100505 * - hlua_sethlua : create the association between hlua context and lua_state.
506 */
507static inline struct hlua *hlua_gethlua(lua_State *L)
508{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100509 struct hlua **hlua = lua_getextraspace(L);
510 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100511}
512static inline void hlua_sethlua(struct hlua *hlua)
513{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100514 struct hlua **hlua_store = lua_getextraspace(hlua->T);
515 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100516}
517
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100518/* This function just ensure that the yield will be always
519 * returned with a timeout and permit to set some flags
520 */
521__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100522 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100523{
524 struct hlua *hlua = hlua_gethlua(L);
525
526 /* Set the wake timeout. If timeout is required, we set
527 * the expiration time.
528 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100529 hlua->wake_time = tick_first(timeout, hlua->expire);
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100530
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100531 hlua->flags |= flags;
532
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100533 /* Process the yield. */
534 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
535}
536
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100537/* This function initialises the Lua environment stored in the session.
538 * It must be called at the start of the session. This function creates
539 * an LUA coroutine. It can not be use to crete the main LUA context.
540 */
541int hlua_ctx_init(struct hlua *lua, struct task *task)
542{
543 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100544 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100545 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100546 lua->T = lua_newthread(gL.T);
547 if (!lua->T) {
548 lua->Tref = LUA_REFNIL;
549 return 0;
550 }
551 hlua_sethlua(lua);
552 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
553 lua->task = task;
554 return 1;
555}
556
557/* Used to destroy the Lua coroutine when the attached session or task
558 * is destroyed. The destroy also the memory context. The struct "lua"
559 * is not freed.
560 */
561void hlua_ctx_destroy(struct hlua *lua)
562{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100563 if (!lua->T)
564 return;
565
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100566 /* Purge all the pending signals. */
567 hlua_com_purge(lua);
568
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100569 /* The thread is garbage collected by Lua. */
570 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
571 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
572}
573
574/* This function is used to restore the Lua context when a coroutine
575 * fails. This function copy the common memory between old coroutine
576 * and the new coroutine. The old coroutine is destroyed, and its
577 * replaced by the new coroutine.
578 * If the flag "keep_msg" is set, the last entry of the old is assumed
579 * as string error message and it is copied in the new stack.
580 */
581static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
582{
583 lua_State *T;
584 int new_ref;
585
586 /* Renew the main LUA stack doesn't have sense. */
587 if (lua == &gL)
588 return 0;
589
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100590 /* New Lua coroutine. */
591 T = lua_newthread(gL.T);
592 if (!T)
593 return 0;
594
595 /* Copy last error message. */
596 if (keep_msg)
597 lua_xmove(lua->T, T, 1);
598
599 /* Copy data between the coroutines. */
600 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
601 lua_xmove(lua->T, T, 1);
602 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
603
604 /* Destroy old data. */
605 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
606
607 /* The thread is garbage collected by Lua. */
608 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
609
610 /* Fill the struct with the new coroutine values. */
611 lua->Mref = new_ref;
612 lua->T = T;
613 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
614
615 /* Set context. */
616 hlua_sethlua(lua);
617
618 return 1;
619}
620
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100621void hlua_hook(lua_State *L, lua_Debug *ar)
622{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100623 struct hlua *hlua = hlua_gethlua(L);
624
625 /* Lua cannot yield when its returning from a function,
626 * so, we can fix the interrupt hook to 1 instruction,
627 * expecting that the function is finnished.
628 */
629 if (lua_gethookmask(L) & LUA_MASKRET) {
630 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
631 return;
632 }
633
634 /* restore the interrupt condition. */
635 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
636
637 /* If we interrupt the Lua processing in yieldable state, we yield.
638 * If the state is not yieldable, trying yield causes an error.
639 */
640 if (lua_isyieldable(L))
641 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
642
643 /* If we cannot yield, check the timeout. */
644 if (tick_is_expired(hlua->expire, now_ms)) {
645 lua_pushfstring(L, "execution timeout");
646 WILL_LJMP(lua_error(L));
647 }
648
649 /* Try to interrupt the process at the end of the current
650 * unyieldable function.
651 */
652 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100653}
654
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100655/* This function start or resumes the Lua stack execution. If the flag
656 * "yield_allowed" if no set and the LUA stack execution returns a yield
657 * The function return an error.
658 *
659 * The function can returns 4 values:
660 * - HLUA_E_OK : The execution is terminated without any errors.
661 * - HLUA_E_AGAIN : The execution must continue at the next associated
662 * task wakeup.
663 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
664 * the top of the stack.
665 * - HLUA_E_ERR : An error has occured without error message.
666 *
667 * If an error occured, the stack is renewed and it is ready to run new
668 * LUA code.
669 */
670static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
671{
672 int ret;
673 const char *msg;
674
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100675 HLUA_SET_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100676
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100677 /* If we want to resume the task, then check first the execution timeout.
678 * if it is reached, we can interrupt the Lua processing.
679 */
680 if (tick_is_expired(lua->expire, now_ms))
681 goto timeout_reached;
682
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100683resume_execution:
684
685 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
686 * instructions. it is used for preventing infinite loops.
687 */
688 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
689
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +0100690 /* Remove all flags except the running flags. */
691 lua->flags = HLUA_RUN;
692
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100693 /* Call the function. */
694 ret = lua_resume(lua->T, gL.T, lua->nargs);
695 switch (ret) {
696
697 case LUA_OK:
698 ret = HLUA_E_OK;
699 break;
700
701 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100702 /* Check if the execution timeout is expired. It it is the case, we
703 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100704 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100705 if (tick_is_expired(lua->expire, now_ms)) {
706
707timeout_reached:
708
709 lua_settop(lua->T, 0); /* Empty the stack. */
710 if (!lua_checkstack(lua->T, 1)) {
711 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100712 break;
713 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100714 lua_pushfstring(lua->T, "execution timeout");
715 ret = HLUA_E_ERRMSG;
716 break;
717 }
718 /* Process the forced yield. if the general yield is not allowed or
719 * if no task were associated this the current Lua execution
720 * coroutine, we resume the execution. Else we want to return in the
721 * scheduler and we want to be waked up again, to continue the
722 * current Lua execution. So we schedule our own task.
723 */
724 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100725 if (!yield_allowed || !lua->task)
726 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100727 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100728 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100729 if (!yield_allowed) {
730 lua_settop(lua->T, 0); /* Empty the stack. */
731 if (!lua_checkstack(lua->T, 1)) {
732 ret = HLUA_E_ERR;
733 break;
734 }
735 lua_pushfstring(lua->T, "yield not allowed");
736 ret = HLUA_E_ERRMSG;
737 break;
738 }
739 ret = HLUA_E_AGAIN;
740 break;
741
742 case LUA_ERRRUN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100743 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100744 if (!lua_checkstack(lua->T, 1)) {
745 ret = HLUA_E_ERR;
746 break;
747 }
748 msg = lua_tostring(lua->T, -1);
749 lua_settop(lua->T, 0); /* Empty the stack. */
750 lua_pop(lua->T, 1);
751 if (msg)
752 lua_pushfstring(lua->T, "runtime error: %s", msg);
753 else
754 lua_pushfstring(lua->T, "unknown runtime error");
755 ret = HLUA_E_ERRMSG;
756 break;
757
758 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100759 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100760 lua_settop(lua->T, 0); /* Empty the stack. */
761 if (!lua_checkstack(lua->T, 1)) {
762 ret = HLUA_E_ERR;
763 break;
764 }
765 lua_pushfstring(lua->T, "out of memory error");
766 ret = HLUA_E_ERRMSG;
767 break;
768
769 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100770 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100771 if (!lua_checkstack(lua->T, 1)) {
772 ret = HLUA_E_ERR;
773 break;
774 }
775 msg = lua_tostring(lua->T, -1);
776 lua_settop(lua->T, 0); /* Empty the stack. */
777 lua_pop(lua->T, 1);
778 if (msg)
779 lua_pushfstring(lua->T, "message handler error: %s", msg);
780 else
781 lua_pushfstring(lua->T, "message handler error");
782 ret = HLUA_E_ERRMSG;
783 break;
784
785 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100786 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100787 lua_settop(lua->T, 0); /* Empty the stack. */
788 if (!lua_checkstack(lua->T, 1)) {
789 ret = HLUA_E_ERR;
790 break;
791 }
792 lua_pushfstring(lua->T, "unknonwn error");
793 ret = HLUA_E_ERRMSG;
794 break;
795 }
796
797 switch (ret) {
798 case HLUA_E_AGAIN:
799 break;
800
801 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100802 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100803 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100804 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100805 break;
806
807 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100808 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100809 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100810 hlua_ctx_renew(lua, 0);
811 break;
812
813 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100814 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100815 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100816 break;
817 }
818
819 return ret;
820}
821
Thierry FOURNIER83758bb2015-02-04 13:21:04 +0100822/* This function is an LUA binding. It provides a function
823 * for deleting ACL from a referenced ACL file.
824 */
825__LJMP static int hlua_del_acl(lua_State *L)
826{
827 const char *name;
828 const char *key;
829 struct pat_ref *ref;
830
831 MAY_LJMP(check_args(L, 2, "del_acl"));
832
833 name = MAY_LJMP(luaL_checkstring(L, 1));
834 key = MAY_LJMP(luaL_checkstring(L, 2));
835
836 ref = pat_ref_lookup(name);
837 if (!ref)
838 WILL_LJMP(luaL_error(L, "'del_acl': unkown acl file '%s'", name));
839
840 pat_ref_delete(ref, key);
841 return 0;
842}
843
844/* This function is an LUA binding. It provides a function
845 * for deleting map entry from a referenced map file.
846 */
847static int hlua_del_map(lua_State *L)
848{
849 const char *name;
850 const char *key;
851 struct pat_ref *ref;
852
853 MAY_LJMP(check_args(L, 2, "del_map"));
854
855 name = MAY_LJMP(luaL_checkstring(L, 1));
856 key = MAY_LJMP(luaL_checkstring(L, 2));
857
858 ref = pat_ref_lookup(name);
859 if (!ref)
860 WILL_LJMP(luaL_error(L, "'del_map': unkown acl file '%s'", name));
861
862 pat_ref_delete(ref, key);
863 return 0;
864}
865
866/* This function is an LUA binding. It provides a function
867 * for adding ACL pattern from a referenced ACL file.
868 */
869static int hlua_add_acl(lua_State *L)
870{
871 const char *name;
872 const char *key;
873 struct pat_ref *ref;
874
875 MAY_LJMP(check_args(L, 2, "add_acl"));
876
877 name = MAY_LJMP(luaL_checkstring(L, 1));
878 key = MAY_LJMP(luaL_checkstring(L, 2));
879
880 ref = pat_ref_lookup(name);
881 if (!ref)
882 WILL_LJMP(luaL_error(L, "'add_acl': unkown acl file '%s'", name));
883
884 if (pat_ref_find_elt(ref, key) == NULL)
885 pat_ref_add(ref, key, NULL, NULL);
886 return 0;
887}
888
889/* This function is an LUA binding. It provides a function
890 * for setting map pattern and sample from a referenced map
891 * file.
892 */
893static int hlua_set_map(lua_State *L)
894{
895 const char *name;
896 const char *key;
897 const char *value;
898 struct pat_ref *ref;
899
900 MAY_LJMP(check_args(L, 3, "set_map"));
901
902 name = MAY_LJMP(luaL_checkstring(L, 1));
903 key = MAY_LJMP(luaL_checkstring(L, 2));
904 value = MAY_LJMP(luaL_checkstring(L, 3));
905
906 ref = pat_ref_lookup(name);
907 if (!ref)
908 WILL_LJMP(luaL_error(L, "'set_map': unkown map file '%s'", name));
909
910 if (pat_ref_find_elt(ref, key) != NULL)
911 pat_ref_set(ref, key, value, NULL);
912 else
913 pat_ref_add(ref, key, value, NULL);
914 return 0;
915}
916
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100917/* A class is a lot of memory that contain data. This data can be a table,
918 * an integer or user data. This data is associated with a metatable. This
919 * metatable have an original version registred in the global context with
920 * the name of the object (_G[<name>] = <metable> ).
921 *
922 * A metable is a table that modify the standard behavior of a standard
923 * access to the associated data. The entries of this new metatable are
924 * defined as is:
925 *
926 * http://lua-users.org/wiki/MetatableEvents
927 *
928 * __index
929 *
930 * we access an absent field in a table, the result is nil. This is
931 * true, but it is not the whole truth. Actually, such access triggers
932 * the interpreter to look for an __index metamethod: If there is no
933 * such method, as usually happens, then the access results in nil;
934 * otherwise, the metamethod will provide the result.
935 *
936 * Control 'prototype' inheritance. When accessing "myTable[key]" and
937 * the key does not appear in the table, but the metatable has an __index
938 * property:
939 *
940 * - if the value is a function, the function is called, passing in the
941 * table and the key; the return value of that function is returned as
942 * the result.
943 *
944 * - if the value is another table, the value of the key in that table is
945 * asked for and returned (and if it doesn't exist in that table, but that
946 * table's metatable has an __index property, then it continues on up)
947 *
948 * - Use "rawget(myTable,key)" to skip this metamethod.
949 *
950 * http://www.lua.org/pil/13.4.1.html
951 *
952 * __newindex
953 *
954 * Like __index, but control property assignment.
955 *
956 * __mode - Control weak references. A string value with one or both
957 * of the characters 'k' and 'v' which specifies that the the
958 * keys and/or values in the table are weak references.
959 *
960 * __call - Treat a table like a function. When a table is followed by
961 * parenthesis such as "myTable( 'foo' )" and the metatable has
962 * a __call key pointing to a function, that function is invoked
963 * (passing any specified arguments) and the return value is
964 * returned.
965 *
966 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
967 * called, if the metatable for myTable has a __metatable
968 * key, the value of that key is returned instead of the
969 * actual metatable.
970 *
971 * __tostring - Control string representation. When the builtin
972 * "tostring( myTable )" function is called, if the metatable
973 * for myTable has a __tostring property set to a function,
974 * that function is invoked (passing myTable to it) and the
975 * return value is used as the string representation.
976 *
977 * __len - Control table length. When the table length is requested using
978 * the length operator ( '#' ), if the metatable for myTable has
979 * a __len key pointing to a function, that function is invoked
980 * (passing myTable to it) and the return value used as the value
981 * of "#myTable".
982 *
983 * __gc - Userdata finalizer code. When userdata is set to be garbage
984 * collected, if the metatable has a __gc field pointing to a
985 * function, that function is first invoked, passing the userdata
986 * to it. The __gc metamethod is not called for tables.
987 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
988 *
989 * Special metamethods for redefining standard operators:
990 * http://www.lua.org/pil/13.1.html
991 *
992 * __add "+"
993 * __sub "-"
994 * __mul "*"
995 * __div "/"
996 * __unm "!"
997 * __pow "^"
998 * __concat ".."
999 *
1000 * Special methods for redfining standar relations
1001 * http://www.lua.org/pil/13.2.html
1002 *
1003 * __eq "=="
1004 * __lt "<"
1005 * __le "<="
1006 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001007
1008/*
1009 *
1010 *
1011 * Class Socket
1012 *
1013 *
1014 */
1015
1016__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1017{
1018 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1019}
1020
1021/* This function is the handler called for each I/O on the established
1022 * connection. It is used for notify space avalaible to send or data
1023 * received.
1024 */
1025static void hlua_socket_handler(struct stream_interface *si)
1026{
1027 struct appctx *appctx = objt_appctx(si->end);
1028 struct connection *c = objt_conn(si->ib->cons->end);
1029
1030 /* Wakeup the main session if the client connection is closed. */
1031 if (!c || channel_output_closed(si->ib) || channel_input_closed(si->ob)) {
1032 if (appctx->ctx.hlua.socket) {
1033 appctx->ctx.hlua.socket->s = NULL;
1034 appctx->ctx.hlua.socket = NULL;
1035 }
1036 si_shutw(si);
1037 si_shutr(si);
1038 si->ib->flags |= CF_READ_NULL;
1039 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1040 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1041 return;
1042 }
1043
1044 if (!(c->flags & CO_FL_CONNECTED))
1045 return;
1046
1047 /* This function is called after the connect. */
1048 appctx->ctx.hlua.connected = 1;
1049
1050 /* Wake the tasks which wants to write if the buffer have avalaible space. */
1051 if (channel_may_recv(si->ob))
1052 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1053
1054 /* Wake the tasks which wants to read if the buffer contains data. */
1055 if (channel_is_empty(si->ib))
1056 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1057}
1058
1059/* This function is called when the "struct session" is destroyed.
1060 * Remove the link from the object to this session.
1061 * Wake all the pending signals.
1062 */
1063static void hlua_socket_release(struct stream_interface *si)
1064{
1065 struct appctx *appctx = objt_appctx(si->end);
1066
1067 /* Remove my link in the original object. */
1068 if (appctx->ctx.hlua.socket)
1069 appctx->ctx.hlua.socket->s = NULL;
1070
1071 /* Wake all the task waiting for me. */
1072 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1073 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1074}
1075
1076/* If the garbage collectio of the object is launch, nobody
1077 * uses this object. If the session does not exists, just quit.
1078 * Send the shutdown signal to the session. In some cases,
1079 * pending signal can rest in the read and write lists. destroy
1080 * it.
1081 */
1082__LJMP static int hlua_socket_gc(lua_State *L)
1083{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001084 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001085 struct appctx *appctx;
1086
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001087 MAY_LJMP(check_args(L, 1, "__gc"));
1088
1089 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001090 if (!socket->s)
1091 return 0;
1092
1093 /* Remove all reference between the Lua stack and the coroutine session. */
1094 appctx = objt_appctx(socket->s->si[0].end);
1095 session_shutdown(socket->s, SN_ERR_KILLED);
1096 socket->s = NULL;
1097 appctx->ctx.hlua.socket = NULL;
1098
1099 return 0;
1100}
1101
1102/* The close function send shutdown signal and break the
1103 * links between the session and the object.
1104 */
1105__LJMP static int hlua_socket_close(lua_State *L)
1106{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001107 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001108 struct appctx *appctx;
1109
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001110 MAY_LJMP(check_args(L, 1, "close"));
1111
1112 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001113 if (!socket->s)
1114 return 0;
1115
1116 /* Close the session and remove the associated stop task. */
1117 session_shutdown(socket->s, SN_ERR_KILLED);
1118 appctx = objt_appctx(socket->s->si[0].end);
1119 appctx->ctx.hlua.socket = NULL;
1120 socket->s = NULL;
1121
1122 return 0;
1123}
1124
1125/* This Lua function assumes that the stack contain three parameters.
1126 * 1 - USERDATA containing a struct socket
1127 * 2 - INTEGER with values of the macro defined below
1128 * If the integer is -1, we must read at most one line.
1129 * If the integer is -2, we ust read all the data until the
1130 * end of the stream.
1131 * If the integer is positive value, we must read a number of
1132 * bytes corresponding to this value.
1133 */
1134#define HLSR_READ_LINE (-1)
1135#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001136__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001137{
1138 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1139 int wanted = lua_tointeger(L, 2);
1140 struct hlua *hlua = hlua_gethlua(L);
1141 struct appctx *appctx;
1142 int len;
1143 int nblk;
1144 char *blk1;
1145 int len1;
1146 char *blk2;
1147 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001148 int skip_at_end = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001149
1150 /* Check if this lua stack is schedulable. */
1151 if (!hlua || !hlua->task)
1152 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1153 "'frontend', 'backend' or 'task'"));
1154
1155 /* check for connection closed. If some data where read, return it. */
1156 if (!socket->s)
1157 goto connection_closed;
1158
1159 if (wanted == HLSR_READ_LINE) {
1160
1161 /* Read line. */
1162 nblk = bo_getline_nc(socket->s->si[0].ob, &blk1, &len1, &blk2, &len2);
1163 if (nblk < 0) /* Connection close. */
1164 goto connection_closed;
1165 if (nblk == 0) /* No data avalaible. */
1166 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001167
1168 /* remove final \r\n. */
1169 if (nblk == 1) {
1170 if (blk1[len1-1] == '\n') {
1171 len1--;
1172 skip_at_end++;
1173 if (blk1[len1-1] == '\r') {
1174 len1--;
1175 skip_at_end++;
1176 }
1177 }
1178 }
1179 else {
1180 if (blk2[len2-1] == '\n') {
1181 len2--;
1182 skip_at_end++;
1183 if (blk2[len2-1] == '\r') {
1184 len2--;
1185 skip_at_end++;
1186 }
1187 }
1188 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001189 }
1190
1191 else if (wanted == HLSR_READ_ALL) {
1192
1193 /* Read all the available data. */
1194 nblk = bo_getblk_nc(socket->s->si[0].ob, &blk1, &len1, &blk2, &len2);
1195 if (nblk < 0) /* Connection close. */
1196 goto connection_closed;
1197 if (nblk == 0) /* No data avalaible. */
1198 goto connection_empty;
1199 }
1200
1201 else {
1202
1203 /* Read a block of data. */
1204 nblk = bo_getblk_nc(socket->s->si[0].ob, &blk1, &len1, &blk2, &len2);
1205 if (nblk < 0) /* Connection close. */
1206 goto connection_closed;
1207 if (nblk == 0) /* No data avalaible. */
1208 goto connection_empty;
1209
1210 if (len1 > wanted) {
1211 nblk = 1;
1212 len1 = wanted;
1213 } if (nblk == 2 && len1 + len2 > wanted)
1214 len2 = wanted - len1;
1215 }
1216
1217 len = len1;
1218
1219 luaL_addlstring(&socket->b, blk1, len1);
1220 if (nblk == 2) {
1221 len += len2;
1222 luaL_addlstring(&socket->b, blk2, len2);
1223 }
1224
1225 /* Consume data. */
Thierry FOURNIER00543922015-03-09 18:35:06 +01001226 bo_skip(socket->s->si[0].ob, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001227
1228 /* Don't wait anything. */
1229 si_update(&socket->s->si[0]);
1230
1231 /* If the pattern reclaim to read all the data
1232 * in the connection, got out.
1233 */
1234 if (wanted == HLSR_READ_ALL)
1235 goto connection_empty;
1236 else if (wanted >= 0 && len < wanted)
1237 goto connection_empty;
1238
1239 /* Return result. */
1240 luaL_pushresult(&socket->b);
1241 return 1;
1242
1243connection_closed:
1244
1245 /* If the buffer containds data. */
1246 if (socket->b.n > 0) {
1247 luaL_pushresult(&socket->b);
1248 return 1;
1249 }
1250 lua_pushnil(L);
1251 lua_pushstring(L, "connection closed.");
1252 return 2;
1253
1254connection_empty:
1255
1256 appctx = objt_appctx(socket->s->si[0].end);
1257 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1258 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001259 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001260 return 0;
1261}
1262
1263/* This Lus function gets two parameters. The first one can be string
1264 * or a number. If the string is "*l", the user require one line. If
1265 * the string is "*a", the user require all the content of the stream.
1266 * If the value is a number, the user require a number of bytes equal
1267 * to the value. The default value is "*l" (a line).
1268 *
1269 * This paraeter with a variable type is converted in integer. This
1270 * integer takes this values:
1271 * -1 : read a line
1272 * -2 : read all the stream
1273 * >0 : amount if bytes.
1274 *
1275 * The second parameter is optinal. It contains a string that must be
1276 * concatenated with the read data.
1277 */
1278__LJMP static int hlua_socket_receive(struct lua_State *L)
1279{
1280 int wanted = HLSR_READ_LINE;
1281 const char *pattern;
1282 int type;
1283 char *error;
1284 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001285 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001286
1287 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1288 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1289
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001290 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001291
1292 /* check for pattern. */
1293 if (lua_gettop(L) >= 2) {
1294 type = lua_type(L, 2);
1295 if (type == LUA_TSTRING) {
1296 pattern = lua_tostring(L, 2);
1297 if (strcmp(pattern, "*a") == 0)
1298 wanted = HLSR_READ_ALL;
1299 else if (strcmp(pattern, "*l") == 0)
1300 wanted = HLSR_READ_LINE;
1301 else {
1302 wanted = strtoll(pattern, &error, 10);
1303 if (*error != '\0')
1304 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1305 }
1306 }
1307 else if (type == LUA_TNUMBER) {
1308 wanted = lua_tointeger(L, 2);
1309 if (wanted < 0)
1310 WILL_LJMP(luaL_error(L, "Unsupported size."));
1311 }
1312 }
1313
1314 /* Set pattern. */
1315 lua_pushinteger(L, wanted);
1316 lua_replace(L, 2);
1317
1318 /* init bufffer, and fiil it wih prefix. */
1319 luaL_buffinit(L, &socket->b);
1320
1321 /* Check prefix. */
1322 if (lua_gettop(L) >= 3) {
1323 if (lua_type(L, 3) != LUA_TSTRING)
1324 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1325 pattern = lua_tolstring(L, 3, &len);
1326 luaL_addlstring(&socket->b, pattern, len);
1327 }
1328
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001329 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001330}
1331
1332/* Write the Lua input string in the output buffer.
1333 * This fucntion returns a yield if no space are available.
1334 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001335static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001336{
1337 struct hlua_socket *socket;
1338 struct hlua *hlua = hlua_gethlua(L);
1339 struct appctx *appctx;
1340 size_t buf_len;
1341 const char *buf;
1342 int len;
1343 int send_len;
1344 int sent;
1345
1346 /* Check if this lua stack is schedulable. */
1347 if (!hlua || !hlua->task)
1348 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1349 "'frontend', 'backend' or 'task'"));
1350
1351 /* Get object */
1352 socket = MAY_LJMP(hlua_checksocket(L, 1));
1353 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001354 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001355
1356 /* Check for connection close. */
1357 if (!socket->s || channel_output_closed(socket->s->req)) {
1358 lua_pushinteger(L, -1);
1359 return 1;
1360 }
1361
1362 /* Update the input buffer data. */
1363 buf += sent;
1364 send_len = buf_len - sent;
1365
1366 /* All the data are sent. */
1367 if (sent >= buf_len)
1368 return 1; /* Implicitly return the length sent. */
1369
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001370 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1371 * the request buffer if its not required.
1372 */
1373 if (socket->s->req->buf->size == 0) {
1374 if (!session_alloc_recv_buffer(socket->s, &socket->s->req->buf)) {
1375 socket->s->req->prod->flags |= SI_FL_WAIT_ROOM;
1376 goto hlua_socket_write_yield_return;
1377 }
1378 }
1379
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001380 /* Check for avalaible space. */
1381 len = buffer_total_space(socket->s->si[0].ib->buf);
1382 if (len <= 0)
1383 goto hlua_socket_write_yield_return;
1384
1385 /* send data */
1386 if (len < send_len)
1387 send_len = len;
1388 len = bi_putblk(socket->s->si[0].ib, buf+sent, send_len);
1389
1390 /* "Not enough space" (-1), "Buffer too little to contain
1391 * the data" (-2) are not expected because the available length
1392 * is tested.
1393 * Other unknown error are also not expected.
1394 */
1395 if (len <= 0) {
1396 MAY_LJMP(hlua_socket_close(L));
1397 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001398 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001399 return 1;
1400 }
1401
1402 /* update buffers. */
1403 si_update(&socket->s->si[0]);
1404 socket->s->si[0].ib->rex = TICK_ETERNITY;
1405 socket->s->si[0].ob->wex = TICK_ETERNITY;
1406
1407 /* Update length sent. */
1408 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001409 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001410
1411 /* All the data buffer is sent ? */
1412 if (sent + len >= buf_len)
1413 return 1;
1414
1415hlua_socket_write_yield_return:
1416 appctx = objt_appctx(socket->s->si[0].end);
1417 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1418 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001419 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001420 return 0;
1421}
1422
1423/* This function initiate the send of data. It just check the input
1424 * parameters and push an integer in the Lua stack that contain the
1425 * amount of data writed in the buffer. This is used by the function
1426 * "hlua_socket_write_yield" that can yield.
1427 *
1428 * The Lua function gets between 3 and 4 parameters. The first one is
1429 * the associated object. The second is a string buffer. The third is
1430 * a facultative integer that represents where is the buffer position
1431 * of the start of the data that can send. The first byte is the
1432 * position "1". The default value is "1". The fourth argument is a
1433 * facultative integer that represents where is the buffer position
1434 * of the end of the data that can send. The default is the last byte.
1435 */
1436static int hlua_socket_send(struct lua_State *L)
1437{
1438 int i;
1439 int j;
1440 const char *buf;
1441 size_t buf_len;
1442
1443 /* Check number of arguments. */
1444 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1445 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1446
1447 /* Get the string. */
1448 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1449
1450 /* Get and check j. */
1451 if (lua_gettop(L) == 4) {
1452 j = MAY_LJMP(luaL_checkinteger(L, 4));
1453 if (j < 0)
1454 j = buf_len + j + 1;
1455 if (j > buf_len)
1456 j = buf_len + 1;
1457 lua_pop(L, 1);
1458 }
1459 else
1460 j = buf_len;
1461
1462 /* Get and check i. */
1463 if (lua_gettop(L) == 3) {
1464 i = MAY_LJMP(luaL_checkinteger(L, 3));
1465 if (i < 0)
1466 i = buf_len + i + 1;
1467 if (i > buf_len)
1468 i = buf_len + 1;
1469 lua_pop(L, 1);
1470 } else
1471 i = 1;
1472
1473 /* Check bth i and j. */
1474 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001475 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001476 return 1;
1477 }
1478 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001479 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001480 return 1;
1481 }
1482 if (i == 0)
1483 i = 1;
1484 if (j == 0)
1485 j = 1;
1486
1487 /* Pop the string. */
1488 lua_pop(L, 1);
1489
1490 /* Update the buffer length. */
1491 buf += i - 1;
1492 buf_len = j - i + 1;
1493 lua_pushlstring(L, buf, buf_len);
1494
1495 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001496 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001497
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001498 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001499}
1500
1501#define SOCKET_INFO_EXPANDED_FORM "[0000:0000:0000:0000:0000:0000:0000:0000]:12345"
1502static char _socket_info_expanded_form[] = SOCKET_INFO_EXPANDED_FORM;
1503#define SOCKET_INFO_MAX_LEN (sizeof(_socket_info_expanded_form))
1504__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
1505{
1506 static char buffer[SOCKET_INFO_MAX_LEN];
1507 int ret;
1508 int len;
1509 char *p;
1510
1511 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
1512 if (ret <= 0) {
1513 lua_pushnil(L);
1514 return 1;
1515 }
1516
1517 if (ret == AF_UNIX) {
1518 lua_pushstring(L, buffer+1);
1519 return 1;
1520 }
1521 else if (ret == AF_INET6) {
1522 buffer[0] = '[';
1523 len = strlen(buffer);
1524 buffer[len] = ']';
1525 len++;
1526 buffer[len] = ':';
1527 len++;
1528 p = buffer;
1529 }
1530 else if (ret == AF_INET) {
1531 p = buffer + 1;
1532 len = strlen(p);
1533 p[len] = ':';
1534 len++;
1535 }
1536 else {
1537 lua_pushnil(L);
1538 return 1;
1539 }
1540
1541 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
1542 lua_pushnil(L);
1543 return 1;
1544 }
1545
1546 lua_pushstring(L, p);
1547 return 1;
1548}
1549
1550/* Returns information about the peer of the connection. */
1551__LJMP static int hlua_socket_getpeername(struct lua_State *L)
1552{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001553 struct hlua_socket *socket;
1554 struct connection *conn;
1555
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001556 MAY_LJMP(check_args(L, 1, "getpeername"));
1557
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001558 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001559
1560 /* Check if the tcp object is avalaible. */
1561 if (!socket->s) {
1562 lua_pushnil(L);
1563 return 1;
1564 }
1565
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001566 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001567 if (!conn) {
1568 lua_pushnil(L);
1569 return 1;
1570 }
1571
1572 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
1573 unsigned int salen = sizeof(conn->addr.to);
1574 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
1575 lua_pushnil(L);
1576 return 1;
1577 }
1578 conn->flags |= CO_FL_ADDR_TO_SET;
1579 }
1580
1581 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
1582}
1583
1584/* Returns information about my connection side. */
1585static int hlua_socket_getsockname(struct lua_State *L)
1586{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001587 struct hlua_socket *socket;
1588 struct connection *conn;
1589
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001590 MAY_LJMP(check_args(L, 1, "getsockname"));
1591
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001592 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001593
1594 /* Check if the tcp object is avalaible. */
1595 if (!socket->s) {
1596 lua_pushnil(L);
1597 return 1;
1598 }
1599
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001600 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001601 if (!conn) {
1602 lua_pushnil(L);
1603 return 1;
1604 }
1605
1606 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
1607 unsigned int salen = sizeof(conn->addr.from);
1608 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
1609 lua_pushnil(L);
1610 return 1;
1611 }
1612 conn->flags |= CO_FL_ADDR_FROM_SET;
1613 }
1614
1615 return hlua_socket_info(L, &conn->addr.from);
1616}
1617
1618/* This struct define the applet. */
1619static struct si_applet update_applet = {
1620 .obj_type = OBJ_TYPE_APPLET,
1621 .name = "<LUA_TCP>",
1622 .fct = hlua_socket_handler,
1623 .release = hlua_socket_release,
1624};
1625
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001626__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001627{
1628 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1629 struct hlua *hlua = hlua_gethlua(L);
1630 struct appctx *appctx;
1631
1632 /* Check for connection close. */
1633 if (!hlua || !socket->s || channel_output_closed(socket->s->req)) {
1634 lua_pushnil(L);
1635 lua_pushstring(L, "Can't connect");
1636 return 2;
1637 }
1638
1639 appctx = objt_appctx(socket->s->si[0].end);
1640
1641 /* Check for connection established. */
1642 if (appctx->ctx.hlua.connected) {
1643 lua_pushinteger(L, 1);
1644 return 1;
1645 }
1646
1647 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1648 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001649 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001650 return 0;
1651}
1652
1653/* This function fail or initite the connection. */
1654__LJMP static int hlua_socket_connect(struct lua_State *L)
1655{
1656 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001657 int port;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001658 const char *ip;
1659 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01001660 struct hlua *hlua;
1661 struct appctx *appctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001662
1663 MAY_LJMP(check_args(L, 3, "connect"));
1664
1665 /* Get args. */
1666 socket = MAY_LJMP(hlua_checksocket(L, 1));
1667 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001668 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001669
1670 conn = si_alloc_conn(socket->s->req->cons, 0);
1671 if (!conn)
1672 WILL_LJMP(luaL_error(L, "connect: internal error"));
1673
1674 /* Parse ip address. */
1675 conn->addr.to.ss_family = AF_UNSPEC;
1676 if (!str2ip2(ip, &conn->addr.to, 0))
1677 WILL_LJMP(luaL_error(L, "connect: cannot parse ip address '%s'", ip));
1678
1679 /* Set port. */
1680 if (conn->addr.to.ss_family == AF_INET)
1681 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
1682 else if (conn->addr.to.ss_family == AF_INET6)
1683 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
1684
1685 /* it is important not to call the wakeup function directly but to
1686 * pass through task_wakeup(), because this one knows how to apply
1687 * priorities to tasks.
1688 */
1689 task_wakeup(socket->s->task, TASK_WOKEN_INIT);
1690
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01001691 hlua = hlua_gethlua(L);
1692 appctx = objt_appctx(socket->s->si[0].end);
1693 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1694 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001695 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001696
1697 return 0;
1698}
1699
Baptiste Assmann84bb4932015-03-02 21:40:06 +01001700#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001701__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
1702{
1703 struct hlua_socket *socket;
1704
1705 MAY_LJMP(check_args(L, 3, "connect_ssl"));
1706 socket = MAY_LJMP(hlua_checksocket(L, 1));
1707 socket->s->target = &socket_ssl.obj_type;
1708 return MAY_LJMP(hlua_socket_connect(L));
1709}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01001710#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001711
1712__LJMP static int hlua_socket_setoption(struct lua_State *L)
1713{
1714 return 0;
1715}
1716
1717__LJMP static int hlua_socket_settimeout(struct lua_State *L)
1718{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001719 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001720 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001721
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001722 MAY_LJMP(check_args(L, 2, "settimeout"));
1723
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001724 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001725 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001726
1727 socket->s->req->rto = tmout;
1728 socket->s->req->wto = tmout;
1729 socket->s->rep->rto = tmout;
1730 socket->s->rep->wto = tmout;
1731
1732 return 0;
1733}
1734
1735__LJMP static int hlua_socket_new(lua_State *L)
1736{
1737 struct hlua_socket *socket;
1738 struct appctx *appctx;
1739
1740 /* Check stack size. */
1741 if (!lua_checkstack(L, 2)) {
1742 hlua_pusherror(L, "socket: full stack");
1743 goto out_fail_conf;
1744 }
1745
1746 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
1747 memset(socket, 0, sizeof(*socket));
1748
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01001749 /* Check if the various memory pools are intialized. */
1750 if (!pool2_session || !pool2_channel || !pool2_buffer) {
1751 hlua_pusherror(L, "socket: uninitialized pools.");
1752 goto out_fail_conf;
1753 }
1754
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001755 /* Pop a class session metatable and affect it to the userdata. */
1756 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
1757 lua_setmetatable(L, -2);
1758
1759 /*
1760 *
1761 * Get memory for the request.
1762 *
1763 */
1764
1765 socket->s = pool_alloc2(pool2_session);
1766 if (!socket->s) {
1767 hlua_pusherror(L, "socket: out of memory");
1768 goto out_fail_conf;
1769 }
1770
1771 socket->s->task = task_new();
1772 if (!socket->s->task) {
1773 hlua_pusherror(L, "socket: out of memory");
1774 goto out_free_session;
1775 }
1776
1777 socket->s->req = pool_alloc2(pool2_channel);
1778 if (!socket->s->req) {
1779 hlua_pusherror(L, "socket: out of memory");
1780 goto out_fail_req;
1781 }
1782
1783 socket->s->req->buf = pool_alloc2(pool2_buffer);
1784 if (!socket->s->req->buf) {
1785 hlua_pusherror(L, "socket: out of memory");
1786 goto out_fail_req_buf;
1787 }
1788
1789 socket->s->rep = pool_alloc2(pool2_channel);
1790 if (!socket->s->rep) {
1791 hlua_pusherror(L, "socket: out of memory");
1792 goto out_fail_rep;
1793 }
1794
1795 socket->s->rep->buf = pool_alloc2(pool2_buffer);
1796 if (!socket->s->rep->buf) {
1797 hlua_pusherror(L, "socket: out of memory");
1798 goto out_fail_rep_buf;
1799 }
1800
1801 /* Configura empty Lua for the session. */
1802 socket->s->hlua.T = NULL;
1803 socket->s->hlua.Tref = LUA_REFNIL;
1804 socket->s->hlua.Mref = LUA_REFNIL;
1805 socket->s->hlua.nargs = 0;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001806 socket->s->hlua.flags = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001807 LIST_INIT(&socket->s->hlua.com);
1808
1809 /* session initialisation. */
1810 session_init_srv_conn(socket->s);
1811
1812 /*
1813 *
1814 * Configure the associated task.
1815 *
1816 */
1817
1818 /* This is the dedicated function to process the session. This function
1819 * is able to establish the conection, process the timeouts, etc ...
1820 */
1821 socket->s->task->process = process_session;
1822
1823 /* Back reference to session. This is used by process_session(). */
1824 socket->s->task->context = socket->s;
1825
1826 /* The priority of the task is normal. */
1827 socket->s->task->nice = 0;
1828
1829 /* Init the next run to eternity. Later in this function, this task is
1830 * waked.
1831 */
1832 socket->s->task->expire = TICK_ETERNITY;
1833
1834 /*
1835 *
1836 * Initialize the attached buffers
1837 *
1838 */
1839 socket->s->req->buf->size = global.tune.bufsize;
1840 socket->s->rep->buf->size = global.tune.bufsize;
1841
1842 /*
1843 *
1844 * Initialize channels.
1845 *
1846 */
1847
1848 /* This function reset the struct. It must be called
1849 * before the configuration.
1850 */
1851 channel_init(socket->s->req);
1852 channel_init(socket->s->rep);
1853
1854 socket->s->req->prod = &socket->s->si[0];
1855 socket->s->req->cons = &socket->s->si[1];
1856
1857 socket->s->rep->prod = &socket->s->si[1];
1858 socket->s->rep->cons = &socket->s->si[0];
1859
1860 socket->s->si[0].ib = socket->s->req;
1861 socket->s->si[0].ob = socket->s->rep;
1862
1863 socket->s->si[1].ib = socket->s->rep;
1864 socket->s->si[1].ob = socket->s->req;
1865
1866 socket->s->req->analysers = 0;
1867 socket->s->req->rto = socket_proxy.timeout.client;
1868 socket->s->req->wto = socket_proxy.timeout.server;
1869 socket->s->req->rex = TICK_ETERNITY;
1870 socket->s->req->wex = TICK_ETERNITY;
1871 socket->s->req->analyse_exp = TICK_ETERNITY;
1872
1873 socket->s->rep->analysers = 0;
1874 socket->s->rep->rto = socket_proxy.timeout.server;
1875 socket->s->rep->wto = socket_proxy.timeout.client;
1876 socket->s->rep->rex = TICK_ETERNITY;
1877 socket->s->rep->wex = TICK_ETERNITY;
1878 socket->s->rep->analyse_exp = TICK_ETERNITY;
1879
1880 /*
1881 *
1882 * Configure the session.
1883 *
1884 */
1885
1886 /* The session dont have listener. The listener is used with real
1887 * proxies.
1888 */
1889 socket->s->listener = NULL;
1890
1891 /* The flags are initialized to 0. Values are setted later. */
1892 socket->s->flags = 0;
1893
1894 /* Assign the configured proxy to the new session. */
1895 socket->s->be = &socket_proxy;
1896 socket->s->fe = &socket_proxy;
1897
1898 /* XXX: Set namy variables */
1899 socket->s->store_count = 0;
1900 memset(socket->s->stkctr, 0, sizeof(socket->s->stkctr));
1901
1902 /* Configure logs. */
1903 socket->s->logs.logwait = 0;
1904 socket->s->logs.level = 0;
1905 socket->s->logs.accept_date = date; /* user-visible date for logging */
1906 socket->s->logs.tv_accept = now; /* corrected date for internal use */
1907 socket->s->do_log = NULL;
1908
1909 /* Function used if an error is occured. */
1910 socket->s->srv_error = default_srv_error;
1911
1912 /* Init the list of buffers. */
1913 LIST_INIT(&socket->s->buffer_wait);
1914
1915 /* Dont configure the unique ID. */
1916 socket->s->uniq_id = 0;
1917 socket->s->unique_id = NULL;
1918
1919 /* XXX: ? */
1920 socket->s->pend_pos = NULL;
1921
1922 /* XXX: See later. */
1923 socket->s->txn.sessid = NULL;
1924 socket->s->txn.srv_cookie = NULL;
1925 socket->s->txn.cli_cookie = NULL;
1926 socket->s->txn.uri = NULL;
1927 socket->s->txn.req.cap = NULL;
1928 socket->s->txn.rsp.cap = NULL;
1929 socket->s->txn.hdr_idx.v = NULL;
1930 socket->s->txn.hdr_idx.size = 0;
1931 socket->s->txn.hdr_idx.used = 0;
1932
1933 /* Configure "left" stream interface as applet. This "si" produce
1934 * and use the data received from the server. The applet is initialized
1935 * and is attached to the stream interface.
1936 */
1937
1938 /* The data producer is already connected. It is the applet. */
1939 socket->s->req->flags = CF_READ_ATTACHED;
1940
1941 channel_auto_connect(socket->s->req); /* don't wait to establish connection */
1942 channel_auto_close(socket->s->req); /* let the producer forward close requests */
1943
1944 si_reset(&socket->s->si[0], socket->s->task);
1945 si_set_state(&socket->s->si[0], SI_ST_EST); /* connection established (resource exists) */
1946
1947 appctx = stream_int_register_handler(&socket->s->si[0], &update_applet);
1948 if (!appctx)
1949 goto out_fail_conn1;
1950 appctx->ctx.hlua.socket = socket;
1951 appctx->ctx.hlua.connected = 0;
1952 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
1953 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
1954
1955 /* Configure "right" stream interface. this "si" is used to connect
1956 * and retrieve data from the server. The connection is initialized
1957 * with the "struct server".
1958 */
1959 si_reset(&socket->s->si[1], socket->s->task);
1960 si_set_state(&socket->s->si[1], SI_ST_INI);
1961 socket->s->si[1].conn_retries = socket_proxy.conn_retries;
1962
1963 /* Force destination server. */
1964 socket->s->flags |= SN_DIRECT | SN_ASSIGNED | SN_ADDR_SET | SN_BE_ASSIGNED;
1965 socket->s->target = &socket_tcp.obj_type;
1966
1967 /* This session is added to te lists of alive sessions. */
1968 LIST_ADDQ(&sessions, &socket->s->list);
1969
1970 /* XXX: I think that this list is used by stats. */
1971 LIST_INIT(&socket->s->back_refs);
1972
1973 /* Update statistics counters. */
1974 socket_proxy.feconn++; /* beconn will be increased later */
1975 jobs++;
1976 totalconn++;
1977
1978 /* Return yield waiting for connection. */
1979 return 1;
1980
1981out_fail_conn1:
1982 pool_free2(pool2_buffer, socket->s->rep->buf);
1983out_fail_rep_buf:
1984 pool_free2(pool2_channel, socket->s->rep);
1985out_fail_rep:
1986 pool_free2(pool2_buffer, socket->s->req->buf);
1987out_fail_req_buf:
1988 pool_free2(pool2_channel, socket->s->req);
1989out_fail_req:
1990 task_free(socket->s->task);
1991out_free_session:
1992 pool_free2(pool2_session, socket->s);
1993out_fail_conf:
1994 WILL_LJMP(lua_error(L));
1995 return 0;
1996}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001997
1998/*
1999 *
2000 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002001 * Class Channel
2002 *
2003 *
2004 */
2005
2006/* Returns the struct hlua_channel join to the class channel in the
2007 * stack entry "ud" or throws an argument error.
2008 */
2009__LJMP static struct hlua_channel *hlua_checkchannel(lua_State *L, int ud)
2010{
2011 return (struct hlua_channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
2012}
2013
2014/* Creates new channel object and put it on the top of the stack.
2015 * If the stask does not have a free slots, the function fails
2016 * and returns 0;
2017 */
Thierry FOURNIERbd1f1322015-03-05 17:04:41 +01002018static int hlua_channel_new(lua_State *L, struct session *s, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002019{
2020 struct hlua_channel *chn;
2021
2022 /* Check stack size. */
2023 if (!lua_checkstack(L, 2))
2024 return 0;
2025
2026 /* NOTE: The allocation never fails. The failure
2027 * throw an error, and the function never returns.
2028 */
2029 chn = lua_newuserdata(L, sizeof(*chn));
2030 chn->chn = channel;
Thierry FOURNIERbd1f1322015-03-05 17:04:41 +01002031 chn->s = s;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002032
2033 /* Pop a class sesison metatable and affect it to the userdata. */
2034 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2035 lua_setmetatable(L, -2);
2036
2037 return 1;
2038}
2039
2040/* Duplicate all the data present in the input channel and put it
2041 * in a string LUA variables. Returns -1 and push a nil value in
2042 * the stack if the channel is closed and all the data are consumed,
2043 * returns 0 if no data are available, otherwise it returns the length
2044 * of the builded string.
2045 */
2046static inline int _hlua_channel_dup(struct hlua_channel *chn, lua_State *L)
2047{
2048 char *blk1;
2049 char *blk2;
2050 int len1;
2051 int len2;
2052 int ret;
2053 luaL_Buffer b;
2054
2055 ret = bi_getblk_nc(chn->chn, &blk1, &len1, &blk2, &len2);
2056 if (unlikely(ret == 0))
2057 return 0;
2058
2059 if (unlikely(ret < 0)) {
2060 lua_pushnil(L);
2061 return -1;
2062 }
2063
2064 luaL_buffinit(L, &b);
2065 luaL_addlstring(&b, blk1, len1);
2066 if (unlikely(ret == 2))
2067 luaL_addlstring(&b, blk2, len2);
2068 luaL_pushresult(&b);
2069
2070 if (unlikely(ret == 2))
2071 return len1 + len2;
2072 return len1;
2073}
2074
2075/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2076 * a yield. This function keep the data in the buffer.
2077 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002078__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002079{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002080 struct hlua_channel *chn;
2081
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002082 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2083
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002084 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002085 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002086 return 1;
2087}
2088
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002089/* Check arguments for the function "hlua_channel_dup_yield". */
2090__LJMP static int hlua_channel_dup(lua_State *L)
2091{
2092 MAY_LJMP(check_args(L, 1, "dup"));
2093 MAY_LJMP(hlua_checkchannel(L, 1));
2094 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2095}
2096
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002097/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2098 * a yield. This function consumes the data in the buffer. It returns
2099 * a string containing the data or a nil pointer if no data are available
2100 * and the channel is closed.
2101 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002102__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002103{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002104 struct hlua_channel *chn;
2105 int ret;
2106
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002107 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002108
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002109 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002110 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002111 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002112
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002113 if (unlikely(ret == -1))
2114 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002115
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002116 chn->chn->buf->i -= ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002117 return 1;
2118}
2119
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002120/* Check arguments for the fucntion "hlua_channel_get_yield". */
2121__LJMP static int hlua_channel_get(lua_State *L)
2122{
2123 MAY_LJMP(check_args(L, 1, "get"));
2124 MAY_LJMP(hlua_checkchannel(L, 1));
2125 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2126}
2127
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002128/* This functions consumes and returns one line. If the channel is closed,
2129 * and the last data does not contains a final '\n', the data are returned
2130 * without the final '\n'. When no more data are avalaible, it returns nil
2131 * value.
2132 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002133__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002134{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002135 char *blk1;
2136 char *blk2;
2137 int len1;
2138 int len2;
2139 int len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002140 struct hlua_channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002141 int ret;
2142 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002143
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002144 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2145
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002146 ret = bi_getline_nc(chn->chn, &blk1, &len1, &blk2, &len2);
2147 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002148 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002149
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002150 if (ret == -1) {
2151 lua_pushnil(L);
2152 return 1;
2153 }
2154
2155 luaL_buffinit(L, &b);
2156 luaL_addlstring(&b, blk1, len1);
2157 len = len1;
2158 if (unlikely(ret == 2)) {
2159 luaL_addlstring(&b, blk2, len2);
2160 len += len2;
2161 }
2162 luaL_pushresult(&b);
2163 buffer_replace2(chn->chn->buf, chn->chn->buf->p, chn->chn->buf->p + len, NULL, 0);
2164 return 1;
2165}
2166
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002167/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2168__LJMP static int hlua_channel_getline(lua_State *L)
2169{
2170 MAY_LJMP(check_args(L, 1, "getline"));
2171 MAY_LJMP(hlua_checkchannel(L, 1));
2172 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2173}
2174
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002175/* This function takes a string as input, and append it at the
2176 * input side of channel. If the data is too big, but a space
2177 * is probably available after sending some data, the function
2178 * yield. If the data is bigger than the buffer, or if the
2179 * channel is closed, it returns -1. otherwise, it returns the
2180 * amount of data writed.
2181 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002182__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002183{
2184 struct hlua_channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
2185 size_t len;
2186 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2187 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2188 int ret;
2189 int max;
2190
2191 max = channel_recv_limit(chn->chn) - buffer_len(chn->chn->buf);
2192 if (max > len - l)
2193 max = len - l;
2194
2195 ret = bi_putblk(chn->chn, str+l, max);
2196 if (ret == -2 || ret == -3) {
2197 lua_pushinteger(L, -1);
2198 return 1;
2199 }
2200 if (ret == -1)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002201 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002202 l += ret;
2203 lua_pop(L, 1);
2204 lua_pushinteger(L, l);
2205
2206 max = channel_recv_limit(chn->chn) - buffer_len(chn->chn->buf);
2207 if (max == 0 && chn->chn->buf->o == 0) {
2208 /* There are no space avalaible, and the output buffer is empty.
2209 * in this case, we cannot add more data, so we cannot yield,
2210 * we return the amount of copyied data.
2211 */
2212 return 1;
2213 }
2214 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002215 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002216 return 1;
2217}
2218
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002219/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002220 * of the writed string, or -1 if the channel is closed or if the
2221 * buffer size is too little for the data.
2222 */
2223__LJMP static int hlua_channel_append(lua_State *L)
2224{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002225 size_t len;
2226
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002227 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002228 MAY_LJMP(hlua_checkchannel(L, 1));
2229 MAY_LJMP(luaL_checklstring(L, 2, &len));
2230 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002231 lua_pushinteger(L, 0);
2232
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002233 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002234}
2235
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002236/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002237 * his process by cleaning the buffer. The result is a replacement
2238 * of the current data. It returns the length of the writed string,
2239 * or -1 if the channel is closed or if the buffer size is too
2240 * little for the data.
2241 */
2242__LJMP static int hlua_channel_set(lua_State *L)
2243{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002244 struct hlua_channel *chn;
2245
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002246 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002247 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002248 lua_pushinteger(L, 0);
2249
2250 chn->chn->buf->i = 0;
2251
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002252 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002253}
2254
2255/* Append data in the output side of the buffer. This data is immediatly
2256 * sent. The fcuntion returns the ammount of data writed. If the buffer
2257 * cannot contains the data, the function yield. The function returns -1
2258 * if the channel is closed.
2259 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002260__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002261{
2262 struct hlua_channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
2263 size_t len;
2264 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2265 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2266 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002267 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002268
2269 if (unlikely(channel_output_closed(chn->chn))) {
2270 lua_pushinteger(L, -1);
2271 return 1;
2272 }
2273
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002274 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2275 * the request buffer if its not required.
2276 */
2277 if (chn->chn->buf->size == 0) {
2278 if (!session_alloc_recv_buffer(chn->s, &chn->chn->buf)) {
2279 chn->chn->prod->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002280 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002281 }
2282 }
2283
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002284 /* the writed data will be immediatly sent, so we can check
2285 * the avalaible space without taking in account the reserve.
2286 * The reserve is guaranted for the processing of incoming
2287 * data, because the buffer will be flushed.
2288 */
2289 max = chn->chn->buf->size - buffer_len(chn->chn->buf);
2290
2291 /* If there are no space avalaible, and the output buffer is empty.
2292 * in this case, we cannot add more data, so we cannot yield,
2293 * we return the amount of copyied data.
2294 */
2295 if (max == 0 && chn->chn->buf->o == 0)
2296 return 1;
2297
2298 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002299 if (max > len - l)
2300 max = len - l;
2301
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002302 /* The buffer avalaible size may be not contiguous. This test
2303 * detects a non contiguous buffer and realign it.
2304 */
Thierry FOURNIERd2b597a2015-03-07 14:38:50 +01002305 if (bi_space_for_replace(chn->chn->buf) < max)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002306 buffer_slow_realign(chn->chn->buf);
2307
2308 /* Copy input data in the buffer. */
Thierry FOURNIER506e46c2015-03-04 11:44:47 +01002309 max = buffer_replace2(chn->chn->buf, chn->chn->buf->p, chn->chn->buf->p, str+l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002310
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002311 /* buffer replace considers that the input part is filled.
2312 * so, I must forward these new data in the output part.
2313 */
2314 b_adv(chn->chn->buf, max);
2315
2316 l += max;
2317 lua_pop(L, 1);
2318 lua_pushinteger(L, l);
2319
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002320 /* If there are no space avalaible, and the output buffer is empty.
2321 * in this case, we cannot add more data, so we cannot yield,
2322 * we return the amount of copyied data.
2323 */
2324 max = chn->chn->buf->size - buffer_len(chn->chn->buf);
2325 if (max == 0 && chn->chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002326 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002327
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002328 if (l < len) {
2329 /* If we are waiting for space in the response buffer, we
2330 * must set the flag WAKERESWR. This flag required the task
2331 * wake up if any activity is detected on the response buffer.
2332 */
2333 if (chn->chn == chn->s->rep)
2334 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002335 else
2336 HLUA_SET_WAKEREQWR(hlua);
2337 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002338 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002339
2340 return 1;
2341}
2342
2343/* Just a wraper of "_hlua_channel_send". This wrapper permits
2344 * yield the LUA process, and resume it without checking the
2345 * input arguments.
2346 */
2347__LJMP static int hlua_channel_send(lua_State *L)
2348{
2349 MAY_LJMP(check_args(L, 2, "send"));
2350 lua_pushinteger(L, 0);
2351
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002352 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002353}
2354
2355/* This function forward and amount of butes. The data pass from
2356 * the input side of the buffer to the output side, and can be
2357 * forwarded. This function never fails.
2358 *
2359 * The Lua function takes an amount of bytes to be forwarded in
2360 * imput. It returns the number of bytes forwarded.
2361 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002362__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002363{
2364 struct hlua_channel *chn;
2365 int len;
2366 int l;
2367 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002368 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002369
2370 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2371 len = MAY_LJMP(luaL_checkinteger(L, 2));
2372 l = MAY_LJMP(luaL_checkinteger(L, -1));
2373
2374 max = len - l;
2375 if (max > chn->chn->buf->i)
2376 max = chn->chn->buf->i;
2377 channel_forward(chn->chn, max);
2378 l += max;
2379
2380 lua_pop(L, 1);
2381 lua_pushinteger(L, l);
2382
2383 /* Check if it miss bytes to forward. */
2384 if (l < len) {
2385 /* The the input channel or the output channel are closed, we
2386 * must return the amount of data forwarded.
2387 */
2388 if (channel_input_closed(chn->chn) || channel_output_closed(chn->chn))
2389 return 1;
2390
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002391 /* If we are waiting for space data in the response buffer, we
2392 * must set the flag WAKERESWR. This flag required the task
2393 * wake up if any activity is detected on the response buffer.
2394 */
2395 if (chn->chn == chn->s->rep)
2396 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002397 else
2398 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002399
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002400 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002401 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002402 }
2403
2404 return 1;
2405}
2406
2407/* Just check the input and prepare the stack for the previous
2408 * function "hlua_channel_forward_yield"
2409 */
2410__LJMP static int hlua_channel_forward(lua_State *L)
2411{
2412 MAY_LJMP(check_args(L, 2, "forward"));
2413 MAY_LJMP(hlua_checkchannel(L, 1));
2414 MAY_LJMP(luaL_checkinteger(L, 2));
2415
2416 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002417 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002418}
2419
2420/* Just returns the number of bytes available in the input
2421 * side of the buffer. This function never fails.
2422 */
2423__LJMP static int hlua_channel_get_in_len(lua_State *L)
2424{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002425 struct hlua_channel *chn;
2426
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002427 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002428 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002429 lua_pushinteger(L, chn->chn->buf->i);
2430 return 1;
2431}
2432
2433/* Just returns the number of bytes available in the output
2434 * side of the buffer. This function never fails.
2435 */
2436__LJMP static int hlua_channel_get_out_len(lua_State *L)
2437{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002438 struct hlua_channel *chn;
2439
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002440 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002441 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002442 lua_pushinteger(L, chn->chn->buf->o);
2443 return 1;
2444}
2445
2446
2447/*
2448 *
2449 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002450 * Class TXN
2451 *
2452 *
2453 */
2454
2455/* Returns a struct hlua_session if the stack entry "ud" is
2456 * a class session, otherwise it throws an error.
2457 */
2458__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
2459{
2460 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
2461}
2462
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002463__LJMP static int hlua_setpriv(lua_State *L)
2464{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002465 struct hlua *hlua;
2466
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002467 MAY_LJMP(check_args(L, 2, "set_priv"));
2468
2469 /* It is useles to retrieve the session, but this function
2470 * runs only in a session context.
2471 */
2472 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002473 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002474
2475 /* Remove previous value. */
2476 if (hlua->Mref != -1)
2477 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
2478
2479 /* Get and store new value. */
2480 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
2481 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
2482
2483 return 0;
2484}
2485
2486__LJMP static int hlua_getpriv(lua_State *L)
2487{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002488 struct hlua *hlua;
2489
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002490 MAY_LJMP(check_args(L, 1, "get_priv"));
2491
2492 /* It is useles to retrieve the session, but this function
2493 * runs only in a session context.
2494 */
2495 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002496 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002497
2498 /* Push configuration index in the stack. */
2499 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
2500
2501 return 1;
2502}
2503
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002504/* Create stack entry containing a class TXN. This function
2505 * return 0 if the stack does not contains free slots,
2506 * otherwise it returns 1.
2507 */
2508static int hlua_txn_new(lua_State *L, struct session *s, struct proxy *p, void *l7)
2509{
2510 struct hlua_txn *hs;
2511
2512 /* Check stack size. */
2513 if (!lua_checkstack(L, 2))
2514 return 0;
2515
2516 /* NOTE: The allocation never fails. The failure
2517 * throw an error, and the function never returns.
2518 * if the throw is not avalaible, the process is aborted.
2519 */
2520 hs = lua_newuserdata(L, sizeof(struct hlua_txn));
2521 hs->s = s;
2522 hs->p = p;
2523 hs->l7 = l7;
2524
2525 /* Pop a class sesison metatable and affect it to the userdata. */
2526 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
2527 lua_setmetatable(L, -2);
2528
2529 return 1;
2530}
2531
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002532/* This function returns a channel object associated
2533 * with the request channel. This function never fails,
2534 * however if the stack is full, it throws an error.
2535 */
2536__LJMP static int hlua_txn_req_channel(lua_State *L)
2537{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002538 struct hlua_txn *s;
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002539
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002540 MAY_LJMP(check_args(L, 1, "req_channel"));
2541 s = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002542
Thierry FOURNIERbd1f1322015-03-05 17:04:41 +01002543 if (!hlua_channel_new(L, s->s, s->s->req))
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002544 WILL_LJMP(luaL_error(L, "full stack"));
2545
2546 return 1;
2547}
2548
2549/* This function returns a channel object associated
2550 * with the response channel. This function never fails,
2551 * however if the stack is full, it throws an error.
2552 */
2553__LJMP static int hlua_txn_res_channel(lua_State *L)
2554{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002555 struct hlua_txn *s;
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002556
Willy Tarreaueee45392015-03-10 14:22:28 +01002557 MAY_LJMP(check_args(L, 1, "res_channel"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002558 s = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002559
Thierry FOURNIERbd1f1322015-03-05 17:04:41 +01002560 if (!hlua_channel_new(L, s->s, s->s->rep))
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002561 WILL_LJMP(luaL_error(L, "full stack"));
2562
2563 return 1;
2564}
2565
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002566/* This function is an Lua binding that send pending data
2567 * to the client, and close the stream interface.
2568 */
2569__LJMP static int hlua_txn_close(lua_State *L)
2570{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002571 struct hlua_txn *s;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002572
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002573 MAY_LJMP(check_args(L, 1, "close"));
2574 s = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002575
2576 channel_abort(s->s->si[0].ib);
2577 channel_auto_close(s->s->si[0].ib);
2578 channel_erase(s->s->si[0].ib);
2579 channel_auto_read(s->s->si[0].ob);
2580 channel_auto_close(s->s->si[0].ob);
2581 channel_shutr_now(s->s->si[0].ob);
2582
2583 return 0;
2584}
2585
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01002586/* This function is an LUA binding. It is called with each sample-fetch.
2587 * It uses closure argument to store the associated sample-fetch. It
Cyril Bonté928ae5c2015-03-02 00:08:41 +01002588 * returns only one argument or throws an error. An error is thrown
2589 * only if an error is encountered during the argument parsing. If
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01002590 * the "sample-fetch" function fails, nil is returned.
2591 */
2592__LJMP static int hlua_run_sample_fetch(lua_State *L)
2593{
2594 struct hlua_txn *s;
2595 struct hlua_sample_fetch *f;
Cyril Bonté928ae5c2015-03-02 00:08:41 +01002596 struct arg args[ARGM_NBARGS + 1];
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01002597 int i;
2598 struct sample smp;
2599
2600 /* Get closure arguments. */
2601 f = (struct hlua_sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
2602
2603 /* Get traditionnal arguments. */
2604 s = MAY_LJMP(hlua_checktxn(L, 1));
2605
2606 /* Get extra arguments. */
Cyril Bonté928ae5c2015-03-02 00:08:41 +01002607 for (i = 0; i < lua_gettop(L) - 1; i++) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01002608 if (i >= ARGM_NBARGS)
2609 break;
2610 hlua_lua2arg(L, i + 2, &args[i]);
2611 }
2612 args[i].type = ARGT_STOP;
2613
2614 /* Check arguments. */
2615 MAY_LJMP(hlua_lua2arg_check(L, 1, args, f->f->arg_mask));
2616
Cyril Bonté928ae5c2015-03-02 00:08:41 +01002617 /* Run the special args checker. */
2618 if (f->f->val_args && !f->f->val_args(args, NULL)) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01002619 lua_pushfstring(L, "error in arguments");
2620 WILL_LJMP(lua_error(L));
2621 }
2622
2623 /* Initialise the sample. */
2624 memset(&smp, 0, sizeof(smp));
2625
2626 /* Run the sample fetch process. */
2627 if (!f->f->process(s->p, s->s, s->l7, 0, args, &smp, f->f->kw, f->f->private)) {
2628 lua_pushnil(L);
2629 return 1;
2630 }
2631
2632 /* Convert the returned sample in lua value. */
2633 hlua_smp2lua(L, &smp);
2634 return 1;
2635}
2636
Thierry FOURNIER9a819e72015-02-16 20:22:55 +01002637/* This function is an LUA binding. It creates ans returns
2638 * an array of HTTP headers. This function does not fails.
2639 */
2640static int hlua_session_getheaders(lua_State *L)
2641{
2642 struct hlua_txn *s = MAY_LJMP(hlua_checktxn(L, 1));
2643 struct session *sess = s->s;
2644 const char *cur_ptr, *cur_next, *p;
2645 int old_idx, cur_idx;
2646 struct hdr_idx_elem *cur_hdr;
2647 const char *hn, *hv;
2648 int hnl, hvl;
2649
2650 /* Create the table. */
2651 lua_newtable(L);
2652
2653 /* Build array of headers. */
2654 old_idx = 0;
2655 cur_next = sess->req->buf->p + hdr_idx_first_pos(&sess->txn.hdr_idx);
2656
2657 while (1) {
2658 cur_idx = sess->txn.hdr_idx.v[old_idx].next;
2659 if (!cur_idx)
2660 break;
2661 old_idx = cur_idx;
2662
2663 cur_hdr = &sess->txn.hdr_idx.v[cur_idx];
2664 cur_ptr = cur_next;
2665 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
2666
2667 /* Now we have one full header at cur_ptr of len cur_hdr->len,
2668 * and the next header starts at cur_next. We'll check
2669 * this header in the list as well as against the default
2670 * rule.
2671 */
2672
2673 /* look for ': *'. */
2674 hn = cur_ptr;
2675 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
2676 if (p >= cur_ptr+cur_hdr->len)
2677 continue;
2678 hnl = p - hn;
2679 p++;
2680 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
2681 p++;
2682 if (p >= cur_ptr+cur_hdr->len)
2683 continue;
2684 hv = p;
2685 hvl = cur_ptr+cur_hdr->len-p;
2686
2687 /* Push values in the table. */
2688 lua_pushlstring(L, hn, hnl);
2689 lua_pushlstring(L, hv, hvl);
2690 lua_settable(L, -3);
2691 }
2692
2693 return 1;
2694}
2695
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002696__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002697{
2698 int wakeup_ms = lua_tointeger(L, -1);
2699 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002700 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002701 return 0;
2702}
2703
2704__LJMP static int hlua_sleep(lua_State *L)
2705{
2706 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002707 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002708
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002709 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002710
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002711 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002712 wakeup_ms = tick_add(now_ms, delay);
2713 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002714
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002715 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
2716 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002717}
2718
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002719__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002720{
2721 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002722 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002723
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002724 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002725
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002726 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002727 wakeup_ms = tick_add(now_ms, delay);
2728 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002729
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002730 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
2731 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002732}
2733
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01002734/* This functionis an LUA binding. it permits to give back
2735 * the hand at the HAProxy scheduler. It is used when the
2736 * LUA processing consumes a lot of time.
2737 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002738__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002739{
2740 return 0;
2741}
2742
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01002743__LJMP static int hlua_yield(lua_State *L)
2744{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002745 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
2746 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01002747}
2748
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002749/* This function change the nice of the currently executed
2750 * task. It is used set low or high priority at the current
2751 * task.
2752 */
2753__LJMP static int hlua_setnice(lua_State *L)
2754{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002755 struct hlua *hlua;
2756 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002757
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002758 MAY_LJMP(check_args(L, 1, "set_nice"));
2759 hlua = hlua_gethlua(L);
2760 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002761
2762 /* If he task is not set, I'm in a start mode. */
2763 if (!hlua || !hlua->task)
2764 return 0;
2765
2766 if (nice < -1024)
2767 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002768 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002769 nice = 1024;
2770
2771 hlua->task->nice = nice;
2772 return 0;
2773}
2774
Thierry FOURNIER24f33532015-01-23 12:13:00 +01002775/* This function is used as a calback of a task. It is called by the
2776 * HAProxy task subsystem when the task is awaked. The LUA runtime can
2777 * return an E_AGAIN signal, the emmiter of this signal must set a
2778 * signal to wake the task.
2779 */
2780static struct task *hlua_process_task(struct task *task)
2781{
2782 struct hlua *hlua = task->context;
2783 enum hlua_exec status;
2784
2785 /* We need to remove the task from the wait queue before executing
2786 * the Lua code because we don't know if it needs to wait for
2787 * another timer or not in the case of E_AGAIN.
2788 */
2789 task_delete(task);
2790
Thierry FOURNIERbd413492015-03-03 16:52:26 +01002791 /* If it is the first call to the task, we must initialize the
2792 * execution timeouts.
2793 */
2794 if (!HLUA_IS_RUNNING(hlua))
2795 hlua->expire = tick_add(now_ms, hlua_timeout_task);
2796
Thierry FOURNIER24f33532015-01-23 12:13:00 +01002797 /* Execute the Lua code. */
2798 status = hlua_ctx_resume(hlua, 1);
2799
2800 switch (status) {
2801 /* finished or yield */
2802 case HLUA_E_OK:
2803 hlua_ctx_destroy(hlua);
2804 task_delete(task);
2805 task_free(task);
2806 break;
2807
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01002808 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
2809 if (hlua->wake_time != TICK_ETERNITY)
2810 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01002811 break;
2812
2813 /* finished with error. */
2814 case HLUA_E_ERRMSG:
2815 send_log(NULL, LOG_ERR, "Lua task: %s.", lua_tostring(hlua->T, -1));
2816 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2817 Alert("Lua task: %s.\n", lua_tostring(hlua->T, -1));
2818 hlua_ctx_destroy(hlua);
2819 task_delete(task);
2820 task_free(task);
2821 break;
2822
2823 case HLUA_E_ERR:
2824 default:
2825 send_log(NULL, LOG_ERR, "Lua task: unknown error.");
2826 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2827 Alert("Lua task: unknown error.\n");
2828 hlua_ctx_destroy(hlua);
2829 task_delete(task);
2830 task_free(task);
2831 break;
2832 }
2833 return NULL;
2834}
2835
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01002836/* This function is an LUA binding that register LUA function to be
2837 * executed after the HAProxy configuration parsing and before the
2838 * HAProxy scheduler starts. This function expect only one LUA
2839 * argument that is a function. This function returns nothing, but
2840 * throws if an error is encountered.
2841 */
2842__LJMP static int hlua_register_init(lua_State *L)
2843{
2844 struct hlua_init_function *init;
2845 int ref;
2846
2847 MAY_LJMP(check_args(L, 1, "register_init"));
2848
2849 ref = MAY_LJMP(hlua_checkfunction(L, 1));
2850
2851 init = malloc(sizeof(*init));
2852 if (!init)
2853 WILL_LJMP(luaL_error(L, "lua out of memory error."));
2854
2855 init->function_ref = ref;
2856 LIST_ADDQ(&hlua_init_functions, &init->l);
2857 return 0;
2858}
2859
Thierry FOURNIER24f33532015-01-23 12:13:00 +01002860/* This functio is an LUA binding. It permits to register a task
2861 * executed in parallel of the main HAroxy activity. The task is
2862 * created and it is set in the HAProxy scheduler. It can be called
2863 * from the "init" section, "post init" or during the runtime.
2864 *
2865 * Lua prototype:
2866 *
2867 * <none> core.register_task(<function>)
2868 */
2869static int hlua_register_task(lua_State *L)
2870{
2871 struct hlua *hlua;
2872 struct task *task;
2873 int ref;
2874
2875 MAY_LJMP(check_args(L, 1, "register_task"));
2876
2877 ref = MAY_LJMP(hlua_checkfunction(L, 1));
2878
2879 hlua = malloc(sizeof(*hlua));
2880 if (!hlua)
2881 WILL_LJMP(luaL_error(L, "lua out of memory error."));
2882
2883 task = task_new();
2884 task->context = hlua;
2885 task->process = hlua_process_task;
2886
2887 if (!hlua_ctx_init(hlua, task))
2888 WILL_LJMP(luaL_error(L, "lua out of memory error."));
2889
2890 /* Restore the function in the stack. */
2891 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
2892 hlua->nargs = 0;
2893
2894 /* Schedule task. */
2895 task_schedule(task, now_ms);
2896
2897 return 0;
2898}
2899
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01002900/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
2901 * doesn't allow "yield" functions because the HAProxy engine cannot
2902 * resume converters.
2903 */
2904static int hlua_sample_conv_wrapper(struct session *session, const struct arg *arg_p,
2905 struct sample *smp, void *private)
2906{
2907 struct hlua_function *fcn = (struct hlua_function *)private;
2908
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01002909 /* In the execution wrappers linked with a session, the
2910 * Lua context can be not initialized. This behavior
2911 * permits to save performances because a systematic
2912 * Lua initialization cause 5% performances loss.
2913 */
2914 if (!session->hlua.T && !hlua_ctx_init(&session->hlua, session->task)) {
2915 send_log(session->be, LOG_ERR, "Lua converter '%s': can't initialize Lua context.", fcn->name);
2916 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2917 Alert("Lua converter '%s': can't initialize Lua context.\n", fcn->name);
2918 return 0;
2919 }
2920
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01002921 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01002922 if (!HLUA_IS_RUNNING(&session->hlua)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01002923 /* Check stack available size. */
2924 if (!lua_checkstack(session->hlua.T, 1)) {
2925 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
2926 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2927 Alert("Lua converter '%s': full stack.\n", fcn->name);
2928 return 0;
2929 }
2930
2931 /* Restore the function in the stack. */
2932 lua_rawgeti(session->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
2933
2934 /* convert input sample and pust-it in the stack. */
2935 if (!lua_checkstack(session->hlua.T, 1)) {
2936 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
2937 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2938 Alert("Lua converter '%s': full stack.\n", fcn->name);
2939 return 0;
2940 }
2941 hlua_smp2lua(session->hlua.T, smp);
2942 session->hlua.nargs = 2;
2943
2944 /* push keywords in the stack. */
2945 if (arg_p) {
2946 for (; arg_p->type != ARGT_STOP; arg_p++) {
2947 if (!lua_checkstack(session->hlua.T, 1)) {
2948 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
2949 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2950 Alert("Lua converter '%s': full stack.\n", fcn->name);
2951 return 0;
2952 }
2953 hlua_arg2lua(session->hlua.T, arg_p);
2954 session->hlua.nargs++;
2955 }
2956 }
2957
Thierry FOURNIERbd413492015-03-03 16:52:26 +01002958 /* We must initialize the execution timeouts. */
2959 session->hlua.expire = tick_add(now_ms, hlua_timeout_session);
2960
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01002961 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01002962 HLUA_SET_RUN(&session->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01002963 }
2964
2965 /* Execute the function. */
2966 switch (hlua_ctx_resume(&session->hlua, 0)) {
2967 /* finished. */
2968 case HLUA_E_OK:
2969 /* Convert the returned value in sample. */
2970 hlua_lua2smp(session->hlua.T, -1, smp);
2971 lua_pop(session->hlua.T, 1);
2972 return 1;
2973
2974 /* yield. */
2975 case HLUA_E_AGAIN:
2976 send_log(session->be, LOG_ERR, "Lua converter '%s': cannot use yielded functions.", fcn->name);
2977 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2978 Alert("Lua converter '%s': cannot use yielded functions.\n", fcn->name);
2979 return 0;
2980
2981 /* finished with error. */
2982 case HLUA_E_ERRMSG:
2983 /* Display log. */
2984 send_log(session->be, LOG_ERR, "Lua converter '%s': %s.", fcn->name, lua_tostring(session->hlua.T, -1));
2985 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2986 Alert("Lua converter '%s': %s.\n", fcn->name, lua_tostring(session->hlua.T, -1));
2987 lua_pop(session->hlua.T, 1);
2988 return 0;
2989
2990 case HLUA_E_ERR:
2991 /* Display log. */
2992 send_log(session->be, LOG_ERR, "Lua converter '%s' returns an unknown error.", fcn->name);
2993 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2994 Alert("Lua converter '%s' returns an unknown error.\n", fcn->name);
2995
2996 default:
2997 return 0;
2998 }
2999}
3000
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003001/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
3002 * doesn't allow "yield" functions because the HAProxy engine cannot
3003 * resume sample-fetches.
3004 */
3005static int hlua_sample_fetch_wrapper(struct proxy *px, struct session *s, void *l7,
3006 unsigned int opt, const struct arg *arg_p,
3007 struct sample *smp, const char *kw, void *private)
3008{
3009 struct hlua_function *fcn = (struct hlua_function *)private;
3010
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003011 /* In the execution wrappers linked with a session, the
3012 * Lua context can be not initialized. This behavior
3013 * permits to save performances because a systematic
3014 * Lua initialization cause 5% performances loss.
3015 */
3016 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
3017 send_log(s->be, LOG_ERR, "Lua sample-fetch '%s': can't initialize Lua context.", fcn->name);
3018 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3019 Alert("Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
3020 return 0;
3021 }
3022
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003023 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003024 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003025 /* Check stack available size. */
3026 if (!lua_checkstack(s->hlua.T, 2)) {
3027 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3028 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3029 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3030 return 0;
3031 }
3032
3033 /* Restore the function in the stack. */
3034 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
3035
3036 /* push arguments in the stack. */
3037 if (!hlua_txn_new(s->hlua.T, s, px, l7)) {
3038 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3039 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3040 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3041 return 0;
3042 }
3043 s->hlua.nargs = 1;
3044
3045 /* push keywords in the stack. */
3046 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
3047 /* Check stack available size. */
3048 if (!lua_checkstack(s->hlua.T, 1)) {
3049 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3050 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3051 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3052 return 0;
3053 }
3054 if (!lua_checkstack(s->hlua.T, 1)) {
3055 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3056 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3057 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3058 return 0;
3059 }
3060 hlua_arg2lua(s->hlua.T, arg_p);
3061 s->hlua.nargs++;
3062 }
3063
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003064 /* We must initialize the execution timeouts. */
3065 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
3066
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003067 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003068 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003069 }
3070
3071 /* Execute the function. */
3072 switch (hlua_ctx_resume(&s->hlua, 0)) {
3073 /* finished. */
3074 case HLUA_E_OK:
3075 /* Convert the returned value in sample. */
3076 hlua_lua2smp(s->hlua.T, -1, smp);
3077 lua_pop(s->hlua.T, 1);
3078
3079 /* Set the end of execution flag. */
3080 smp->flags &= ~SMP_F_MAY_CHANGE;
3081 return 1;
3082
3083 /* yield. */
3084 case HLUA_E_AGAIN:
3085 send_log(px, LOG_ERR, "Lua sample-fetch '%s': cannot use yielded functions.", fcn->name);
3086 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3087 Alert("Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
3088 return 0;
3089
3090 /* finished with error. */
3091 case HLUA_E_ERRMSG:
3092 /* Display log. */
3093 send_log(px, LOG_ERR, "Lua sample-fetch '%s': %s.", fcn->name, lua_tostring(s->hlua.T, -1));
3094 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3095 Alert("Lua sample-fetch '%s': %s.\n", fcn->name, lua_tostring(s->hlua.T, -1));
3096 lua_pop(s->hlua.T, 1);
3097 return 0;
3098
3099 case HLUA_E_ERR:
3100 /* Display log. */
3101 send_log(px, LOG_ERR, "Lua sample-fetch '%s' returns an unknown error.", fcn->name);
3102 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3103 Alert("Lua sample-fetch '%s': returns an unknown error.\n", fcn->name);
3104
3105 default:
3106 return 0;
3107 }
3108}
3109
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003110/* This function is an LUA binding used for registering
3111 * "sample-conv" functions. It expects a converter name used
3112 * in the haproxy configuration file, and an LUA function.
3113 */
3114__LJMP static int hlua_register_converters(lua_State *L)
3115{
3116 struct sample_conv_kw_list *sck;
3117 const char *name;
3118 int ref;
3119 int len;
3120 struct hlua_function *fcn;
3121
3122 MAY_LJMP(check_args(L, 2, "register_converters"));
3123
3124 /* First argument : converter name. */
3125 name = MAY_LJMP(luaL_checkstring(L, 1));
3126
3127 /* Second argument : lua function. */
3128 ref = MAY_LJMP(hlua_checkfunction(L, 2));
3129
3130 /* Allocate and fill the sample fetch keyword struct. */
3131 sck = malloc(sizeof(struct sample_conv_kw_list) +
3132 sizeof(struct sample_conv) * 2);
3133 if (!sck)
3134 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3135 fcn = malloc(sizeof(*fcn));
3136 if (!fcn)
3137 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3138
3139 /* Fill fcn. */
3140 fcn->name = strdup(name);
3141 if (!fcn->name)
3142 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3143 fcn->function_ref = ref;
3144
3145 /* List head */
3146 sck->list.n = sck->list.p = NULL;
3147
3148 /* converter keyword. */
3149 len = strlen("lua.") + strlen(name) + 1;
3150 sck->kw[0].kw = malloc(len);
3151 if (!sck->kw[0].kw)
3152 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3153
3154 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
3155 sck->kw[0].process = hlua_sample_conv_wrapper;
3156 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
3157 sck->kw[0].val_args = NULL;
3158 sck->kw[0].in_type = SMP_T_STR;
3159 sck->kw[0].out_type = SMP_T_STR;
3160 sck->kw[0].private = fcn;
3161
3162 /* End of array. */
3163 memset(&sck->kw[1], 0, sizeof(struct sample_conv));
3164
3165 /* Register this new converter */
3166 sample_register_convs(sck);
3167
3168 return 0;
3169}
3170
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003171/* This fucntion is an LUA binding used for registering
3172 * "sample-fetch" functions. It expects a converter name used
3173 * in the haproxy configuration file, and an LUA function.
3174 */
3175__LJMP static int hlua_register_fetches(lua_State *L)
3176{
3177 const char *name;
3178 int ref;
3179 int len;
3180 struct sample_fetch_kw_list *sfk;
3181 struct hlua_function *fcn;
3182
3183 MAY_LJMP(check_args(L, 2, "register_fetches"));
3184
3185 /* First argument : sample-fetch name. */
3186 name = MAY_LJMP(luaL_checkstring(L, 1));
3187
3188 /* Second argument : lua function. */
3189 ref = MAY_LJMP(hlua_checkfunction(L, 2));
3190
3191 /* Allocate and fill the sample fetch keyword struct. */
3192 sfk = malloc(sizeof(struct sample_fetch_kw_list) +
3193 sizeof(struct sample_fetch) * 2);
3194 if (!sfk)
3195 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3196 fcn = malloc(sizeof(*fcn));
3197 if (!fcn)
3198 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3199
3200 /* Fill fcn. */
3201 fcn->name = strdup(name);
3202 if (!fcn->name)
3203 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3204 fcn->function_ref = ref;
3205
3206 /* List head */
3207 sfk->list.n = sfk->list.p = NULL;
3208
3209 /* sample-fetch keyword. */
3210 len = strlen("lua.") + strlen(name) + 1;
3211 sfk->kw[0].kw = malloc(len);
3212 if (!sfk->kw[0].kw)
3213 return luaL_error(L, "lua out of memory error.");
3214
3215 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
3216 sfk->kw[0].process = hlua_sample_fetch_wrapper;
3217 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
3218 sfk->kw[0].val_args = NULL;
3219 sfk->kw[0].out_type = SMP_T_STR;
3220 sfk->kw[0].use = SMP_USE_HTTP_ANY;
3221 sfk->kw[0].val = 0;
3222 sfk->kw[0].private = fcn;
3223
3224 /* End of array. */
3225 memset(&sfk->kw[1], 0, sizeof(struct sample_fetch));
3226
3227 /* Register this new fetch. */
3228 sample_register_fetches(sfk);
3229
3230 return 0;
3231}
3232
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003233/* global {tcp|http}-request parser. Return 1 in succes case, else return 0. */
3234static int hlua_parse_rule(const char **args, int *cur_arg, struct proxy *px,
3235 struct hlua_rule **rule_p, char **err)
3236{
3237 struct hlua_rule *rule;
3238
3239 /* Memory for the rule. */
3240 rule = malloc(sizeof(*rule));
3241 if (!rule) {
3242 memprintf(err, "out of memory error");
3243 return 0;
3244 }
3245 *rule_p = rule;
3246
3247 /* The requiered arg is a function name. */
3248 if (!args[*cur_arg]) {
3249 memprintf(err, "expect Lua function name");
3250 return 0;
3251 }
3252
3253 /* Lookup for the symbol, and check if it is a function. */
3254 lua_getglobal(gL.T, args[*cur_arg]);
3255 if (lua_isnil(gL.T, -1)) {
3256 lua_pop(gL.T, 1);
3257 memprintf(err, "Lua function '%s' not found", args[*cur_arg]);
3258 return 0;
3259 }
3260 if (!lua_isfunction(gL.T, -1)) {
3261 lua_pop(gL.T, 1);
3262 memprintf(err, "'%s' is not a function", args[*cur_arg]);
3263 return 0;
3264 }
3265
3266 /* Reference the Lua function and store the reference. */
3267 rule->fcn.function_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
3268 rule->fcn.name = strdup(args[*cur_arg]);
3269 if (!rule->fcn.name) {
3270 memprintf(err, "out of memory error.");
3271 return 0;
3272 }
3273 (*cur_arg)++;
3274
3275 /* TODO: later accept arguments. */
3276 rule->args = NULL;
3277
3278 return 1;
3279}
3280
3281/* This function is a wrapper to execute each LUA function declared
3282 * as an action wrapper during the initialisation period. This function
3283 * return 1 if the processing is finished (with oe without error) and
3284 * return 0 if the function must be called again because the LUA
3285 * returns a yield.
3286 */
3287static int hlua_request_act_wrapper(struct hlua_rule *rule, struct proxy *px,
3288 struct session *s, struct http_txn *http_txn,
3289 unsigned int analyzer)
3290{
3291 char **arg;
3292
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003293 /* In the execution wrappers linked with a session, the
3294 * Lua context can be not initialized. This behavior
3295 * permits to save performances because a systematic
3296 * Lua initialization cause 5% performances loss.
3297 */
3298 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
3299 send_log(px, LOG_ERR, "Lua action '%s': can't initialize Lua context.", rule->fcn.name);
3300 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3301 Alert("Lua action '%s': can't initialize Lua context.\n", rule->fcn.name);
3302 return 0;
3303 }
3304
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003305 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003306 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003307 /* Check stack available size. */
3308 if (!lua_checkstack(s->hlua.T, 1)) {
3309 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
3310 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3311 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
3312 return 0;
3313 }
3314
3315 /* Restore the function in the stack. */
3316 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->fcn.function_ref);
3317
3318 /* Create and and push object session in the stack. */
3319 if (!hlua_txn_new(s->hlua.T, s, px, http_txn)) {
3320 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
3321 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3322 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
3323 return 0;
3324 }
3325 s->hlua.nargs = 1;
3326
3327 /* push keywords in the stack. */
3328 for (arg = rule->args; arg && *arg; arg++) {
3329 if (!lua_checkstack(s->hlua.T, 1)) {
3330 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
3331 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3332 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
3333 return 0;
3334 }
3335 lua_pushstring(s->hlua.T, *arg);
3336 s->hlua.nargs++;
3337 }
3338
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003339 /* We must initialize the execution timeouts. */
3340 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
3341
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003342 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003343 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003344 }
3345
3346 /* Execute the function. */
3347 switch (hlua_ctx_resume(&s->hlua, 1)) {
3348 /* finished. */
3349 case HLUA_E_OK:
3350 return 1;
3351
3352 /* yield. */
3353 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003354 /* Set timeout in the required channel. */
3355 if (s->hlua.wake_time != TICK_ETERNITY) {
3356 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
3357 s->req->analyse_exp = s->hlua.wake_time;
3358 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
3359 s->rep->analyse_exp = s->hlua.wake_time;
3360 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003361 /* Some actions can be wake up when a "write" event
3362 * is detected on a response channel. This is useful
3363 * only for actions targetted on the requests.
3364 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003365 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003366 s->rep->flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01003367 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
3368 s->rep->analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003369 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003370 if (HLUA_IS_WAKEREQWR(&s->hlua))
3371 s->req->flags |= CF_WAKE_WRITE;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003372 return 0;
3373
3374 /* finished with error. */
3375 case HLUA_E_ERRMSG:
3376 /* Display log. */
3377 send_log(px, LOG_ERR, "Lua function '%s': %s.", rule->fcn.name, lua_tostring(s->hlua.T, -1));
3378 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3379 Alert("Lua function '%s': %s.\n", rule->fcn.name, lua_tostring(s->hlua.T, -1));
3380 lua_pop(s->hlua.T, 1);
3381 return 1;
3382
3383 case HLUA_E_ERR:
3384 /* Display log. */
3385 send_log(px, LOG_ERR, "Lua function '%s' return an unknown error.", rule->fcn.name);
3386 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3387 Alert("Lua function '%s' return an unknown error.\n", rule->fcn.name);
3388
3389 default:
3390 return 1;
3391 }
3392}
3393
3394/* Lua execution wrapper for "tcp-request". This function uses
3395 * "hlua_request_act_wrapper" for executing the LUA code.
3396 */
3397int hlua_tcp_req_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
3398 struct session *s)
3399{
3400 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
3401 px, s, NULL, AN_REQ_INSPECT_FE);
3402}
3403
3404/* Lua execution wrapper for "tcp-response". This function uses
3405 * "hlua_request_act_wrapper" for executing the LUA code.
3406 */
3407int hlua_tcp_res_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
3408 struct session *s)
3409{
3410 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
3411 px, s, NULL, AN_RES_INSPECT);
3412}
3413
3414/* Lua execution wrapper for http-request.
3415 * This function uses "hlua_request_act_wrapper" for executing
3416 * the LUA code.
3417 */
3418int hlua_http_req_act_wrapper(struct http_req_rule *rule, struct proxy *px,
3419 struct session *s, struct http_txn *http_txn)
3420{
3421 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
3422 s, http_txn, AN_REQ_HTTP_PROCESS_FE);
3423}
3424
3425/* Lua execution wrapper for http-response.
3426 * This function uses "hlua_request_act_wrapper" for executing
3427 * the LUA code.
3428 */
3429int hlua_http_res_act_wrapper(struct http_res_rule *rule, struct proxy *px,
3430 struct session *s, struct http_txn *http_txn)
3431{
3432 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
3433 s, http_txn, AN_RES_HTTP_PROCESS_BE);
3434}
3435
3436/* tcp-request <*> configuration wrapper. */
3437static int tcp_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3438 struct tcp_rule *rule, char **err)
3439{
3440 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003441 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003442 rule->action = TCP_ACT_CUSTOM;
3443 rule->action_ptr = hlua_tcp_req_act_wrapper;
3444 return 1;
3445}
3446
3447/* tcp-response <*> configuration wrapper. */
3448static int tcp_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3449 struct tcp_rule *rule, char **err)
3450{
3451 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003452 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003453 rule->action = TCP_ACT_CUSTOM;
3454 rule->action_ptr = hlua_tcp_res_act_wrapper;
3455 return 1;
3456}
3457
3458/* http-request <*> configuration wrapper. */
3459static int http_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3460 struct http_req_rule *rule, char **err)
3461{
3462 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
3463 return -1;
3464 rule->action = HTTP_REQ_ACT_CUSTOM_CONT;
3465 rule->action_ptr = hlua_http_req_act_wrapper;
3466 return 1;
3467}
3468
3469/* http-response <*> configuration wrapper. */
3470static int http_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3471 struct http_res_rule *rule, char **err)
3472{
3473 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
3474 return -1;
3475 rule->action = HTTP_RES_ACT_CUSTOM_CONT;
3476 rule->action_ptr = hlua_http_res_act_wrapper;
3477 return 1;
3478}
3479
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003480static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
3481 struct proxy *defpx, const char *file, int line,
3482 char **err, unsigned int *timeout)
3483{
3484 const char *error;
3485
3486 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
3487 if (error && *error != '\0') {
3488 memprintf(err, "%s: invalid timeout", args[0]);
3489 return -1;
3490 }
3491 return 0;
3492}
3493
3494static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
3495 struct proxy *defpx, const char *file, int line,
3496 char **err)
3497{
3498 return hlua_read_timeout(args, section_type, curpx, defpx,
3499 file, line, err, &hlua_timeout_session);
3500}
3501
3502static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
3503 struct proxy *defpx, const char *file, int line,
3504 char **err)
3505{
3506 return hlua_read_timeout(args, section_type, curpx, defpx,
3507 file, line, err, &hlua_timeout_task);
3508}
3509
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01003510static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
3511 struct proxy *defpx, const char *file, int line,
3512 char **err)
3513{
3514 char *error;
3515
3516 hlua_nb_instruction = strtoll(args[1], &error, 10);
3517 if (*error != '\0') {
3518 memprintf(err, "%s: invalid number", args[0]);
3519 return -1;
3520 }
3521 return 0;
3522}
3523
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01003524/* This function is called by the main configuration key "lua-load". It loads and
3525 * execute an lua file during the parsing of the HAProxy configuration file. It is
3526 * the main lua entry point.
3527 *
3528 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
3529 * occured, otherwise it returns 0.
3530 *
3531 * In some error case, LUA set an error message in top of the stack. This function
3532 * returns this error message in the HAProxy logs and pop it from the stack.
3533 */
3534static int hlua_load(char **args, int section_type, struct proxy *curpx,
3535 struct proxy *defpx, const char *file, int line,
3536 char **err)
3537{
3538 int error;
3539
3540 /* Just load and compile the file. */
3541 error = luaL_loadfile(gL.T, args[1]);
3542 if (error) {
3543 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
3544 lua_pop(gL.T, 1);
3545 return -1;
3546 }
3547
3548 /* If no syntax error where detected, execute the code. */
3549 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
3550 switch (error) {
3551 case LUA_OK:
3552 break;
3553 case LUA_ERRRUN:
3554 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
3555 lua_pop(gL.T, 1);
3556 return -1;
3557 case LUA_ERRMEM:
3558 memprintf(err, "lua out of memory error\n");
3559 return -1;
3560 case LUA_ERRERR:
3561 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
3562 lua_pop(gL.T, 1);
3563 return -1;
3564 case LUA_ERRGCMM:
3565 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
3566 lua_pop(gL.T, 1);
3567 return -1;
3568 default:
3569 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
3570 lua_pop(gL.T, 1);
3571 return -1;
3572 }
3573
3574 return 0;
3575}
3576
3577/* configuration keywords declaration */
3578static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003579 { CFG_GLOBAL, "lua-load", hlua_load },
3580 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
3581 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01003582 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01003583 { 0, NULL, NULL },
3584}};
3585
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003586static struct http_req_action_kw_list http_req_kws = {"lua", { }, {
3587 { "lua", http_req_action_register_lua },
3588 { NULL, NULL }
3589}};
3590
3591static struct http_res_action_kw_list http_res_kws = {"lua", { }, {
3592 { "lua", http_res_action_register_lua },
3593 { NULL, NULL }
3594}};
3595
3596static struct tcp_action_kw_list tcp_req_cont_kws = {"lua", { }, {
3597 { "lua", tcp_req_action_register_lua },
3598 { NULL, NULL }
3599}};
3600
3601static struct tcp_action_kw_list tcp_res_cont_kws = {"lua", { }, {
3602 { "lua", tcp_res_action_register_lua },
3603 { NULL, NULL }
3604}};
3605
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003606int hlua_post_init()
3607{
3608 struct hlua_init_function *init;
3609 const char *msg;
3610 enum hlua_exec ret;
3611
3612 list_for_each_entry(init, &hlua_init_functions, l) {
3613 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
3614 ret = hlua_ctx_resume(&gL, 0);
3615 switch (ret) {
3616 case HLUA_E_OK:
3617 lua_pop(gL.T, -1);
3618 return 1;
3619 case HLUA_E_AGAIN:
3620 Alert("lua init: yield not allowed.\n");
3621 return 0;
3622 case HLUA_E_ERRMSG:
3623 msg = lua_tostring(gL.T, -1);
3624 Alert("lua init: %s.\n", msg);
3625 return 0;
3626 case HLUA_E_ERR:
3627 default:
3628 Alert("lua init: unknown runtime error.\n");
3629 return 0;
3630 }
3631 }
3632 return 1;
3633}
3634
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01003635void hlua_init(void)
3636{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003637 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01003638 int idx;
3639 struct sample_fetch *sf;
3640 struct hlua_sample_fetch *hsf;
3641 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003642#ifdef USE_OPENSSL
3643 char *args[4];
3644 struct srv_kw *kw;
3645 int tmp_error;
3646 char *error;
3647#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003648
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01003649 /* Initialise com signals pool session. */
3650 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
3651
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003652 /* Initialise sleep pool. */
3653 pool2_hlua_sleep = create_pool("hlua_sleep", sizeof(struct hlua_sleep), MEM_F_SHARED);
3654
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01003655 /* Register configuration keywords. */
3656 cfg_register_keywords(&cfg_kws);
3657
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003658 /* Register custom HTTP rules. */
3659 http_req_keywords_register(&http_req_kws);
3660 http_res_keywords_register(&http_res_kws);
3661 tcp_req_cont_keywords_register(&tcp_req_cont_kws);
3662 tcp_res_cont_keywords_register(&tcp_res_cont_kws);
3663
Thierry FOURNIER380d0932015-01-23 14:27:52 +01003664 /* Init main lua stack. */
3665 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003666 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01003667 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01003668 gL.T = luaL_newstate();
3669 hlua_sethlua(&gL);
3670 gL.Tref = LUA_REFNIL;
3671 gL.task = NULL;
3672
3673 /* Initialise lua. */
3674 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003675
3676 /*
3677 *
3678 * Create "core" object.
3679 *
3680 */
3681
3682 /* This integer entry is just used as base value for the object "core". */
3683 lua_pushinteger(gL.T, 0);
3684
3685 /* Create and fill the metatable. */
3686 lua_newtable(gL.T);
3687
3688 /* Create and fill the __index entry. */
3689 lua_pushstring(gL.T, "__index");
3690 lua_newtable(gL.T);
3691
3692 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003693 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003694 hlua_class_const_int(gL.T, log_levels[i], i);
3695
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003696 /* Register special functions. */
3697 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003698 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003699 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003700 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003701 hlua_class_function(gL.T, "yield", hlua_yield);
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003702 hlua_class_function(gL.T, "set_nice", hlua_setnice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003703 hlua_class_function(gL.T, "sleep", hlua_sleep);
3704 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01003705 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
3706 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
3707 hlua_class_function(gL.T, "set_map", hlua_set_map);
3708 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003709 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003710
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003711 /* Store the table __index in the metable. */
3712 lua_settable(gL.T, -3);
3713
3714 /* Register previous table in the registry with named entry. */
3715 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
3716 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CORE); /* register class session. */
3717
3718 /* Register previous table in the registry with reference. */
3719 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
3720 class_core_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
3721
3722 /* Create new object with class Core. */
3723 lua_setmetatable(gL.T, -2);
3724 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003725
3726 /*
3727 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003728 * Register class Channel
3729 *
3730 */
3731
3732 /* Create and fill the metatable. */
3733 lua_newtable(gL.T);
3734
3735 /* Create and fille the __index entry. */
3736 lua_pushstring(gL.T, "__index");
3737 lua_newtable(gL.T);
3738
3739 /* Register . */
3740 hlua_class_function(gL.T, "get", hlua_channel_get);
3741 hlua_class_function(gL.T, "dup", hlua_channel_dup);
3742 hlua_class_function(gL.T, "getline", hlua_channel_getline);
3743 hlua_class_function(gL.T, "set", hlua_channel_set);
3744 hlua_class_function(gL.T, "append", hlua_channel_append);
3745 hlua_class_function(gL.T, "send", hlua_channel_send);
3746 hlua_class_function(gL.T, "forward", hlua_channel_forward);
3747 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
3748 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
3749
3750 lua_settable(gL.T, -3);
3751
3752 /* Register previous table in the registry with reference and named entry. */
3753 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
3754 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
3755 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
3756
3757 /*
3758 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003759 * Register class TXN
3760 *
3761 */
3762
3763 /* Create and fill the metatable. */
3764 lua_newtable(gL.T);
3765
3766 /* Create and fille the __index entry. */
3767 lua_pushstring(gL.T, "__index");
3768 lua_newtable(gL.T);
3769
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01003770 /* Browse existing fetches and create the associated
3771 * object method.
3772 */
3773 sf = NULL;
3774 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
3775
3776 /* Dont register the keywork if the arguments check function are
3777 * not safe during the runtime.
3778 */
3779 if ((sf->val_args != NULL) &&
3780 (sf->val_args != val_payload_lv) &&
3781 (sf->val_args != val_hdr))
3782 continue;
3783
3784 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
3785 * by an underscore.
3786 */
3787 strncpy(trash.str, sf->kw, trash.size);
3788 trash.str[trash.size - 1] = '\0';
3789 for (p = trash.str; *p; p++)
3790 if (*p == '.' || *p == '-' || *p == '+')
3791 *p = '_';
3792
3793 /* Register the function. */
3794 lua_pushstring(gL.T, trash.str);
3795 hsf = lua_newuserdata(gL.T, sizeof(struct hlua_sample_fetch));
3796 hsf->f = sf;
3797 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
3798 lua_settable(gL.T, -3);
3799 }
3800
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003801 /* Register Lua functions. */
Thierry FOURNIER9a819e72015-02-16 20:22:55 +01003802 hlua_class_function(gL.T, "get_headers", hlua_session_getheaders);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003803 hlua_class_function(gL.T, "set_priv", hlua_setpriv);
3804 hlua_class_function(gL.T, "get_priv", hlua_getpriv);
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01003805 hlua_class_function(gL.T, "req_channel", hlua_txn_req_channel);
3806 hlua_class_function(gL.T, "res_channel", hlua_txn_res_channel);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003807 hlua_class_function(gL.T, "close", hlua_txn_close);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003808
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003809 lua_settable(gL.T, -3);
3810
3811 /* Register previous table in the registry with reference and named entry. */
3812 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
3813 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
3814 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003815
3816 /*
3817 *
3818 * Register class Socket
3819 *
3820 */
3821
3822 /* Create and fill the metatable. */
3823 lua_newtable(gL.T);
3824
3825 /* Create and fille the __index entry. */
3826 lua_pushstring(gL.T, "__index");
3827 lua_newtable(gL.T);
3828
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003829#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003830 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003831#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003832 hlua_class_function(gL.T, "connect", hlua_socket_connect);
3833 hlua_class_function(gL.T, "send", hlua_socket_send);
3834 hlua_class_function(gL.T, "receive", hlua_socket_receive);
3835 hlua_class_function(gL.T, "close", hlua_socket_close);
3836 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
3837 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
3838 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
3839 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
3840
3841 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
3842
3843 /* Register the garbage collector entry. */
3844 lua_pushstring(gL.T, "__gc");
3845 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
3846 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
3847
3848 /* Register previous table in the registry with reference and named entry. */
3849 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
3850 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
3851 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
3852 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
3853
3854 /* Proxy and server configuration initialisation. */
3855 memset(&socket_proxy, 0, sizeof(socket_proxy));
3856 init_new_proxy(&socket_proxy);
3857 socket_proxy.parent = NULL;
3858 socket_proxy.last_change = now.tv_sec;
3859 socket_proxy.id = "LUA-SOCKET";
3860 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
3861 socket_proxy.maxconn = 0;
3862 socket_proxy.accept = NULL;
3863 socket_proxy.options2 |= PR_O2_INDEPSTR;
3864 socket_proxy.srv = NULL;
3865 socket_proxy.conn_retries = 0;
3866 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
3867
3868 /* Init TCP server: unchanged parameters */
3869 memset(&socket_tcp, 0, sizeof(socket_tcp));
3870 socket_tcp.next = NULL;
3871 socket_tcp.proxy = &socket_proxy;
3872 socket_tcp.obj_type = OBJ_TYPE_SERVER;
3873 LIST_INIT(&socket_tcp.actconns);
3874 LIST_INIT(&socket_tcp.pendconns);
3875 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
3876 socket_tcp.last_change = 0;
3877 socket_tcp.id = "LUA-TCP-CONN";
3878 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
3879 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
3880 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
3881
3882 /* XXX: Copy default parameter from default server,
3883 * but the default server is not initialized.
3884 */
3885 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
3886 socket_tcp.minconn = socket_proxy.defsrv.minconn;
3887 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
3888 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
3889 socket_tcp.onerror = socket_proxy.defsrv.onerror;
3890 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
3891 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
3892 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
3893 socket_tcp.uweight = socket_proxy.defsrv.iweight;
3894 socket_tcp.iweight = socket_proxy.defsrv.iweight;
3895
3896 socket_tcp.check.status = HCHK_STATUS_INI;
3897 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
3898 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
3899 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
3900 socket_tcp.check.server = &socket_tcp;
3901
3902 socket_tcp.agent.status = HCHK_STATUS_INI;
3903 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
3904 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
3905 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
3906 socket_tcp.agent.server = &socket_tcp;
3907
3908 socket_tcp.xprt = &raw_sock;
3909
3910#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003911 /* Init TCP server: unchanged parameters */
3912 memset(&socket_ssl, 0, sizeof(socket_ssl));
3913 socket_ssl.next = NULL;
3914 socket_ssl.proxy = &socket_proxy;
3915 socket_ssl.obj_type = OBJ_TYPE_SERVER;
3916 LIST_INIT(&socket_ssl.actconns);
3917 LIST_INIT(&socket_ssl.pendconns);
3918 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
3919 socket_ssl.last_change = 0;
3920 socket_ssl.id = "LUA-SSL-CONN";
3921 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
3922 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
3923 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
3924
3925 /* XXX: Copy default parameter from default server,
3926 * but the default server is not initialized.
3927 */
3928 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
3929 socket_ssl.minconn = socket_proxy.defsrv.minconn;
3930 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
3931 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
3932 socket_ssl.onerror = socket_proxy.defsrv.onerror;
3933 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
3934 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
3935 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
3936 socket_ssl.uweight = socket_proxy.defsrv.iweight;
3937 socket_ssl.iweight = socket_proxy.defsrv.iweight;
3938
3939 socket_ssl.check.status = HCHK_STATUS_INI;
3940 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
3941 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
3942 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
3943 socket_ssl.check.server = &socket_ssl;
3944
3945 socket_ssl.agent.status = HCHK_STATUS_INI;
3946 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
3947 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
3948 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
3949 socket_ssl.agent.server = &socket_ssl;
3950
3951 socket_ssl.xprt = &raw_sock;
3952
3953 args[0] = "ssl";
3954 args[1] = "verify";
3955 args[2] = "none";
3956 args[3] = NULL;
3957
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003958 for (idx = 0; idx < 3; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003959 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
3960 /*
3961 *
3962 * If the keyword is not known, we can search in the registered
3963 * server keywords. This is usefull to configure special SSL
3964 * features like client certificates and ssl_verify.
3965 *
3966 */
3967 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
3968 if (tmp_error != 0) {
3969 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
3970 abort(); /* This must be never arrives because the command line
3971 not editable by the user. */
3972 }
3973 idx += kw->skip;
3974 }
3975 }
3976
3977 /* Initialize SSL server. */
3978 if (socket_ssl.xprt == &ssl_sock) {
3979 socket_ssl.use_ssl = 1;
3980 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
3981 }
3982#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01003983}