blob: d59a462d5d948ce8d85d3671059d9b6e96dc1dbc [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 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010071static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010072static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010073static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010074static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010075static int class_converters_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010076
Thierry FOURNIERbd413492015-03-03 16:52:26 +010077/* Global Lua execution timeout. By default Lua, execution linked
78 * with session (actions, sample-fetches and converters) have a
79 * short timeout. Lua linked with tasks doesn't have a timeout
80 * because a task may remain alive during all the haproxy execution.
81 */
82static unsigned int hlua_timeout_session = 4000; /* session timeout. */
83static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
84
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010085/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
86 * it is used for preventing infinite loops.
87 *
88 * I test the scheer with an infinite loop containing one incrementation
89 * and one test. I run this loop between 10 seconds, I raise a ceil of
90 * 710M loops from one interrupt each 9000 instructions, so I fix the value
91 * to one interrupt each 10 000 instructions.
92 *
93 * configured | Number of
94 * instructions | loops executed
95 * between two | in milions
96 * forced yields |
97 * ---------------+---------------
98 * 10 | 160
99 * 500 | 670
100 * 1000 | 680
101 * 5000 | 700
102 * 7000 | 700
103 * 8000 | 700
104 * 9000 | 710 <- ceil
105 * 10000 | 710
106 * 100000 | 710
107 * 1000000 | 710
108 *
109 */
110static unsigned int hlua_nb_instruction = 10000;
111
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100112/* These functions converts types between HAProxy internal args or
113 * sample and LUA types. Another function permits to check if the
114 * LUA stack contains arguments according with an required ARG_T
115 * format.
116 */
117static int hlua_arg2lua(lua_State *L, const struct arg *arg);
118static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
119__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp, unsigned int mask);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100120static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100121static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100122static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
123
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100124/* Used to check an Lua function type in the stack. It creates and
125 * returns a reference of the function. This function throws an
126 * error if the rgument is not a "function".
127 */
128__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
129{
130 if (!lua_isfunction(L, argno)) {
131 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
132 WILL_LJMP(luaL_argerror(L, argno, msg));
133 }
134 lua_pushvalue(L, argno);
135 return luaL_ref(L, LUA_REGISTRYINDEX);
136}
137
138/* The three following functions are useful for adding entries
139 * in a table. These functions takes a string and respectively an
140 * integer, a string or a function and add it to the table in the
141 * top of the stack.
142 *
143 * These functions throws an error if no more stack size is
144 * available.
145 */
146__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100147 int value)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100148{
149 if (!lua_checkstack(L, 2))
150 WILL_LJMP(luaL_error(L, "full stack"));
151 lua_pushstring(L, name);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100152 lua_pushinteger(L, value);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100153 lua_settable(L, -3);
154}
155__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
156 const char *value)
157{
158 if (!lua_checkstack(L, 2))
159 WILL_LJMP(luaL_error(L, "full stack"));
160 lua_pushstring(L, name);
161 lua_pushstring(L, value);
162 lua_settable(L, -3);
163}
164__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
165 int (*function)(lua_State *L))
166{
167 if (!lua_checkstack(L, 2))
168 WILL_LJMP(luaL_error(L, "full stack"));
169 lua_pushstring(L, name);
170 lua_pushcclosure(L, function, 0);
171 lua_settable(L, -3);
172}
173
174/* This function check the number of arguments available in the
175 * stack. If the number of arguments available is not the same
176 * then <nb> an error is throwed.
177 */
178__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
179{
180 if (lua_gettop(L) == nb)
181 return;
182 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
183}
184
185/* Return true if the data in stack[<ud>] is an object of
186 * type <class_ref>.
187 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100188static int hlua_metaistype(lua_State *L, int ud, int class_ref)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100189{
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100190 if (!lua_getmetatable(L, ud))
191 return 0;
192
193 lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
194 if (!lua_rawequal(L, -1, -2)) {
195 lua_pop(L, 2);
196 return 0;
197 }
198
199 lua_pop(L, 2);
200 return 1;
201}
202
203/* Return an object of the expected type, or throws an error. */
204__LJMP static void *hlua_checkudata(lua_State *L, int ud, int class_ref)
205{
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100206 void *p;
207
208 /* Check if the stack entry is an array. */
209 if (!lua_istable(L, ud))
210 WILL_LJMP(luaL_argerror(L, ud, NULL));
211 /* Check if the metadata have the expected type. */
212 if (!hlua_metaistype(L, ud, class_ref))
213 WILL_LJMP(luaL_argerror(L, ud, NULL));
214 /* Push on the stack at the entry [0] of the table. */
215 lua_rawgeti(L, ud, 0);
216 /* Check if this entry is userdata. */
217 p = lua_touserdata(L, -1);
218 if (!p)
219 WILL_LJMP(luaL_argerror(L, ud, NULL));
220 /* Remove the entry returned by lua_rawgeti(). */
221 lua_pop(L, 1);
222 /* Return the associated struct. */
223 return p;
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100224}
225
226/* This fucntion push an error string prefixed by the file name
227 * and the line number where the error is encountered.
228 */
229static int hlua_pusherror(lua_State *L, const char *fmt, ...)
230{
231 va_list argp;
232 va_start(argp, fmt);
233 luaL_where(L, 1);
234 lua_pushvfstring(L, fmt, argp);
235 va_end(argp);
236 lua_concat(L, 2);
237 return 1;
238}
239
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100240/* This function register a new signal. "lua" is the current lua
241 * execution context. It contains a pointer to the associated task.
242 * "link" is a list head attached to an other task that must be wake
243 * the lua task if an event occurs. This is useful with external
244 * events like TCP I/O or sleep functions. This funcion allocate
245 * memory for the signal.
246 */
247static int hlua_com_new(struct hlua *lua, struct list *link)
248{
249 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
250 if (!com)
251 return 0;
252 LIST_ADDQ(&lua->com, &com->purge_me);
253 LIST_ADDQ(link, &com->wake_me);
254 com->task = lua->task;
255 return 1;
256}
257
258/* This function purge all the pending signals when the LUA execution
259 * is finished. This prevent than a coprocess try to wake a deleted
260 * task. This function remove the memory associated to the signal.
261 */
262static void hlua_com_purge(struct hlua *lua)
263{
264 struct hlua_com *com, *back;
265
266 /* Delete all pending communication signals. */
267 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
268 LIST_DEL(&com->purge_me);
269 LIST_DEL(&com->wake_me);
270 pool_free2(pool2_hlua_com, com);
271 }
272}
273
274/* This function sends signals. It wakes all the tasks attached
275 * to a list head, and remove the signal, and free the used
276 * memory.
277 */
278static void hlua_com_wake(struct list *wake)
279{
280 struct hlua_com *com, *back;
281
282 /* Wake task and delete all pending communication signals. */
283 list_for_each_entry_safe(com, back, wake, wake_me) {
284 LIST_DEL(&com->purge_me);
285 LIST_DEL(&com->wake_me);
286 task_wakeup(com->task, TASK_WOKEN_MSG);
287 pool_free2(pool2_hlua_com, com);
288 }
289}
290
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100291/* This functions is used with sample fetch and converters. It
292 * converts the HAProxy configuration argument in a lua stack
293 * values.
294 *
295 * It takes an array of "arg", and each entry of the array is
296 * converted and pushed in the LUA stack.
297 */
298static int hlua_arg2lua(lua_State *L, const struct arg *arg)
299{
300 switch (arg->type) {
301 case ARGT_SINT:
302 lua_pushinteger(L, arg->data.sint);
303 break;
304
305 case ARGT_UINT:
306 case ARGT_TIME:
307 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100308 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100309 break;
310
311 case ARGT_STR:
312 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
313 break;
314
315 case ARGT_IPV4:
316 case ARGT_IPV6:
317 case ARGT_MSK4:
318 case ARGT_MSK6:
319 case ARGT_FE:
320 case ARGT_BE:
321 case ARGT_TAB:
322 case ARGT_SRV:
323 case ARGT_USR:
324 case ARGT_MAP:
325 default:
326 lua_pushnil(L);
327 break;
328 }
329 return 1;
330}
331
332/* This function take one entrie in an LUA stack at the index "ud",
333 * and try to convert it in an HAProxy argument entry. This is useful
334 * with sample fetch wrappers. The input arguments are gived to the
335 * lua wrapper and converted as arg list by thi function.
336 */
337static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
338{
339 switch (lua_type(L, ud)) {
340
341 case LUA_TNUMBER:
342 case LUA_TBOOLEAN:
343 arg->type = ARGT_SINT;
344 arg->data.sint = lua_tointeger(L, ud);
345 break;
346
347 case LUA_TSTRING:
348 arg->type = ARGT_STR;
349 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
350 break;
351
352 case LUA_TUSERDATA:
353 case LUA_TNIL:
354 case LUA_TTABLE:
355 case LUA_TFUNCTION:
356 case LUA_TTHREAD:
357 case LUA_TLIGHTUSERDATA:
358 arg->type = ARGT_SINT;
359 arg->data.uint = 0;
360 break;
361 }
362 return 1;
363}
364
365/* the following functions are used to convert a struct sample
366 * in Lua type. This useful to convert the return of the
367 * fetchs or converters.
368 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100369static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100370{
371 switch (smp->type) {
372 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100373 case SMP_T_BOOL:
374 case SMP_T_UINT:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100375 lua_pushinteger(L, smp->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100376 break;
377
378 case SMP_T_BIN:
379 case SMP_T_STR:
380 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
381 break;
382
383 case SMP_T_METH:
384 switch (smp->data.meth.meth) {
385 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
386 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
387 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
388 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
389 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
390 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
391 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
392 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
393 case HTTP_METH_OTHER:
394 lua_pushlstring(L, smp->data.meth.str.str, smp->data.meth.str.len);
395 break;
396 default:
397 lua_pushnil(L);
398 break;
399 }
400 break;
401
402 case SMP_T_IPV4:
403 case SMP_T_IPV6:
404 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100405 if (sample_casts[smp->type][SMP_T_STR] &&
406 sample_casts[smp->type][SMP_T_STR](smp))
407 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
408 else
409 lua_pushnil(L);
410 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100411 default:
412 lua_pushnil(L);
413 break;
414 }
415 return 1;
416}
417
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100418/* the following functions are used to convert a struct sample
419 * in Lua strings. This is useful to convert the return of the
420 * fetchs or converters.
421 */
422static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
423{
424 switch (smp->type) {
425
426 case SMP_T_BIN:
427 case SMP_T_STR:
428 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
429 break;
430
431 case SMP_T_METH:
432 switch (smp->data.meth.meth) {
433 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
434 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
435 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
436 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
437 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
438 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
439 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
440 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
441 case HTTP_METH_OTHER:
442 lua_pushlstring(L, smp->data.meth.str.str, smp->data.meth.str.len);
443 break;
444 default:
445 lua_pushstring(L, "");
446 break;
447 }
448 break;
449
450 case SMP_T_SINT:
451 case SMP_T_BOOL:
452 case SMP_T_UINT:
453 case SMP_T_IPV4:
454 case SMP_T_IPV6:
455 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
456 if (sample_casts[smp->type][SMP_T_STR] &&
457 sample_casts[smp->type][SMP_T_STR](smp))
458 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
459 else
460 lua_pushstring(L, "");
461 break;
462 default:
463 lua_pushstring(L, "");
464 break;
465 }
466 return 1;
467}
468
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100469/* the following functions are used to convert an Lua type in a
470 * struct sample. This is useful to provide data from a converter
471 * to the LUA code.
472 */
473static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
474{
475 switch (lua_type(L, ud)) {
476
477 case LUA_TNUMBER:
478 smp->type = SMP_T_SINT;
479 smp->data.sint = lua_tointeger(L, ud);
480 break;
481
482
483 case LUA_TBOOLEAN:
484 smp->type = SMP_T_BOOL;
485 smp->data.uint = lua_toboolean(L, ud);
486 break;
487
488 case LUA_TSTRING:
489 smp->type = SMP_T_STR;
490 smp->flags |= SMP_F_CONST;
491 smp->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.str.len);
492 break;
493
494 case LUA_TUSERDATA:
495 case LUA_TNIL:
496 case LUA_TTABLE:
497 case LUA_TFUNCTION:
498 case LUA_TTHREAD:
499 case LUA_TLIGHTUSERDATA:
500 smp->type = SMP_T_BOOL;
501 smp->data.uint = 0;
502 break;
503 }
504 return 1;
505}
506
507/* This function check the "argp" builded by another conversion function
508 * is in accord with the expected argp defined by the "mask". The fucntion
509 * returns true or false. It can be adjust the types if there compatibles.
510 */
511__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp, unsigned int mask)
512{
513 int min_arg;
514 int idx;
515
516 idx = 0;
517 min_arg = ARGM(mask);
518 mask >>= ARGM_BITS;
519
520 while (1) {
521
522 /* Check oversize. */
523 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100524 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100525 }
526
527 /* Check for mandatory arguments. */
528 if (argp[idx].type == ARGT_STOP) {
529 if (idx + 1 < min_arg)
530 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
531 return 0;
532 }
533
534 /* Check for exceed the number of requiered argument. */
535 if ((mask & ARGT_MASK) == ARGT_STOP &&
536 argp[idx].type != ARGT_STOP) {
537 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
538 }
539
540 if ((mask & ARGT_MASK) == ARGT_STOP &&
541 argp[idx].type == ARGT_STOP) {
542 return 0;
543 }
544
545 /* Compatibility mask. */
546 switch (argp[idx].type) {
547 case ARGT_SINT:
548 switch (mask & ARGT_MASK) {
549 case ARGT_UINT: argp[idx].type = mask & ARGT_MASK; break;
550 case ARGT_TIME: argp[idx].type = mask & ARGT_MASK; break;
551 case ARGT_SIZE: argp[idx].type = mask & ARGT_MASK; break;
552 }
553 break;
554 }
555
556 /* Check for type of argument. */
557 if ((mask & ARGT_MASK) != argp[idx].type) {
558 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
559 arg_type_names[(mask & ARGT_MASK)],
560 arg_type_names[argp[idx].type & ARGT_MASK]);
561 WILL_LJMP(luaL_argerror(L, first + idx, msg));
562 }
563
564 /* Next argument. */
565 mask >>= ARGT_BITS;
566 idx++;
567 }
568}
569
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100570/*
571 * The following functions are used to make correspondance between the the
572 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100573 *
574 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100575 * - hlua_sethlua : create the association between hlua context and lua_state.
576 */
577static inline struct hlua *hlua_gethlua(lua_State *L)
578{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100579 struct hlua **hlua = lua_getextraspace(L);
580 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100581}
582static inline void hlua_sethlua(struct hlua *hlua)
583{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100584 struct hlua **hlua_store = lua_getextraspace(hlua->T);
585 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100586}
587
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100588/* This function just ensure that the yield will be always
589 * returned with a timeout and permit to set some flags
590 */
591__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100592 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100593{
594 struct hlua *hlua = hlua_gethlua(L);
595
596 /* Set the wake timeout. If timeout is required, we set
597 * the expiration time.
598 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100599 hlua->wake_time = tick_first(timeout, hlua->expire);
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100600
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100601 hlua->flags |= flags;
602
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100603 /* Process the yield. */
604 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
605}
606
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100607/* This function initialises the Lua environment stored in the session.
608 * It must be called at the start of the session. This function creates
609 * an LUA coroutine. It can not be use to crete the main LUA context.
610 */
611int hlua_ctx_init(struct hlua *lua, struct task *task)
612{
613 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100614 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100615 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100616 lua->T = lua_newthread(gL.T);
617 if (!lua->T) {
618 lua->Tref = LUA_REFNIL;
619 return 0;
620 }
621 hlua_sethlua(lua);
622 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
623 lua->task = task;
624 return 1;
625}
626
627/* Used to destroy the Lua coroutine when the attached session or task
628 * is destroyed. The destroy also the memory context. The struct "lua"
629 * is not freed.
630 */
631void hlua_ctx_destroy(struct hlua *lua)
632{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100633 if (!lua->T)
634 return;
635
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100636 /* Purge all the pending signals. */
637 hlua_com_purge(lua);
638
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100639 /* The thread is garbage collected by Lua. */
640 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
641 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
642}
643
644/* This function is used to restore the Lua context when a coroutine
645 * fails. This function copy the common memory between old coroutine
646 * and the new coroutine. The old coroutine is destroyed, and its
647 * replaced by the new coroutine.
648 * If the flag "keep_msg" is set, the last entry of the old is assumed
649 * as string error message and it is copied in the new stack.
650 */
651static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
652{
653 lua_State *T;
654 int new_ref;
655
656 /* Renew the main LUA stack doesn't have sense. */
657 if (lua == &gL)
658 return 0;
659
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100660 /* New Lua coroutine. */
661 T = lua_newthread(gL.T);
662 if (!T)
663 return 0;
664
665 /* Copy last error message. */
666 if (keep_msg)
667 lua_xmove(lua->T, T, 1);
668
669 /* Copy data between the coroutines. */
670 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
671 lua_xmove(lua->T, T, 1);
672 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
673
674 /* Destroy old data. */
675 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
676
677 /* The thread is garbage collected by Lua. */
678 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
679
680 /* Fill the struct with the new coroutine values. */
681 lua->Mref = new_ref;
682 lua->T = T;
683 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
684
685 /* Set context. */
686 hlua_sethlua(lua);
687
688 return 1;
689}
690
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100691void hlua_hook(lua_State *L, lua_Debug *ar)
692{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100693 struct hlua *hlua = hlua_gethlua(L);
694
695 /* Lua cannot yield when its returning from a function,
696 * so, we can fix the interrupt hook to 1 instruction,
697 * expecting that the function is finnished.
698 */
699 if (lua_gethookmask(L) & LUA_MASKRET) {
700 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
701 return;
702 }
703
704 /* restore the interrupt condition. */
705 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
706
707 /* If we interrupt the Lua processing in yieldable state, we yield.
708 * If the state is not yieldable, trying yield causes an error.
709 */
710 if (lua_isyieldable(L))
711 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
712
713 /* If we cannot yield, check the timeout. */
714 if (tick_is_expired(hlua->expire, now_ms)) {
715 lua_pushfstring(L, "execution timeout");
716 WILL_LJMP(lua_error(L));
717 }
718
719 /* Try to interrupt the process at the end of the current
720 * unyieldable function.
721 */
722 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100723}
724
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100725/* This function start or resumes the Lua stack execution. If the flag
726 * "yield_allowed" if no set and the LUA stack execution returns a yield
727 * The function return an error.
728 *
729 * The function can returns 4 values:
730 * - HLUA_E_OK : The execution is terminated without any errors.
731 * - HLUA_E_AGAIN : The execution must continue at the next associated
732 * task wakeup.
733 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
734 * the top of the stack.
735 * - HLUA_E_ERR : An error has occured without error message.
736 *
737 * If an error occured, the stack is renewed and it is ready to run new
738 * LUA code.
739 */
740static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
741{
742 int ret;
743 const char *msg;
744
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100745 HLUA_SET_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100746
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100747 /* If we want to resume the task, then check first the execution timeout.
748 * if it is reached, we can interrupt the Lua processing.
749 */
750 if (tick_is_expired(lua->expire, now_ms))
751 goto timeout_reached;
752
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100753resume_execution:
754
755 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
756 * instructions. it is used for preventing infinite loops.
757 */
758 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
759
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +0100760 /* Remove all flags except the running flags. */
761 lua->flags = HLUA_RUN;
762
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100763 /* Call the function. */
764 ret = lua_resume(lua->T, gL.T, lua->nargs);
765 switch (ret) {
766
767 case LUA_OK:
768 ret = HLUA_E_OK;
769 break;
770
771 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100772 /* Check if the execution timeout is expired. It it is the case, we
773 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100774 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100775 if (tick_is_expired(lua->expire, now_ms)) {
776
777timeout_reached:
778
779 lua_settop(lua->T, 0); /* Empty the stack. */
780 if (!lua_checkstack(lua->T, 1)) {
781 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100782 break;
783 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100784 lua_pushfstring(lua->T, "execution timeout");
785 ret = HLUA_E_ERRMSG;
786 break;
787 }
788 /* Process the forced yield. if the general yield is not allowed or
789 * if no task were associated this the current Lua execution
790 * coroutine, we resume the execution. Else we want to return in the
791 * scheduler and we want to be waked up again, to continue the
792 * current Lua execution. So we schedule our own task.
793 */
794 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100795 if (!yield_allowed || !lua->task)
796 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100797 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100798 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100799 if (!yield_allowed) {
800 lua_settop(lua->T, 0); /* Empty the stack. */
801 if (!lua_checkstack(lua->T, 1)) {
802 ret = HLUA_E_ERR;
803 break;
804 }
805 lua_pushfstring(lua->T, "yield not allowed");
806 ret = HLUA_E_ERRMSG;
807 break;
808 }
809 ret = HLUA_E_AGAIN;
810 break;
811
812 case LUA_ERRRUN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100813 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100814 if (!lua_checkstack(lua->T, 1)) {
815 ret = HLUA_E_ERR;
816 break;
817 }
818 msg = lua_tostring(lua->T, -1);
819 lua_settop(lua->T, 0); /* Empty the stack. */
820 lua_pop(lua->T, 1);
821 if (msg)
822 lua_pushfstring(lua->T, "runtime error: %s", msg);
823 else
824 lua_pushfstring(lua->T, "unknown runtime error");
825 ret = HLUA_E_ERRMSG;
826 break;
827
828 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100829 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100830 lua_settop(lua->T, 0); /* Empty the stack. */
831 if (!lua_checkstack(lua->T, 1)) {
832 ret = HLUA_E_ERR;
833 break;
834 }
835 lua_pushfstring(lua->T, "out of memory error");
836 ret = HLUA_E_ERRMSG;
837 break;
838
839 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100840 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100841 if (!lua_checkstack(lua->T, 1)) {
842 ret = HLUA_E_ERR;
843 break;
844 }
845 msg = lua_tostring(lua->T, -1);
846 lua_settop(lua->T, 0); /* Empty the stack. */
847 lua_pop(lua->T, 1);
848 if (msg)
849 lua_pushfstring(lua->T, "message handler error: %s", msg);
850 else
851 lua_pushfstring(lua->T, "message handler error");
852 ret = HLUA_E_ERRMSG;
853 break;
854
855 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100856 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100857 lua_settop(lua->T, 0); /* Empty the stack. */
858 if (!lua_checkstack(lua->T, 1)) {
859 ret = HLUA_E_ERR;
860 break;
861 }
862 lua_pushfstring(lua->T, "unknonwn error");
863 ret = HLUA_E_ERRMSG;
864 break;
865 }
866
867 switch (ret) {
868 case HLUA_E_AGAIN:
869 break;
870
871 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100872 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100873 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100874 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100875 break;
876
877 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100878 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100879 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100880 hlua_ctx_renew(lua, 0);
881 break;
882
883 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100884 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100885 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100886 break;
887 }
888
889 return ret;
890}
891
Thierry FOURNIER83758bb2015-02-04 13:21:04 +0100892/* This function is an LUA binding. It provides a function
893 * for deleting ACL from a referenced ACL file.
894 */
895__LJMP static int hlua_del_acl(lua_State *L)
896{
897 const char *name;
898 const char *key;
899 struct pat_ref *ref;
900
901 MAY_LJMP(check_args(L, 2, "del_acl"));
902
903 name = MAY_LJMP(luaL_checkstring(L, 1));
904 key = MAY_LJMP(luaL_checkstring(L, 2));
905
906 ref = pat_ref_lookup(name);
907 if (!ref)
908 WILL_LJMP(luaL_error(L, "'del_acl': unkown acl file '%s'", name));
909
910 pat_ref_delete(ref, key);
911 return 0;
912}
913
914/* This function is an LUA binding. It provides a function
915 * for deleting map entry from a referenced map file.
916 */
917static int hlua_del_map(lua_State *L)
918{
919 const char *name;
920 const char *key;
921 struct pat_ref *ref;
922
923 MAY_LJMP(check_args(L, 2, "del_map"));
924
925 name = MAY_LJMP(luaL_checkstring(L, 1));
926 key = MAY_LJMP(luaL_checkstring(L, 2));
927
928 ref = pat_ref_lookup(name);
929 if (!ref)
930 WILL_LJMP(luaL_error(L, "'del_map': unkown acl file '%s'", name));
931
932 pat_ref_delete(ref, key);
933 return 0;
934}
935
936/* This function is an LUA binding. It provides a function
937 * for adding ACL pattern from a referenced ACL file.
938 */
939static int hlua_add_acl(lua_State *L)
940{
941 const char *name;
942 const char *key;
943 struct pat_ref *ref;
944
945 MAY_LJMP(check_args(L, 2, "add_acl"));
946
947 name = MAY_LJMP(luaL_checkstring(L, 1));
948 key = MAY_LJMP(luaL_checkstring(L, 2));
949
950 ref = pat_ref_lookup(name);
951 if (!ref)
952 WILL_LJMP(luaL_error(L, "'add_acl': unkown acl file '%s'", name));
953
954 if (pat_ref_find_elt(ref, key) == NULL)
955 pat_ref_add(ref, key, NULL, NULL);
956 return 0;
957}
958
959/* This function is an LUA binding. It provides a function
960 * for setting map pattern and sample from a referenced map
961 * file.
962 */
963static int hlua_set_map(lua_State *L)
964{
965 const char *name;
966 const char *key;
967 const char *value;
968 struct pat_ref *ref;
969
970 MAY_LJMP(check_args(L, 3, "set_map"));
971
972 name = MAY_LJMP(luaL_checkstring(L, 1));
973 key = MAY_LJMP(luaL_checkstring(L, 2));
974 value = MAY_LJMP(luaL_checkstring(L, 3));
975
976 ref = pat_ref_lookup(name);
977 if (!ref)
978 WILL_LJMP(luaL_error(L, "'set_map': unkown map file '%s'", name));
979
980 if (pat_ref_find_elt(ref, key) != NULL)
981 pat_ref_set(ref, key, value, NULL);
982 else
983 pat_ref_add(ref, key, value, NULL);
984 return 0;
985}
986
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100987/* A class is a lot of memory that contain data. This data can be a table,
988 * an integer or user data. This data is associated with a metatable. This
989 * metatable have an original version registred in the global context with
990 * the name of the object (_G[<name>] = <metable> ).
991 *
992 * A metable is a table that modify the standard behavior of a standard
993 * access to the associated data. The entries of this new metatable are
994 * defined as is:
995 *
996 * http://lua-users.org/wiki/MetatableEvents
997 *
998 * __index
999 *
1000 * we access an absent field in a table, the result is nil. This is
1001 * true, but it is not the whole truth. Actually, such access triggers
1002 * the interpreter to look for an __index metamethod: If there is no
1003 * such method, as usually happens, then the access results in nil;
1004 * otherwise, the metamethod will provide the result.
1005 *
1006 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1007 * the key does not appear in the table, but the metatable has an __index
1008 * property:
1009 *
1010 * - if the value is a function, the function is called, passing in the
1011 * table and the key; the return value of that function is returned as
1012 * the result.
1013 *
1014 * - if the value is another table, the value of the key in that table is
1015 * asked for and returned (and if it doesn't exist in that table, but that
1016 * table's metatable has an __index property, then it continues on up)
1017 *
1018 * - Use "rawget(myTable,key)" to skip this metamethod.
1019 *
1020 * http://www.lua.org/pil/13.4.1.html
1021 *
1022 * __newindex
1023 *
1024 * Like __index, but control property assignment.
1025 *
1026 * __mode - Control weak references. A string value with one or both
1027 * of the characters 'k' and 'v' which specifies that the the
1028 * keys and/or values in the table are weak references.
1029 *
1030 * __call - Treat a table like a function. When a table is followed by
1031 * parenthesis such as "myTable( 'foo' )" and the metatable has
1032 * a __call key pointing to a function, that function is invoked
1033 * (passing any specified arguments) and the return value is
1034 * returned.
1035 *
1036 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1037 * called, if the metatable for myTable has a __metatable
1038 * key, the value of that key is returned instead of the
1039 * actual metatable.
1040 *
1041 * __tostring - Control string representation. When the builtin
1042 * "tostring( myTable )" function is called, if the metatable
1043 * for myTable has a __tostring property set to a function,
1044 * that function is invoked (passing myTable to it) and the
1045 * return value is used as the string representation.
1046 *
1047 * __len - Control table length. When the table length is requested using
1048 * the length operator ( '#' ), if the metatable for myTable has
1049 * a __len key pointing to a function, that function is invoked
1050 * (passing myTable to it) and the return value used as the value
1051 * of "#myTable".
1052 *
1053 * __gc - Userdata finalizer code. When userdata is set to be garbage
1054 * collected, if the metatable has a __gc field pointing to a
1055 * function, that function is first invoked, passing the userdata
1056 * to it. The __gc metamethod is not called for tables.
1057 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1058 *
1059 * Special metamethods for redefining standard operators:
1060 * http://www.lua.org/pil/13.1.html
1061 *
1062 * __add "+"
1063 * __sub "-"
1064 * __mul "*"
1065 * __div "/"
1066 * __unm "!"
1067 * __pow "^"
1068 * __concat ".."
1069 *
1070 * Special methods for redfining standar relations
1071 * http://www.lua.org/pil/13.2.html
1072 *
1073 * __eq "=="
1074 * __lt "<"
1075 * __le "<="
1076 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001077
1078/*
1079 *
1080 *
1081 * Class Socket
1082 *
1083 *
1084 */
1085
1086__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1087{
1088 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1089}
1090
1091/* This function is the handler called for each I/O on the established
1092 * connection. It is used for notify space avalaible to send or data
1093 * received.
1094 */
1095static void hlua_socket_handler(struct stream_interface *si)
1096{
1097 struct appctx *appctx = objt_appctx(si->end);
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001098 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001099
1100 /* Wakeup the main session if the client connection is closed. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001101 if (!c || channel_output_closed(si_ic(si)) || channel_input_closed(si_oc(si))) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001102 if (appctx->ctx.hlua.socket) {
1103 appctx->ctx.hlua.socket->s = NULL;
1104 appctx->ctx.hlua.socket = NULL;
1105 }
1106 si_shutw(si);
1107 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001108 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001109 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1110 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1111 return;
1112 }
1113
1114 if (!(c->flags & CO_FL_CONNECTED))
1115 return;
1116
1117 /* This function is called after the connect. */
1118 appctx->ctx.hlua.connected = 1;
1119
1120 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001121 if (channel_may_recv(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001122 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1123
1124 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001125 if (channel_is_empty(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001126 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1127}
1128
1129/* This function is called when the "struct session" is destroyed.
1130 * Remove the link from the object to this session.
1131 * Wake all the pending signals.
1132 */
1133static void hlua_socket_release(struct stream_interface *si)
1134{
1135 struct appctx *appctx = objt_appctx(si->end);
1136
1137 /* Remove my link in the original object. */
1138 if (appctx->ctx.hlua.socket)
1139 appctx->ctx.hlua.socket->s = NULL;
1140
1141 /* Wake all the task waiting for me. */
1142 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1143 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1144}
1145
1146/* If the garbage collectio of the object is launch, nobody
1147 * uses this object. If the session does not exists, just quit.
1148 * Send the shutdown signal to the session. In some cases,
1149 * pending signal can rest in the read and write lists. destroy
1150 * it.
1151 */
1152__LJMP static int hlua_socket_gc(lua_State *L)
1153{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001154 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001155 struct appctx *appctx;
1156
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001157 MAY_LJMP(check_args(L, 1, "__gc"));
1158
1159 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001160 if (!socket->s)
1161 return 0;
1162
1163 /* Remove all reference between the Lua stack and the coroutine session. */
1164 appctx = objt_appctx(socket->s->si[0].end);
1165 session_shutdown(socket->s, SN_ERR_KILLED);
1166 socket->s = NULL;
1167 appctx->ctx.hlua.socket = NULL;
1168
1169 return 0;
1170}
1171
1172/* The close function send shutdown signal and break the
1173 * links between the session and the object.
1174 */
1175__LJMP static int hlua_socket_close(lua_State *L)
1176{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001177 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001178 struct appctx *appctx;
1179
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001180 MAY_LJMP(check_args(L, 1, "close"));
1181
1182 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001183 if (!socket->s)
1184 return 0;
1185
1186 /* Close the session and remove the associated stop task. */
1187 session_shutdown(socket->s, SN_ERR_KILLED);
1188 appctx = objt_appctx(socket->s->si[0].end);
1189 appctx->ctx.hlua.socket = NULL;
1190 socket->s = NULL;
1191
1192 return 0;
1193}
1194
1195/* This Lua function assumes that the stack contain three parameters.
1196 * 1 - USERDATA containing a struct socket
1197 * 2 - INTEGER with values of the macro defined below
1198 * If the integer is -1, we must read at most one line.
1199 * If the integer is -2, we ust read all the data until the
1200 * end of the stream.
1201 * If the integer is positive value, we must read a number of
1202 * bytes corresponding to this value.
1203 */
1204#define HLSR_READ_LINE (-1)
1205#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001206__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001207{
1208 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1209 int wanted = lua_tointeger(L, 2);
1210 struct hlua *hlua = hlua_gethlua(L);
1211 struct appctx *appctx;
1212 int len;
1213 int nblk;
1214 char *blk1;
1215 int len1;
1216 char *blk2;
1217 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001218 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001219 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001220
1221 /* Check if this lua stack is schedulable. */
1222 if (!hlua || !hlua->task)
1223 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1224 "'frontend', 'backend' or 'task'"));
1225
1226 /* check for connection closed. If some data where read, return it. */
1227 if (!socket->s)
1228 goto connection_closed;
1229
Willy Tarreau81389672015-03-10 12:03:52 +01001230 oc = si_oc(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001231 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001232 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001233 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001234 if (nblk < 0) /* Connection close. */
1235 goto connection_closed;
1236 if (nblk == 0) /* No data avalaible. */
1237 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001238
1239 /* remove final \r\n. */
1240 if (nblk == 1) {
1241 if (blk1[len1-1] == '\n') {
1242 len1--;
1243 skip_at_end++;
1244 if (blk1[len1-1] == '\r') {
1245 len1--;
1246 skip_at_end++;
1247 }
1248 }
1249 }
1250 else {
1251 if (blk2[len2-1] == '\n') {
1252 len2--;
1253 skip_at_end++;
1254 if (blk2[len2-1] == '\r') {
1255 len2--;
1256 skip_at_end++;
1257 }
1258 }
1259 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001260 }
1261
1262 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001263 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001264 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001265 if (nblk < 0) /* Connection close. */
1266 goto connection_closed;
1267 if (nblk == 0) /* No data avalaible. */
1268 goto connection_empty;
1269 }
1270
1271 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001272 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001273 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001274 if (nblk < 0) /* Connection close. */
1275 goto connection_closed;
1276 if (nblk == 0) /* No data avalaible. */
1277 goto connection_empty;
1278
1279 if (len1 > wanted) {
1280 nblk = 1;
1281 len1 = wanted;
1282 } if (nblk == 2 && len1 + len2 > wanted)
1283 len2 = wanted - len1;
1284 }
1285
1286 len = len1;
1287
1288 luaL_addlstring(&socket->b, blk1, len1);
1289 if (nblk == 2) {
1290 len += len2;
1291 luaL_addlstring(&socket->b, blk2, len2);
1292 }
1293
1294 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001295 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001296
1297 /* Don't wait anything. */
1298 si_update(&socket->s->si[0]);
1299
1300 /* If the pattern reclaim to read all the data
1301 * in the connection, got out.
1302 */
1303 if (wanted == HLSR_READ_ALL)
1304 goto connection_empty;
1305 else if (wanted >= 0 && len < wanted)
1306 goto connection_empty;
1307
1308 /* Return result. */
1309 luaL_pushresult(&socket->b);
1310 return 1;
1311
1312connection_closed:
1313
1314 /* If the buffer containds data. */
1315 if (socket->b.n > 0) {
1316 luaL_pushresult(&socket->b);
1317 return 1;
1318 }
1319 lua_pushnil(L);
1320 lua_pushstring(L, "connection closed.");
1321 return 2;
1322
1323connection_empty:
1324
1325 appctx = objt_appctx(socket->s->si[0].end);
1326 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1327 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001328 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001329 return 0;
1330}
1331
1332/* This Lus function gets two parameters. The first one can be string
1333 * or a number. If the string is "*l", the user require one line. If
1334 * the string is "*a", the user require all the content of the stream.
1335 * If the value is a number, the user require a number of bytes equal
1336 * to the value. The default value is "*l" (a line).
1337 *
1338 * This paraeter with a variable type is converted in integer. This
1339 * integer takes this values:
1340 * -1 : read a line
1341 * -2 : read all the stream
1342 * >0 : amount if bytes.
1343 *
1344 * The second parameter is optinal. It contains a string that must be
1345 * concatenated with the read data.
1346 */
1347__LJMP static int hlua_socket_receive(struct lua_State *L)
1348{
1349 int wanted = HLSR_READ_LINE;
1350 const char *pattern;
1351 int type;
1352 char *error;
1353 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001354 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001355
1356 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1357 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1358
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001359 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001360
1361 /* check for pattern. */
1362 if (lua_gettop(L) >= 2) {
1363 type = lua_type(L, 2);
1364 if (type == LUA_TSTRING) {
1365 pattern = lua_tostring(L, 2);
1366 if (strcmp(pattern, "*a") == 0)
1367 wanted = HLSR_READ_ALL;
1368 else if (strcmp(pattern, "*l") == 0)
1369 wanted = HLSR_READ_LINE;
1370 else {
1371 wanted = strtoll(pattern, &error, 10);
1372 if (*error != '\0')
1373 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1374 }
1375 }
1376 else if (type == LUA_TNUMBER) {
1377 wanted = lua_tointeger(L, 2);
1378 if (wanted < 0)
1379 WILL_LJMP(luaL_error(L, "Unsupported size."));
1380 }
1381 }
1382
1383 /* Set pattern. */
1384 lua_pushinteger(L, wanted);
1385 lua_replace(L, 2);
1386
1387 /* init bufffer, and fiil it wih prefix. */
1388 luaL_buffinit(L, &socket->b);
1389
1390 /* Check prefix. */
1391 if (lua_gettop(L) >= 3) {
1392 if (lua_type(L, 3) != LUA_TSTRING)
1393 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1394 pattern = lua_tolstring(L, 3, &len);
1395 luaL_addlstring(&socket->b, pattern, len);
1396 }
1397
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001398 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001399}
1400
1401/* Write the Lua input string in the output buffer.
1402 * This fucntion returns a yield if no space are available.
1403 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001404static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001405{
1406 struct hlua_socket *socket;
1407 struct hlua *hlua = hlua_gethlua(L);
1408 struct appctx *appctx;
1409 size_t buf_len;
1410 const char *buf;
1411 int len;
1412 int send_len;
1413 int sent;
1414
1415 /* Check if this lua stack is schedulable. */
1416 if (!hlua || !hlua->task)
1417 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1418 "'frontend', 'backend' or 'task'"));
1419
1420 /* Get object */
1421 socket = MAY_LJMP(hlua_checksocket(L, 1));
1422 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001423 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001424
1425 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001426 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001427 lua_pushinteger(L, -1);
1428 return 1;
1429 }
1430
1431 /* Update the input buffer data. */
1432 buf += sent;
1433 send_len = buf_len - sent;
1434
1435 /* All the data are sent. */
1436 if (sent >= buf_len)
1437 return 1; /* Implicitly return the length sent. */
1438
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001439 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1440 * the request buffer if its not required.
1441 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001442 if (socket->s->req.buf->size == 0) {
Willy Tarreau78955f42014-12-28 13:09:02 +01001443 if (!session_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001444 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001445 goto hlua_socket_write_yield_return;
1446 }
1447 }
1448
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001449 /* Check for avalaible space. */
Willy Tarreau4e4292b2014-11-28 12:18:45 +01001450 len = buffer_total_space(si_ib(&socket->s->si[0]));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001451 if (len <= 0)
1452 goto hlua_socket_write_yield_return;
1453
1454 /* send data */
1455 if (len < send_len)
1456 send_len = len;
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001457 len = bi_putblk(si_ic(&socket->s->si[0]), buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001458
1459 /* "Not enough space" (-1), "Buffer too little to contain
1460 * the data" (-2) are not expected because the available length
1461 * is tested.
1462 * Other unknown error are also not expected.
1463 */
1464 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001465 if (len == -1)
1466 si_ic(&socket->s->si[0])->flags |= CF_WAKE_WRITE;
1467
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001468 MAY_LJMP(hlua_socket_close(L));
1469 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001470 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001471 return 1;
1472 }
1473
1474 /* update buffers. */
1475 si_update(&socket->s->si[0]);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001476 si_ic(&socket->s->si[0])->rex = TICK_ETERNITY;
1477 si_oc(&socket->s->si[0])->wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001478
1479 /* Update length sent. */
1480 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001481 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001482
1483 /* All the data buffer is sent ? */
1484 if (sent + len >= buf_len)
1485 return 1;
1486
1487hlua_socket_write_yield_return:
1488 appctx = objt_appctx(socket->s->si[0].end);
1489 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1490 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001491 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001492 return 0;
1493}
1494
1495/* This function initiate the send of data. It just check the input
1496 * parameters and push an integer in the Lua stack that contain the
1497 * amount of data writed in the buffer. This is used by the function
1498 * "hlua_socket_write_yield" that can yield.
1499 *
1500 * The Lua function gets between 3 and 4 parameters. The first one is
1501 * the associated object. The second is a string buffer. The third is
1502 * a facultative integer that represents where is the buffer position
1503 * of the start of the data that can send. The first byte is the
1504 * position "1". The default value is "1". The fourth argument is a
1505 * facultative integer that represents where is the buffer position
1506 * of the end of the data that can send. The default is the last byte.
1507 */
1508static int hlua_socket_send(struct lua_State *L)
1509{
1510 int i;
1511 int j;
1512 const char *buf;
1513 size_t buf_len;
1514
1515 /* Check number of arguments. */
1516 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1517 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1518
1519 /* Get the string. */
1520 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1521
1522 /* Get and check j. */
1523 if (lua_gettop(L) == 4) {
1524 j = MAY_LJMP(luaL_checkinteger(L, 4));
1525 if (j < 0)
1526 j = buf_len + j + 1;
1527 if (j > buf_len)
1528 j = buf_len + 1;
1529 lua_pop(L, 1);
1530 }
1531 else
1532 j = buf_len;
1533
1534 /* Get and check i. */
1535 if (lua_gettop(L) == 3) {
1536 i = MAY_LJMP(luaL_checkinteger(L, 3));
1537 if (i < 0)
1538 i = buf_len + i + 1;
1539 if (i > buf_len)
1540 i = buf_len + 1;
1541 lua_pop(L, 1);
1542 } else
1543 i = 1;
1544
1545 /* Check bth i and j. */
1546 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001547 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001548 return 1;
1549 }
1550 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001551 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001552 return 1;
1553 }
1554 if (i == 0)
1555 i = 1;
1556 if (j == 0)
1557 j = 1;
1558
1559 /* Pop the string. */
1560 lua_pop(L, 1);
1561
1562 /* Update the buffer length. */
1563 buf += i - 1;
1564 buf_len = j - i + 1;
1565 lua_pushlstring(L, buf, buf_len);
1566
1567 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001568 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001569
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001570 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001571}
1572
1573#define SOCKET_INFO_EXPANDED_FORM "[0000:0000:0000:0000:0000:0000:0000:0000]:12345"
1574static char _socket_info_expanded_form[] = SOCKET_INFO_EXPANDED_FORM;
1575#define SOCKET_INFO_MAX_LEN (sizeof(_socket_info_expanded_form))
1576__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
1577{
1578 static char buffer[SOCKET_INFO_MAX_LEN];
1579 int ret;
1580 int len;
1581 char *p;
1582
1583 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
1584 if (ret <= 0) {
1585 lua_pushnil(L);
1586 return 1;
1587 }
1588
1589 if (ret == AF_UNIX) {
1590 lua_pushstring(L, buffer+1);
1591 return 1;
1592 }
1593 else if (ret == AF_INET6) {
1594 buffer[0] = '[';
1595 len = strlen(buffer);
1596 buffer[len] = ']';
1597 len++;
1598 buffer[len] = ':';
1599 len++;
1600 p = buffer;
1601 }
1602 else if (ret == AF_INET) {
1603 p = buffer + 1;
1604 len = strlen(p);
1605 p[len] = ':';
1606 len++;
1607 }
1608 else {
1609 lua_pushnil(L);
1610 return 1;
1611 }
1612
1613 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
1614 lua_pushnil(L);
1615 return 1;
1616 }
1617
1618 lua_pushstring(L, p);
1619 return 1;
1620}
1621
1622/* Returns information about the peer of the connection. */
1623__LJMP static int hlua_socket_getpeername(struct lua_State *L)
1624{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001625 struct hlua_socket *socket;
1626 struct connection *conn;
1627
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001628 MAY_LJMP(check_args(L, 1, "getpeername"));
1629
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001630 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001631
1632 /* Check if the tcp object is avalaible. */
1633 if (!socket->s) {
1634 lua_pushnil(L);
1635 return 1;
1636 }
1637
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001638 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001639 if (!conn) {
1640 lua_pushnil(L);
1641 return 1;
1642 }
1643
1644 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
1645 unsigned int salen = sizeof(conn->addr.to);
1646 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
1647 lua_pushnil(L);
1648 return 1;
1649 }
1650 conn->flags |= CO_FL_ADDR_TO_SET;
1651 }
1652
1653 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
1654}
1655
1656/* Returns information about my connection side. */
1657static int hlua_socket_getsockname(struct lua_State *L)
1658{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001659 struct hlua_socket *socket;
1660 struct connection *conn;
1661
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001662 MAY_LJMP(check_args(L, 1, "getsockname"));
1663
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001664 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001665
1666 /* Check if the tcp object is avalaible. */
1667 if (!socket->s) {
1668 lua_pushnil(L);
1669 return 1;
1670 }
1671
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001672 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001673 if (!conn) {
1674 lua_pushnil(L);
1675 return 1;
1676 }
1677
1678 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
1679 unsigned int salen = sizeof(conn->addr.from);
1680 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
1681 lua_pushnil(L);
1682 return 1;
1683 }
1684 conn->flags |= CO_FL_ADDR_FROM_SET;
1685 }
1686
1687 return hlua_socket_info(L, &conn->addr.from);
1688}
1689
1690/* This struct define the applet. */
1691static struct si_applet update_applet = {
1692 .obj_type = OBJ_TYPE_APPLET,
1693 .name = "<LUA_TCP>",
1694 .fct = hlua_socket_handler,
1695 .release = hlua_socket_release,
1696};
1697
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001698__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001699{
1700 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1701 struct hlua *hlua = hlua_gethlua(L);
1702 struct appctx *appctx;
1703
1704 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001705 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001706 lua_pushnil(L);
1707 lua_pushstring(L, "Can't connect");
1708 return 2;
1709 }
1710
1711 appctx = objt_appctx(socket->s->si[0].end);
1712
1713 /* Check for connection established. */
1714 if (appctx->ctx.hlua.connected) {
1715 lua_pushinteger(L, 1);
1716 return 1;
1717 }
1718
1719 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1720 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001721 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001722 return 0;
1723}
1724
1725/* This function fail or initite the connection. */
1726__LJMP static int hlua_socket_connect(struct lua_State *L)
1727{
1728 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001729 int port;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001730 const char *ip;
1731 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01001732 struct hlua *hlua;
1733 struct appctx *appctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001734
1735 MAY_LJMP(check_args(L, 3, "connect"));
1736
1737 /* Get args. */
1738 socket = MAY_LJMP(hlua_checksocket(L, 1));
1739 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001740 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001741
Willy Tarreau350f4872014-11-28 14:42:25 +01001742 conn = si_alloc_conn(&socket->s->si[1], 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001743 if (!conn)
1744 WILL_LJMP(luaL_error(L, "connect: internal error"));
1745
1746 /* Parse ip address. */
1747 conn->addr.to.ss_family = AF_UNSPEC;
1748 if (!str2ip2(ip, &conn->addr.to, 0))
1749 WILL_LJMP(luaL_error(L, "connect: cannot parse ip address '%s'", ip));
1750
1751 /* Set port. */
1752 if (conn->addr.to.ss_family == AF_INET)
1753 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
1754 else if (conn->addr.to.ss_family == AF_INET6)
1755 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
1756
1757 /* it is important not to call the wakeup function directly but to
1758 * pass through task_wakeup(), because this one knows how to apply
1759 * priorities to tasks.
1760 */
1761 task_wakeup(socket->s->task, TASK_WOKEN_INIT);
1762
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01001763 hlua = hlua_gethlua(L);
1764 appctx = objt_appctx(socket->s->si[0].end);
1765 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1766 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001767 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001768
1769 return 0;
1770}
1771
Baptiste Assmann84bb4932015-03-02 21:40:06 +01001772#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001773__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
1774{
1775 struct hlua_socket *socket;
1776
1777 MAY_LJMP(check_args(L, 3, "connect_ssl"));
1778 socket = MAY_LJMP(hlua_checksocket(L, 1));
1779 socket->s->target = &socket_ssl.obj_type;
1780 return MAY_LJMP(hlua_socket_connect(L));
1781}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01001782#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001783
1784__LJMP static int hlua_socket_setoption(struct lua_State *L)
1785{
1786 return 0;
1787}
1788
1789__LJMP static int hlua_socket_settimeout(struct lua_State *L)
1790{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001791 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001792 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001793
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001794 MAY_LJMP(check_args(L, 2, "settimeout"));
1795
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001796 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001797 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001798
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001799 socket->s->req.rto = tmout;
1800 socket->s->req.wto = tmout;
1801 socket->s->res.rto = tmout;
1802 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001803
1804 return 0;
1805}
1806
1807__LJMP static int hlua_socket_new(lua_State *L)
1808{
1809 struct hlua_socket *socket;
1810 struct appctx *appctx;
1811
1812 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01001813 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001814 hlua_pusherror(L, "socket: full stack");
1815 goto out_fail_conf;
1816 }
1817
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01001818 /* Create the object: obj[0] = userdata. */
1819 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001820 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01001821 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001822 memset(socket, 0, sizeof(*socket));
1823
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01001824 /* Check if the various memory pools are intialized. */
Willy Tarreaua27dc192014-11-27 22:10:04 +01001825 if (!pool2_session || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01001826 hlua_pusherror(L, "socket: uninitialized pools.");
1827 goto out_fail_conf;
1828 }
1829
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001830 /* Pop a class session metatable and affect it to the userdata. */
1831 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
1832 lua_setmetatable(L, -2);
1833
1834 /*
1835 *
1836 * Get memory for the request.
1837 *
1838 */
1839
1840 socket->s = pool_alloc2(pool2_session);
1841 if (!socket->s) {
1842 hlua_pusherror(L, "socket: out of memory");
1843 goto out_fail_conf;
1844 }
1845
1846 socket->s->task = task_new();
1847 if (!socket->s->task) {
1848 hlua_pusherror(L, "socket: out of memory");
1849 goto out_free_session;
1850 }
1851
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001852 socket->s->req.buf = pool_alloc2(pool2_buffer);
1853 if (!socket->s->req.buf) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001854 hlua_pusherror(L, "socket: out of memory");
1855 goto out_fail_req_buf;
1856 }
1857
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001858 socket->s->res.buf = pool_alloc2(pool2_buffer);
1859 if (!socket->s->res.buf) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001860 hlua_pusherror(L, "socket: out of memory");
1861 goto out_fail_rep_buf;
1862 }
1863
1864 /* Configura empty Lua for the session. */
1865 socket->s->hlua.T = NULL;
1866 socket->s->hlua.Tref = LUA_REFNIL;
1867 socket->s->hlua.Mref = LUA_REFNIL;
1868 socket->s->hlua.nargs = 0;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001869 socket->s->hlua.flags = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001870 LIST_INIT(&socket->s->hlua.com);
1871
1872 /* session initialisation. */
1873 session_init_srv_conn(socket->s);
1874
1875 /*
1876 *
1877 * Configure the associated task.
1878 *
1879 */
1880
1881 /* This is the dedicated function to process the session. This function
1882 * is able to establish the conection, process the timeouts, etc ...
1883 */
1884 socket->s->task->process = process_session;
1885
1886 /* Back reference to session. This is used by process_session(). */
1887 socket->s->task->context = socket->s;
1888
1889 /* The priority of the task is normal. */
1890 socket->s->task->nice = 0;
1891
1892 /* Init the next run to eternity. Later in this function, this task is
1893 * waked.
1894 */
1895 socket->s->task->expire = TICK_ETERNITY;
1896
1897 /*
1898 *
1899 * Initialize the attached buffers
1900 *
1901 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001902 socket->s->req.buf->size = global.tune.bufsize;
1903 socket->s->res.buf->size = global.tune.bufsize;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001904
1905 /*
1906 *
1907 * Initialize channels.
1908 *
1909 */
1910
1911 /* This function reset the struct. It must be called
1912 * before the configuration.
1913 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001914 channel_init(&socket->s->req);
1915 channel_init(&socket->s->res);
Willy Tarreauef573c02014-11-28 14:17:09 +01001916 socket->s->res.flags |= CF_ISRESP;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001917
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001918 socket->s->req.analysers = 0;
1919 socket->s->req.rto = socket_proxy.timeout.client;
1920 socket->s->req.wto = socket_proxy.timeout.server;
1921 socket->s->req.rex = TICK_ETERNITY;
1922 socket->s->req.wex = TICK_ETERNITY;
1923 socket->s->req.analyse_exp = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001924
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001925 socket->s->res.analysers = 0;
1926 socket->s->res.rto = socket_proxy.timeout.server;
1927 socket->s->res.wto = socket_proxy.timeout.client;
1928 socket->s->res.rex = TICK_ETERNITY;
1929 socket->s->res.wex = TICK_ETERNITY;
1930 socket->s->res.analyse_exp = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001931
1932 /*
1933 *
1934 * Configure the session.
1935 *
1936 */
1937
1938 /* The session dont have listener. The listener is used with real
1939 * proxies.
1940 */
1941 socket->s->listener = NULL;
1942
1943 /* The flags are initialized to 0. Values are setted later. */
1944 socket->s->flags = 0;
1945
1946 /* Assign the configured proxy to the new session. */
1947 socket->s->be = &socket_proxy;
1948 socket->s->fe = &socket_proxy;
1949
1950 /* XXX: Set namy variables */
1951 socket->s->store_count = 0;
1952 memset(socket->s->stkctr, 0, sizeof(socket->s->stkctr));
1953
1954 /* Configure logs. */
1955 socket->s->logs.logwait = 0;
1956 socket->s->logs.level = 0;
1957 socket->s->logs.accept_date = date; /* user-visible date for logging */
1958 socket->s->logs.tv_accept = now; /* corrected date for internal use */
1959 socket->s->do_log = NULL;
1960
1961 /* Function used if an error is occured. */
1962 socket->s->srv_error = default_srv_error;
1963
1964 /* Init the list of buffers. */
1965 LIST_INIT(&socket->s->buffer_wait);
1966
1967 /* Dont configure the unique ID. */
1968 socket->s->uniq_id = 0;
1969 socket->s->unique_id = NULL;
1970
1971 /* XXX: ? */
1972 socket->s->pend_pos = NULL;
1973
1974 /* XXX: See later. */
1975 socket->s->txn.sessid = NULL;
1976 socket->s->txn.srv_cookie = NULL;
1977 socket->s->txn.cli_cookie = NULL;
1978 socket->s->txn.uri = NULL;
1979 socket->s->txn.req.cap = NULL;
1980 socket->s->txn.rsp.cap = NULL;
1981 socket->s->txn.hdr_idx.v = NULL;
1982 socket->s->txn.hdr_idx.size = 0;
1983 socket->s->txn.hdr_idx.used = 0;
1984
1985 /* Configure "left" stream interface as applet. This "si" produce
1986 * and use the data received from the server. The applet is initialized
1987 * and is attached to the stream interface.
1988 */
1989
1990 /* The data producer is already connected. It is the applet. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001991 socket->s->req.flags = CF_READ_ATTACHED;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001992
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001993 channel_auto_connect(&socket->s->req); /* don't wait to establish connection */
1994 channel_auto_close(&socket->s->req); /* let the producer forward close requests */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001995
Willy Tarreaua5f5d8d2014-11-28 11:26:07 +01001996 socket->s->si[0].flags = SI_FL_NONE;
Willy Tarreau819d3322014-11-28 12:12:34 +01001997 si_reset(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001998 si_set_state(&socket->s->si[0], SI_ST_EST); /* connection established (resource exists) */
1999
2000 appctx = stream_int_register_handler(&socket->s->si[0], &update_applet);
2001 if (!appctx)
2002 goto out_fail_conn1;
2003 appctx->ctx.hlua.socket = socket;
2004 appctx->ctx.hlua.connected = 0;
2005 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2006 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
2007
2008 /* Configure "right" stream interface. this "si" is used to connect
2009 * and retrieve data from the server. The connection is initialized
2010 * with the "struct server".
2011 */
Willy Tarreaua5f5d8d2014-11-28 11:26:07 +01002012 socket->s->si[1].flags = SI_FL_ISBACK;
Willy Tarreau819d3322014-11-28 12:12:34 +01002013 si_reset(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002014 si_set_state(&socket->s->si[1], SI_ST_INI);
2015 socket->s->si[1].conn_retries = socket_proxy.conn_retries;
2016
2017 /* Force destination server. */
2018 socket->s->flags |= SN_DIRECT | SN_ASSIGNED | SN_ADDR_SET | SN_BE_ASSIGNED;
2019 socket->s->target = &socket_tcp.obj_type;
2020
2021 /* This session is added to te lists of alive sessions. */
2022 LIST_ADDQ(&sessions, &socket->s->list);
2023
2024 /* XXX: I think that this list is used by stats. */
2025 LIST_INIT(&socket->s->back_refs);
2026
2027 /* Update statistics counters. */
2028 socket_proxy.feconn++; /* beconn will be increased later */
2029 jobs++;
2030 totalconn++;
2031
2032 /* Return yield waiting for connection. */
2033 return 1;
2034
2035out_fail_conn1:
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002036 pool_free2(pool2_buffer, socket->s->res.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002037out_fail_rep_buf:
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002038 pool_free2(pool2_buffer, socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002039out_fail_req_buf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002040 task_free(socket->s->task);
2041out_free_session:
2042 pool_free2(pool2_session, socket->s);
2043out_fail_conf:
2044 WILL_LJMP(lua_error(L));
2045 return 0;
2046}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002047
2048/*
2049 *
2050 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002051 * Class Channel
2052 *
2053 *
2054 */
2055
2056/* Returns the struct hlua_channel join to the class channel in the
2057 * stack entry "ud" or throws an argument error.
2058 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002059__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002060{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002061 return (struct channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002062}
2063
Willy Tarreau47860ed2015-03-10 14:07:50 +01002064/* Pushes the channel onto the top of the stack. If the stask does not have a
2065 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002066 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002067static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002068{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002069 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002070 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002071 return 0;
2072
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002073 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002074 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002075 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002076
2077 /* Pop a class sesison metatable and affect it to the userdata. */
2078 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2079 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002080 return 1;
2081}
2082
2083/* Duplicate all the data present in the input channel and put it
2084 * in a string LUA variables. Returns -1 and push a nil value in
2085 * the stack if the channel is closed and all the data are consumed,
2086 * returns 0 if no data are available, otherwise it returns the length
2087 * of the builded string.
2088 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002089static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002090{
2091 char *blk1;
2092 char *blk2;
2093 int len1;
2094 int len2;
2095 int ret;
2096 luaL_Buffer b;
2097
Willy Tarreau47860ed2015-03-10 14:07:50 +01002098 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002099 if (unlikely(ret == 0))
2100 return 0;
2101
2102 if (unlikely(ret < 0)) {
2103 lua_pushnil(L);
2104 return -1;
2105 }
2106
2107 luaL_buffinit(L, &b);
2108 luaL_addlstring(&b, blk1, len1);
2109 if (unlikely(ret == 2))
2110 luaL_addlstring(&b, blk2, len2);
2111 luaL_pushresult(&b);
2112
2113 if (unlikely(ret == 2))
2114 return len1 + len2;
2115 return len1;
2116}
2117
2118/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2119 * a yield. This function keep the data in the buffer.
2120 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002121__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002122{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002123 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002124
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002125 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2126
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002127 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002128 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002129 return 1;
2130}
2131
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002132/* Check arguments for the function "hlua_channel_dup_yield". */
2133__LJMP static int hlua_channel_dup(lua_State *L)
2134{
2135 MAY_LJMP(check_args(L, 1, "dup"));
2136 MAY_LJMP(hlua_checkchannel(L, 1));
2137 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2138}
2139
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002140/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2141 * a yield. This function consumes the data in the buffer. It returns
2142 * a string containing the data or a nil pointer if no data are available
2143 * and the channel is closed.
2144 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002145__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002146{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002147 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002148 int ret;
2149
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002150 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002151
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002152 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002153 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002154 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002155
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002156 if (unlikely(ret == -1))
2157 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002158
Willy Tarreau47860ed2015-03-10 14:07:50 +01002159 chn->buf->i -= ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002160 return 1;
2161}
2162
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002163/* Check arguments for the fucntion "hlua_channel_get_yield". */
2164__LJMP static int hlua_channel_get(lua_State *L)
2165{
2166 MAY_LJMP(check_args(L, 1, "get"));
2167 MAY_LJMP(hlua_checkchannel(L, 1));
2168 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2169}
2170
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002171/* This functions consumes and returns one line. If the channel is closed,
2172 * and the last data does not contains a final '\n', the data are returned
2173 * without the final '\n'. When no more data are avalaible, it returns nil
2174 * value.
2175 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002176__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002177{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002178 char *blk1;
2179 char *blk2;
2180 int len1;
2181 int len2;
2182 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002183 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002184 int ret;
2185 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002186
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002187 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2188
Willy Tarreau47860ed2015-03-10 14:07:50 +01002189 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002190 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002191 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002192
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002193 if (ret == -1) {
2194 lua_pushnil(L);
2195 return 1;
2196 }
2197
2198 luaL_buffinit(L, &b);
2199 luaL_addlstring(&b, blk1, len1);
2200 len = len1;
2201 if (unlikely(ret == 2)) {
2202 luaL_addlstring(&b, blk2, len2);
2203 len += len2;
2204 }
2205 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002206 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002207 return 1;
2208}
2209
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002210/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2211__LJMP static int hlua_channel_getline(lua_State *L)
2212{
2213 MAY_LJMP(check_args(L, 1, "getline"));
2214 MAY_LJMP(hlua_checkchannel(L, 1));
2215 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2216}
2217
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002218/* This function takes a string as input, and append it at the
2219 * input side of channel. If the data is too big, but a space
2220 * is probably available after sending some data, the function
2221 * yield. If the data is bigger than the buffer, or if the
2222 * channel is closed, it returns -1. otherwise, it returns the
2223 * amount of data writed.
2224 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002225__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002226{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002227 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002228 size_t len;
2229 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2230 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2231 int ret;
2232 int max;
2233
Willy Tarreau47860ed2015-03-10 14:07:50 +01002234 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002235 if (max > len - l)
2236 max = len - l;
2237
Willy Tarreau47860ed2015-03-10 14:07:50 +01002238 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002239 if (ret == -2 || ret == -3) {
2240 lua_pushinteger(L, -1);
2241 return 1;
2242 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002243 if (ret == -1) {
2244 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002245 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002246 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002247 l += ret;
2248 lua_pop(L, 1);
2249 lua_pushinteger(L, l);
2250
Willy Tarreau47860ed2015-03-10 14:07:50 +01002251 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2252 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002253 /* There are no space avalaible, and the output buffer is empty.
2254 * in this case, we cannot add more data, so we cannot yield,
2255 * we return the amount of copyied data.
2256 */
2257 return 1;
2258 }
2259 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002260 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002261 return 1;
2262}
2263
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002264/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002265 * of the writed string, or -1 if the channel is closed or if the
2266 * buffer size is too little for the data.
2267 */
2268__LJMP static int hlua_channel_append(lua_State *L)
2269{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002270 size_t len;
2271
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002272 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002273 MAY_LJMP(hlua_checkchannel(L, 1));
2274 MAY_LJMP(luaL_checklstring(L, 2, &len));
2275 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002276 lua_pushinteger(L, 0);
2277
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002278 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002279}
2280
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002281/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002282 * his process by cleaning the buffer. The result is a replacement
2283 * of the current data. It returns the length of the writed string,
2284 * or -1 if the channel is closed or if the buffer size is too
2285 * little for the data.
2286 */
2287__LJMP static int hlua_channel_set(lua_State *L)
2288{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002289 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002290
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002291 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002292 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002293 lua_pushinteger(L, 0);
2294
Willy Tarreau47860ed2015-03-10 14:07:50 +01002295 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002296
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002297 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002298}
2299
2300/* Append data in the output side of the buffer. This data is immediatly
2301 * sent. The fcuntion returns the ammount of data writed. If the buffer
2302 * cannot contains the data, the function yield. The function returns -1
2303 * if the channel is closed.
2304 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002305__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002306{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002307 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002308 size_t len;
2309 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2310 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2311 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002312 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002313
Willy Tarreau47860ed2015-03-10 14:07:50 +01002314 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002315 lua_pushinteger(L, -1);
2316 return 1;
2317 }
2318
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002319 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2320 * the request buffer if its not required.
2321 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002322 if (chn->buf->size == 0) {
2323 if (!session_alloc_recv_buffer(chn)) {
2324 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002325 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002326 }
2327 }
2328
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002329 /* the writed data will be immediatly sent, so we can check
2330 * the avalaible space without taking in account the reserve.
2331 * The reserve is guaranted for the processing of incoming
2332 * data, because the buffer will be flushed.
2333 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002334 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002335
2336 /* If there are no space avalaible, and the output buffer is empty.
2337 * in this case, we cannot add more data, so we cannot yield,
2338 * we return the amount of copyied data.
2339 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002340 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002341 return 1;
2342
2343 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002344 if (max > len - l)
2345 max = len - l;
2346
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002347 /* The buffer avalaible size may be not contiguous. This test
2348 * detects a non contiguous buffer and realign it.
2349 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002350 if (bi_space_for_replace(chn->buf) < max)
2351 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002352
2353 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002354 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002355
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002356 /* buffer replace considers that the input part is filled.
2357 * so, I must forward these new data in the output part.
2358 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002359 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002360
2361 l += max;
2362 lua_pop(L, 1);
2363 lua_pushinteger(L, l);
2364
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002365 /* If there are no space avalaible, and the output buffer is empty.
2366 * in this case, we cannot add more data, so we cannot yield,
2367 * we return the amount of copyied data.
2368 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002369 max = chn->buf->size - buffer_len(chn->buf);
2370 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002371 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002372
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002373 if (l < len) {
2374 /* If we are waiting for space in the response buffer, we
2375 * must set the flag WAKERESWR. This flag required the task
2376 * wake up if any activity is detected on the response buffer.
2377 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002378 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002379 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002380 else
2381 HLUA_SET_WAKEREQWR(hlua);
2382 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002383 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002384
2385 return 1;
2386}
2387
2388/* Just a wraper of "_hlua_channel_send". This wrapper permits
2389 * yield the LUA process, and resume it without checking the
2390 * input arguments.
2391 */
2392__LJMP static int hlua_channel_send(lua_State *L)
2393{
2394 MAY_LJMP(check_args(L, 2, "send"));
2395 lua_pushinteger(L, 0);
2396
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002397 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002398}
2399
2400/* This function forward and amount of butes. The data pass from
2401 * the input side of the buffer to the output side, and can be
2402 * forwarded. This function never fails.
2403 *
2404 * The Lua function takes an amount of bytes to be forwarded in
2405 * imput. It returns the number of bytes forwarded.
2406 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002407__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002408{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002409 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002410 int len;
2411 int l;
2412 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002413 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002414
2415 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2416 len = MAY_LJMP(luaL_checkinteger(L, 2));
2417 l = MAY_LJMP(luaL_checkinteger(L, -1));
2418
2419 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002420 if (max > chn->buf->i)
2421 max = chn->buf->i;
2422 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002423 l += max;
2424
2425 lua_pop(L, 1);
2426 lua_pushinteger(L, l);
2427
2428 /* Check if it miss bytes to forward. */
2429 if (l < len) {
2430 /* The the input channel or the output channel are closed, we
2431 * must return the amount of data forwarded.
2432 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002433 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002434 return 1;
2435
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002436 /* If we are waiting for space data in the response buffer, we
2437 * must set the flag WAKERESWR. This flag required the task
2438 * wake up if any activity is detected on the response buffer.
2439 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002440 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002441 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002442 else
2443 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002444
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002445 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002446 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002447 }
2448
2449 return 1;
2450}
2451
2452/* Just check the input and prepare the stack for the previous
2453 * function "hlua_channel_forward_yield"
2454 */
2455__LJMP static int hlua_channel_forward(lua_State *L)
2456{
2457 MAY_LJMP(check_args(L, 2, "forward"));
2458 MAY_LJMP(hlua_checkchannel(L, 1));
2459 MAY_LJMP(luaL_checkinteger(L, 2));
2460
2461 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002462 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002463}
2464
2465/* Just returns the number of bytes available in the input
2466 * side of the buffer. This function never fails.
2467 */
2468__LJMP static int hlua_channel_get_in_len(lua_State *L)
2469{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002470 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002471
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002472 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002473 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002474 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002475 return 1;
2476}
2477
2478/* Just returns the number of bytes available in the output
2479 * side of the buffer. This function never fails.
2480 */
2481__LJMP static int hlua_channel_get_out_len(lua_State *L)
2482{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002483 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002484
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002485 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002486 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002487 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002488 return 1;
2489}
2490
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002491/*
2492 *
2493 *
2494 * Class Fetches
2495 *
2496 *
2497 */
2498
2499/* Returns a struct hlua_session if the stack entry "ud" is
2500 * a class session, otherwise it throws an error.
2501 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002502__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002503{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002504 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002505}
2506
2507/* This function creates and push in the stack a fetch object according
2508 * with a current TXN.
2509 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002510static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002511{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002512 struct hlua_smp *hs;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002513
2514 /* Check stack size. */
2515 if (!lua_checkstack(L, 3))
2516 return 0;
2517
2518 /* Create the object: obj[0] = userdata.
2519 * Note that the base of the Fetches object is the
2520 * transaction object.
2521 */
2522 lua_newtable(L);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002523 hs = lua_newuserdata(L, sizeof(struct hlua_smp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002524 lua_rawseti(L, -2, 0);
2525
2526 hs->s = txn->s;
2527 hs->p = txn->p;
2528 hs->l7 = txn->l7;
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002529 hs->stringsafe = stringsafe;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002530
2531 /* Pop a class sesison metatable and affect it to the userdata. */
2532 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2533 lua_setmetatable(L, -2);
2534
2535 return 1;
2536}
2537
2538/* This function is an LUA binding. It is called with each sample-fetch.
2539 * It uses closure argument to store the associated sample-fetch. It
2540 * returns only one argument or throws an error. An error is thrown
2541 * only if an error is encountered during the argument parsing. If
2542 * the "sample-fetch" function fails, nil is returned.
2543 */
2544__LJMP static int hlua_run_sample_fetch(lua_State *L)
2545{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002546 struct hlua_smp *s;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002547 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002548 struct arg args[ARGM_NBARGS + 1];
2549 int i;
2550 struct sample smp;
2551
2552 /* Get closure arguments. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002553 f = (struct sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002554
2555 /* Get traditionnal arguments. */
2556 s = MAY_LJMP(hlua_checkfetches(L, 1));
2557
2558 /* Get extra arguments. */
2559 for (i = 0; i < lua_gettop(L) - 1; i++) {
2560 if (i >= ARGM_NBARGS)
2561 break;
2562 hlua_lua2arg(L, i + 2, &args[i]);
2563 }
2564 args[i].type = ARGT_STOP;
2565
2566 /* Check arguments. */
Thierry FOURNIER53dd3cf2015-03-12 18:27:10 +01002567 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, s->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002568
2569 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002570 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002571 lua_pushfstring(L, "error in arguments");
2572 WILL_LJMP(lua_error(L));
2573 }
2574
2575 /* Initialise the sample. */
2576 memset(&smp, 0, sizeof(smp));
2577
2578 /* Run the sample fetch process. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002579 if (!f->process(s->p, s->s, s->l7, 0, args, &smp, f->kw, f->private)) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002580 if (s->stringsafe)
2581 lua_pushstring(L, "");
2582 else
2583 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002584 return 1;
2585 }
2586
2587 /* Convert the returned sample in lua value. */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002588 if (s->stringsafe)
2589 hlua_smp2lua_str(L, &smp);
2590 else
2591 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002592 return 1;
2593}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002594
2595/*
2596 *
2597 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002598 * Class Converters
2599 *
2600 *
2601 */
2602
2603/* Returns a struct hlua_session if the stack entry "ud" is
2604 * a class session, otherwise it throws an error.
2605 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002606__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002607{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002608 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002609}
2610
2611/* This function creates and push in the stack a Converters object
2612 * according with a current TXN.
2613 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002614static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002615{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002616 struct hlua_smp *hs;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002617
2618 /* Check stack size. */
2619 if (!lua_checkstack(L, 3))
2620 return 0;
2621
2622 /* Create the object: obj[0] = userdata.
2623 * Note that the base of the Converters object is the
2624 * same than the TXN object.
2625 */
2626 lua_newtable(L);
2627 hs = lua_newuserdata(L, sizeof(struct hlua_txn));
2628 lua_rawseti(L, -2, 0);
2629
2630 hs->s = txn->s;
2631 hs->p = txn->p;
2632 hs->l7 = txn->l7;
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002633 hs->stringsafe = stringsafe;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002634
2635 /* Pop a class session metatable and affect it to the table. */
2636 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
2637 lua_setmetatable(L, -2);
2638
2639 return 1;
2640}
2641
2642/* This function is an LUA binding. It is called with each converter.
2643 * It uses closure argument to store the associated converter. It
2644 * returns only one argument or throws an error. An error is thrown
2645 * only if an error is encountered during the argument parsing. If
2646 * the converter function function fails, nil is returned.
2647 */
2648__LJMP static int hlua_run_sample_conv(lua_State *L)
2649{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002650 struct hlua_smp *sc;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002651 struct sample_conv *conv;
2652 struct arg args[ARGM_NBARGS + 1];
2653 int i;
2654 struct sample smp;
2655
2656 /* Get closure arguments. */
2657 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
2658
2659 /* Get traditionnal arguments. */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002660 sc = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002661
2662 /* Get extra arguments. */
2663 for (i = 0; i < lua_gettop(L) - 2; i++) {
2664 if (i >= ARGM_NBARGS)
2665 break;
2666 hlua_lua2arg(L, i + 3, &args[i]);
2667 }
2668 args[i].type = ARGT_STOP;
2669
2670 /* Check arguments. */
Thierry FOURNIER53dd3cf2015-03-12 18:27:10 +01002671 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, sc->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002672
2673 /* Run the special args checker. */
2674 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
2675 hlua_pusherror(L, "error in arguments");
2676 WILL_LJMP(lua_error(L));
2677 }
2678
2679 /* Initialise the sample. */
2680 if (!hlua_lua2smp(L, 2, &smp)) {
2681 hlua_pusherror(L, "error in the input argument");
2682 WILL_LJMP(lua_error(L));
2683 }
2684
2685 /* Apply expected cast. */
2686 if (!sample_casts[smp.type][conv->in_type]) {
2687 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
2688 smp_to_type[smp.type], smp_to_type[conv->in_type]);
2689 WILL_LJMP(lua_error(L));
2690 }
2691 if (sample_casts[smp.type][conv->in_type] != c_none &&
2692 !sample_casts[smp.type][conv->in_type](&smp)) {
2693 hlua_pusherror(L, "error during the input argument casting");
2694 WILL_LJMP(lua_error(L));
2695 }
2696
2697 /* Run the sample conversion process. */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002698 if (!conv->process(sc->s, args, &smp, conv->private)) {
2699 if (sc->stringsafe)
2700 lua_pushstring(L, "");
2701 else
2702 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002703 return 1;
2704 }
2705
2706 /* Convert the returned sample in lua value. */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002707 if (sc->stringsafe)
2708 hlua_smp2lua_str(L, &smp);
2709 else
2710 hlua_smp2lua(L, &smp);
2711 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002712}
2713
2714/*
2715 *
2716 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002717 * Class TXN
2718 *
2719 *
2720 */
2721
2722/* Returns a struct hlua_session if the stack entry "ud" is
2723 * a class session, otherwise it throws an error.
2724 */
2725__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
2726{
2727 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
2728}
2729
Willy Tarreau59551662015-03-10 14:23:13 +01002730__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002731{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002732 struct hlua *hlua;
2733
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002734 MAY_LJMP(check_args(L, 2, "set_priv"));
2735
2736 /* It is useles to retrieve the session, but this function
2737 * runs only in a session context.
2738 */
2739 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002740 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002741
2742 /* Remove previous value. */
2743 if (hlua->Mref != -1)
2744 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
2745
2746 /* Get and store new value. */
2747 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
2748 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
2749
2750 return 0;
2751}
2752
Willy Tarreau59551662015-03-10 14:23:13 +01002753__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002754{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002755 struct hlua *hlua;
2756
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002757 MAY_LJMP(check_args(L, 1, "get_priv"));
2758
2759 /* It is useles to retrieve the session, but this function
2760 * runs only in a session context.
2761 */
2762 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002763 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002764
2765 /* Push configuration index in the stack. */
2766 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
2767
2768 return 1;
2769}
2770
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002771/* Create stack entry containing a class TXN. This function
2772 * return 0 if the stack does not contains free slots,
2773 * otherwise it returns 1.
2774 */
2775static int hlua_txn_new(lua_State *L, struct session *s, struct proxy *p, void *l7)
2776{
2777 struct hlua_txn *hs;
2778
2779 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002780 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002781 return 0;
2782
2783 /* NOTE: The allocation never fails. The failure
2784 * throw an error, and the function never returns.
2785 * if the throw is not avalaible, the process is aborted.
2786 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002787 /* Create the object: obj[0] = userdata. */
2788 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002789 hs = lua_newuserdata(L, sizeof(struct hlua_txn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002790 lua_rawseti(L, -2, 0);
2791
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002792 hs->s = s;
2793 hs->p = p;
2794 hs->l7 = l7;
2795
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002796 /* Create the "f" field that contains a list of fetches. */
2797 lua_pushstring(L, "f");
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002798 if (!hlua_fetches_new(L, hs, 0))
2799 return 0;
2800 lua_settable(L, -3);
2801
2802 /* Create the "sf" field that contains a list of stringsafe fetches. */
2803 lua_pushstring(L, "sf");
2804 if (!hlua_fetches_new(L, hs, 1))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002805 return 0;
2806 lua_settable(L, -3);
2807
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002808 /* Create the "c" field that contains a list of converters. */
2809 lua_pushstring(L, "c");
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002810 if (!hlua_converters_new(L, hs, 0))
2811 return 0;
2812 lua_settable(L, -3);
2813
2814 /* Create the "sc" field that contains a list of stringsafe converters. */
2815 lua_pushstring(L, "sc");
2816 if (!hlua_converters_new(L, hs, 1))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002817 return 0;
2818 lua_settable(L, -3);
2819
Thierry FOURNIER397826a2015-03-11 19:39:09 +01002820 /* Create the "req" field that contains the request channel object. */
2821 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01002822 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01002823 return 0;
2824 lua_settable(L, -3);
2825
2826 /* Create the "res" field that contains the response channel object. */
2827 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01002828 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01002829 return 0;
2830 lua_settable(L, -3);
2831
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002832 /* Pop a class sesison metatable and affect it to the userdata. */
2833 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
2834 lua_setmetatable(L, -2);
2835
2836 return 1;
2837}
2838
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002839/* This function is an Lua binding that send pending data
2840 * to the client, and close the stream interface.
2841 */
2842__LJMP static int hlua_txn_close(lua_State *L)
2843{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002844 struct hlua_txn *s;
Willy Tarreau81389672015-03-10 12:03:52 +01002845 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002846
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002847 MAY_LJMP(check_args(L, 1, "close"));
2848 s = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002849
Willy Tarreau81389672015-03-10 12:03:52 +01002850 ic = si_ic(&s->s->si[0]);
2851 oc = si_oc(&s->s->si[0]);
2852
2853 channel_abort(ic);
2854 channel_auto_close(ic);
2855 channel_erase(ic);
2856 channel_auto_read(oc);
2857 channel_auto_close(oc);
2858 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002859
2860 return 0;
2861}
2862
Thierry FOURNIER9a819e72015-02-16 20:22:55 +01002863/* This function is an LUA binding. It creates ans returns
2864 * an array of HTTP headers. This function does not fails.
2865 */
Willy Tarreau59551662015-03-10 14:23:13 +01002866static int hlua_session_get_headers(lua_State *L)
Thierry FOURNIER9a819e72015-02-16 20:22:55 +01002867{
2868 struct hlua_txn *s = MAY_LJMP(hlua_checktxn(L, 1));
2869 struct session *sess = s->s;
2870 const char *cur_ptr, *cur_next, *p;
2871 int old_idx, cur_idx;
2872 struct hdr_idx_elem *cur_hdr;
2873 const char *hn, *hv;
2874 int hnl, hvl;
2875
2876 /* Create the table. */
2877 lua_newtable(L);
2878
2879 /* Build array of headers. */
2880 old_idx = 0;
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002881 cur_next = sess->req.buf->p + hdr_idx_first_pos(&sess->txn.hdr_idx);
Thierry FOURNIER9a819e72015-02-16 20:22:55 +01002882
2883 while (1) {
2884 cur_idx = sess->txn.hdr_idx.v[old_idx].next;
2885 if (!cur_idx)
2886 break;
2887 old_idx = cur_idx;
2888
2889 cur_hdr = &sess->txn.hdr_idx.v[cur_idx];
2890 cur_ptr = cur_next;
2891 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
2892
2893 /* Now we have one full header at cur_ptr of len cur_hdr->len,
2894 * and the next header starts at cur_next. We'll check
2895 * this header in the list as well as against the default
2896 * rule.
2897 */
2898
2899 /* look for ': *'. */
2900 hn = cur_ptr;
2901 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
2902 if (p >= cur_ptr+cur_hdr->len)
2903 continue;
2904 hnl = p - hn;
2905 p++;
2906 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
2907 p++;
2908 if (p >= cur_ptr+cur_hdr->len)
2909 continue;
2910 hv = p;
2911 hvl = cur_ptr+cur_hdr->len-p;
2912
2913 /* Push values in the table. */
2914 lua_pushlstring(L, hn, hnl);
2915 lua_pushlstring(L, hv, hvl);
2916 lua_settable(L, -3);
2917 }
2918
2919 return 1;
2920}
2921
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002922__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002923{
2924 int wakeup_ms = lua_tointeger(L, -1);
2925 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002926 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002927 return 0;
2928}
2929
2930__LJMP static int hlua_sleep(lua_State *L)
2931{
2932 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002933 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002934
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002935 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002936
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002937 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002938 wakeup_ms = tick_add(now_ms, delay);
2939 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002940
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002941 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
2942 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002943}
2944
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002945__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002946{
2947 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002948 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002949
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002950 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002951
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002952 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002953 wakeup_ms = tick_add(now_ms, delay);
2954 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002955
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002956 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
2957 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002958}
2959
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01002960/* This functionis an LUA binding. it permits to give back
2961 * the hand at the HAProxy scheduler. It is used when the
2962 * LUA processing consumes a lot of time.
2963 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002964__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002965{
2966 return 0;
2967}
2968
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01002969__LJMP static int hlua_yield(lua_State *L)
2970{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002971 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
2972 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01002973}
2974
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002975/* This function change the nice of the currently executed
2976 * task. It is used set low or high priority at the current
2977 * task.
2978 */
Willy Tarreau59551662015-03-10 14:23:13 +01002979__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002980{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002981 struct hlua *hlua;
2982 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002983
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002984 MAY_LJMP(check_args(L, 1, "set_nice"));
2985 hlua = hlua_gethlua(L);
2986 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002987
2988 /* If he task is not set, I'm in a start mode. */
2989 if (!hlua || !hlua->task)
2990 return 0;
2991
2992 if (nice < -1024)
2993 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002994 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002995 nice = 1024;
2996
2997 hlua->task->nice = nice;
2998 return 0;
2999}
3000
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003001/* This function is used as a calback of a task. It is called by the
3002 * HAProxy task subsystem when the task is awaked. The LUA runtime can
3003 * return an E_AGAIN signal, the emmiter of this signal must set a
3004 * signal to wake the task.
3005 */
3006static struct task *hlua_process_task(struct task *task)
3007{
3008 struct hlua *hlua = task->context;
3009 enum hlua_exec status;
3010
3011 /* We need to remove the task from the wait queue before executing
3012 * the Lua code because we don't know if it needs to wait for
3013 * another timer or not in the case of E_AGAIN.
3014 */
3015 task_delete(task);
3016
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003017 /* If it is the first call to the task, we must initialize the
3018 * execution timeouts.
3019 */
3020 if (!HLUA_IS_RUNNING(hlua))
3021 hlua->expire = tick_add(now_ms, hlua_timeout_task);
3022
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003023 /* Execute the Lua code. */
3024 status = hlua_ctx_resume(hlua, 1);
3025
3026 switch (status) {
3027 /* finished or yield */
3028 case HLUA_E_OK:
3029 hlua_ctx_destroy(hlua);
3030 task_delete(task);
3031 task_free(task);
3032 break;
3033
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003034 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
3035 if (hlua->wake_time != TICK_ETERNITY)
3036 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003037 break;
3038
3039 /* finished with error. */
3040 case HLUA_E_ERRMSG:
3041 send_log(NULL, LOG_ERR, "Lua task: %s.", lua_tostring(hlua->T, -1));
3042 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3043 Alert("Lua task: %s.\n", lua_tostring(hlua->T, -1));
3044 hlua_ctx_destroy(hlua);
3045 task_delete(task);
3046 task_free(task);
3047 break;
3048
3049 case HLUA_E_ERR:
3050 default:
3051 send_log(NULL, LOG_ERR, "Lua task: unknown error.");
3052 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3053 Alert("Lua task: unknown error.\n");
3054 hlua_ctx_destroy(hlua);
3055 task_delete(task);
3056 task_free(task);
3057 break;
3058 }
3059 return NULL;
3060}
3061
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003062/* This function is an LUA binding that register LUA function to be
3063 * executed after the HAProxy configuration parsing and before the
3064 * HAProxy scheduler starts. This function expect only one LUA
3065 * argument that is a function. This function returns nothing, but
3066 * throws if an error is encountered.
3067 */
3068__LJMP static int hlua_register_init(lua_State *L)
3069{
3070 struct hlua_init_function *init;
3071 int ref;
3072
3073 MAY_LJMP(check_args(L, 1, "register_init"));
3074
3075 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3076
3077 init = malloc(sizeof(*init));
3078 if (!init)
3079 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3080
3081 init->function_ref = ref;
3082 LIST_ADDQ(&hlua_init_functions, &init->l);
3083 return 0;
3084}
3085
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003086/* This functio is an LUA binding. It permits to register a task
3087 * executed in parallel of the main HAroxy activity. The task is
3088 * created and it is set in the HAProxy scheduler. It can be called
3089 * from the "init" section, "post init" or during the runtime.
3090 *
3091 * Lua prototype:
3092 *
3093 * <none> core.register_task(<function>)
3094 */
3095static int hlua_register_task(lua_State *L)
3096{
3097 struct hlua *hlua;
3098 struct task *task;
3099 int ref;
3100
3101 MAY_LJMP(check_args(L, 1, "register_task"));
3102
3103 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3104
3105 hlua = malloc(sizeof(*hlua));
3106 if (!hlua)
3107 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3108
3109 task = task_new();
3110 task->context = hlua;
3111 task->process = hlua_process_task;
3112
3113 if (!hlua_ctx_init(hlua, task))
3114 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3115
3116 /* Restore the function in the stack. */
3117 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
3118 hlua->nargs = 0;
3119
3120 /* Schedule task. */
3121 task_schedule(task, now_ms);
3122
3123 return 0;
3124}
3125
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003126/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
3127 * doesn't allow "yield" functions because the HAProxy engine cannot
3128 * resume converters.
3129 */
3130static int hlua_sample_conv_wrapper(struct session *session, const struct arg *arg_p,
3131 struct sample *smp, void *private)
3132{
3133 struct hlua_function *fcn = (struct hlua_function *)private;
3134
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003135 /* In the execution wrappers linked with a session, the
3136 * Lua context can be not initialized. This behavior
3137 * permits to save performances because a systematic
3138 * Lua initialization cause 5% performances loss.
3139 */
3140 if (!session->hlua.T && !hlua_ctx_init(&session->hlua, session->task)) {
3141 send_log(session->be, LOG_ERR, "Lua converter '%s': can't initialize Lua context.", fcn->name);
3142 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3143 Alert("Lua converter '%s': can't initialize Lua context.\n", fcn->name);
3144 return 0;
3145 }
3146
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003147 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003148 if (!HLUA_IS_RUNNING(&session->hlua)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003149 /* Check stack available size. */
3150 if (!lua_checkstack(session->hlua.T, 1)) {
3151 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
3152 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3153 Alert("Lua converter '%s': full stack.\n", fcn->name);
3154 return 0;
3155 }
3156
3157 /* Restore the function in the stack. */
3158 lua_rawgeti(session->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
3159
3160 /* convert input sample and pust-it in the stack. */
3161 if (!lua_checkstack(session->hlua.T, 1)) {
3162 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
3163 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3164 Alert("Lua converter '%s': full stack.\n", fcn->name);
3165 return 0;
3166 }
3167 hlua_smp2lua(session->hlua.T, smp);
3168 session->hlua.nargs = 2;
3169
3170 /* push keywords in the stack. */
3171 if (arg_p) {
3172 for (; arg_p->type != ARGT_STOP; arg_p++) {
3173 if (!lua_checkstack(session->hlua.T, 1)) {
3174 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
3175 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3176 Alert("Lua converter '%s': full stack.\n", fcn->name);
3177 return 0;
3178 }
3179 hlua_arg2lua(session->hlua.T, arg_p);
3180 session->hlua.nargs++;
3181 }
3182 }
3183
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003184 /* We must initialize the execution timeouts. */
3185 session->hlua.expire = tick_add(now_ms, hlua_timeout_session);
3186
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003187 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003188 HLUA_SET_RUN(&session->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003189 }
3190
3191 /* Execute the function. */
3192 switch (hlua_ctx_resume(&session->hlua, 0)) {
3193 /* finished. */
3194 case HLUA_E_OK:
3195 /* Convert the returned value in sample. */
3196 hlua_lua2smp(session->hlua.T, -1, smp);
3197 lua_pop(session->hlua.T, 1);
3198 return 1;
3199
3200 /* yield. */
3201 case HLUA_E_AGAIN:
3202 send_log(session->be, LOG_ERR, "Lua converter '%s': cannot use yielded functions.", fcn->name);
3203 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3204 Alert("Lua converter '%s': cannot use yielded functions.\n", fcn->name);
3205 return 0;
3206
3207 /* finished with error. */
3208 case HLUA_E_ERRMSG:
3209 /* Display log. */
3210 send_log(session->be, LOG_ERR, "Lua converter '%s': %s.", fcn->name, lua_tostring(session->hlua.T, -1));
3211 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3212 Alert("Lua converter '%s': %s.\n", fcn->name, lua_tostring(session->hlua.T, -1));
3213 lua_pop(session->hlua.T, 1);
3214 return 0;
3215
3216 case HLUA_E_ERR:
3217 /* Display log. */
3218 send_log(session->be, LOG_ERR, "Lua converter '%s' returns an unknown error.", fcn->name);
3219 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3220 Alert("Lua converter '%s' returns an unknown error.\n", fcn->name);
3221
3222 default:
3223 return 0;
3224 }
3225}
3226
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003227/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
3228 * doesn't allow "yield" functions because the HAProxy engine cannot
3229 * resume sample-fetches.
3230 */
3231static int hlua_sample_fetch_wrapper(struct proxy *px, struct session *s, void *l7,
3232 unsigned int opt, const struct arg *arg_p,
3233 struct sample *smp, const char *kw, void *private)
3234{
3235 struct hlua_function *fcn = (struct hlua_function *)private;
3236
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003237 /* In the execution wrappers linked with a session, the
3238 * Lua context can be not initialized. This behavior
3239 * permits to save performances because a systematic
3240 * Lua initialization cause 5% performances loss.
3241 */
3242 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
3243 send_log(s->be, LOG_ERR, "Lua sample-fetch '%s': can't initialize Lua context.", fcn->name);
3244 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3245 Alert("Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
3246 return 0;
3247 }
3248
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003249 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003250 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003251 /* Check stack available size. */
3252 if (!lua_checkstack(s->hlua.T, 2)) {
3253 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3254 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3255 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3256 return 0;
3257 }
3258
3259 /* Restore the function in the stack. */
3260 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
3261
3262 /* push arguments in the stack. */
3263 if (!hlua_txn_new(s->hlua.T, s, px, l7)) {
3264 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3265 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3266 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3267 return 0;
3268 }
3269 s->hlua.nargs = 1;
3270
3271 /* push keywords in the stack. */
3272 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
3273 /* Check stack available size. */
3274 if (!lua_checkstack(s->hlua.T, 1)) {
3275 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3276 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3277 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3278 return 0;
3279 }
3280 if (!lua_checkstack(s->hlua.T, 1)) {
3281 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3282 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3283 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3284 return 0;
3285 }
3286 hlua_arg2lua(s->hlua.T, arg_p);
3287 s->hlua.nargs++;
3288 }
3289
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003290 /* We must initialize the execution timeouts. */
3291 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
3292
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003293 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003294 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003295 }
3296
3297 /* Execute the function. */
3298 switch (hlua_ctx_resume(&s->hlua, 0)) {
3299 /* finished. */
3300 case HLUA_E_OK:
3301 /* Convert the returned value in sample. */
3302 hlua_lua2smp(s->hlua.T, -1, smp);
3303 lua_pop(s->hlua.T, 1);
3304
3305 /* Set the end of execution flag. */
3306 smp->flags &= ~SMP_F_MAY_CHANGE;
3307 return 1;
3308
3309 /* yield. */
3310 case HLUA_E_AGAIN:
3311 send_log(px, LOG_ERR, "Lua sample-fetch '%s': cannot use yielded functions.", fcn->name);
3312 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3313 Alert("Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
3314 return 0;
3315
3316 /* finished with error. */
3317 case HLUA_E_ERRMSG:
3318 /* Display log. */
3319 send_log(px, LOG_ERR, "Lua sample-fetch '%s': %s.", fcn->name, lua_tostring(s->hlua.T, -1));
3320 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3321 Alert("Lua sample-fetch '%s': %s.\n", fcn->name, lua_tostring(s->hlua.T, -1));
3322 lua_pop(s->hlua.T, 1);
3323 return 0;
3324
3325 case HLUA_E_ERR:
3326 /* Display log. */
3327 send_log(px, LOG_ERR, "Lua sample-fetch '%s' returns an unknown error.", fcn->name);
3328 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3329 Alert("Lua sample-fetch '%s': returns an unknown error.\n", fcn->name);
3330
3331 default:
3332 return 0;
3333 }
3334}
3335
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003336/* This function is an LUA binding used for registering
3337 * "sample-conv" functions. It expects a converter name used
3338 * in the haproxy configuration file, and an LUA function.
3339 */
3340__LJMP static int hlua_register_converters(lua_State *L)
3341{
3342 struct sample_conv_kw_list *sck;
3343 const char *name;
3344 int ref;
3345 int len;
3346 struct hlua_function *fcn;
3347
3348 MAY_LJMP(check_args(L, 2, "register_converters"));
3349
3350 /* First argument : converter name. */
3351 name = MAY_LJMP(luaL_checkstring(L, 1));
3352
3353 /* Second argument : lua function. */
3354 ref = MAY_LJMP(hlua_checkfunction(L, 2));
3355
3356 /* Allocate and fill the sample fetch keyword struct. */
3357 sck = malloc(sizeof(struct sample_conv_kw_list) +
3358 sizeof(struct sample_conv) * 2);
3359 if (!sck)
3360 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3361 fcn = malloc(sizeof(*fcn));
3362 if (!fcn)
3363 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3364
3365 /* Fill fcn. */
3366 fcn->name = strdup(name);
3367 if (!fcn->name)
3368 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3369 fcn->function_ref = ref;
3370
3371 /* List head */
3372 sck->list.n = sck->list.p = NULL;
3373
3374 /* converter keyword. */
3375 len = strlen("lua.") + strlen(name) + 1;
3376 sck->kw[0].kw = malloc(len);
3377 if (!sck->kw[0].kw)
3378 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3379
3380 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
3381 sck->kw[0].process = hlua_sample_conv_wrapper;
3382 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
3383 sck->kw[0].val_args = NULL;
3384 sck->kw[0].in_type = SMP_T_STR;
3385 sck->kw[0].out_type = SMP_T_STR;
3386 sck->kw[0].private = fcn;
3387
3388 /* End of array. */
3389 memset(&sck->kw[1], 0, sizeof(struct sample_conv));
3390
3391 /* Register this new converter */
3392 sample_register_convs(sck);
3393
3394 return 0;
3395}
3396
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003397/* This fucntion is an LUA binding used for registering
3398 * "sample-fetch" functions. It expects a converter name used
3399 * in the haproxy configuration file, and an LUA function.
3400 */
3401__LJMP static int hlua_register_fetches(lua_State *L)
3402{
3403 const char *name;
3404 int ref;
3405 int len;
3406 struct sample_fetch_kw_list *sfk;
3407 struct hlua_function *fcn;
3408
3409 MAY_LJMP(check_args(L, 2, "register_fetches"));
3410
3411 /* First argument : sample-fetch name. */
3412 name = MAY_LJMP(luaL_checkstring(L, 1));
3413
3414 /* Second argument : lua function. */
3415 ref = MAY_LJMP(hlua_checkfunction(L, 2));
3416
3417 /* Allocate and fill the sample fetch keyword struct. */
3418 sfk = malloc(sizeof(struct sample_fetch_kw_list) +
3419 sizeof(struct sample_fetch) * 2);
3420 if (!sfk)
3421 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3422 fcn = malloc(sizeof(*fcn));
3423 if (!fcn)
3424 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3425
3426 /* Fill fcn. */
3427 fcn->name = strdup(name);
3428 if (!fcn->name)
3429 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3430 fcn->function_ref = ref;
3431
3432 /* List head */
3433 sfk->list.n = sfk->list.p = NULL;
3434
3435 /* sample-fetch keyword. */
3436 len = strlen("lua.") + strlen(name) + 1;
3437 sfk->kw[0].kw = malloc(len);
3438 if (!sfk->kw[0].kw)
3439 return luaL_error(L, "lua out of memory error.");
3440
3441 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
3442 sfk->kw[0].process = hlua_sample_fetch_wrapper;
3443 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
3444 sfk->kw[0].val_args = NULL;
3445 sfk->kw[0].out_type = SMP_T_STR;
3446 sfk->kw[0].use = SMP_USE_HTTP_ANY;
3447 sfk->kw[0].val = 0;
3448 sfk->kw[0].private = fcn;
3449
3450 /* End of array. */
3451 memset(&sfk->kw[1], 0, sizeof(struct sample_fetch));
3452
3453 /* Register this new fetch. */
3454 sample_register_fetches(sfk);
3455
3456 return 0;
3457}
3458
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003459/* global {tcp|http}-request parser. Return 1 in succes case, else return 0. */
3460static int hlua_parse_rule(const char **args, int *cur_arg, struct proxy *px,
3461 struct hlua_rule **rule_p, char **err)
3462{
3463 struct hlua_rule *rule;
3464
3465 /* Memory for the rule. */
3466 rule = malloc(sizeof(*rule));
3467 if (!rule) {
3468 memprintf(err, "out of memory error");
3469 return 0;
3470 }
3471 *rule_p = rule;
3472
3473 /* The requiered arg is a function name. */
3474 if (!args[*cur_arg]) {
3475 memprintf(err, "expect Lua function name");
3476 return 0;
3477 }
3478
3479 /* Lookup for the symbol, and check if it is a function. */
3480 lua_getglobal(gL.T, args[*cur_arg]);
3481 if (lua_isnil(gL.T, -1)) {
3482 lua_pop(gL.T, 1);
3483 memprintf(err, "Lua function '%s' not found", args[*cur_arg]);
3484 return 0;
3485 }
3486 if (!lua_isfunction(gL.T, -1)) {
3487 lua_pop(gL.T, 1);
3488 memprintf(err, "'%s' is not a function", args[*cur_arg]);
3489 return 0;
3490 }
3491
3492 /* Reference the Lua function and store the reference. */
3493 rule->fcn.function_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
3494 rule->fcn.name = strdup(args[*cur_arg]);
3495 if (!rule->fcn.name) {
3496 memprintf(err, "out of memory error.");
3497 return 0;
3498 }
3499 (*cur_arg)++;
3500
3501 /* TODO: later accept arguments. */
3502 rule->args = NULL;
3503
3504 return 1;
3505}
3506
3507/* This function is a wrapper to execute each LUA function declared
3508 * as an action wrapper during the initialisation period. This function
3509 * return 1 if the processing is finished (with oe without error) and
3510 * return 0 if the function must be called again because the LUA
3511 * returns a yield.
3512 */
3513static int hlua_request_act_wrapper(struct hlua_rule *rule, struct proxy *px,
3514 struct session *s, struct http_txn *http_txn,
3515 unsigned int analyzer)
3516{
3517 char **arg;
3518
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003519 /* In the execution wrappers linked with a session, the
3520 * Lua context can be not initialized. This behavior
3521 * permits to save performances because a systematic
3522 * Lua initialization cause 5% performances loss.
3523 */
3524 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
3525 send_log(px, LOG_ERR, "Lua action '%s': can't initialize Lua context.", rule->fcn.name);
3526 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3527 Alert("Lua action '%s': can't initialize Lua context.\n", rule->fcn.name);
3528 return 0;
3529 }
3530
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003531 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003532 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003533 /* Check stack available size. */
3534 if (!lua_checkstack(s->hlua.T, 1)) {
3535 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
3536 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3537 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
3538 return 0;
3539 }
3540
3541 /* Restore the function in the stack. */
3542 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->fcn.function_ref);
3543
3544 /* Create and and push object session in the stack. */
3545 if (!hlua_txn_new(s->hlua.T, s, px, http_txn)) {
3546 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
3547 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3548 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
3549 return 0;
3550 }
3551 s->hlua.nargs = 1;
3552
3553 /* push keywords in the stack. */
3554 for (arg = rule->args; arg && *arg; arg++) {
3555 if (!lua_checkstack(s->hlua.T, 1)) {
3556 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
3557 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3558 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
3559 return 0;
3560 }
3561 lua_pushstring(s->hlua.T, *arg);
3562 s->hlua.nargs++;
3563 }
3564
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003565 /* We must initialize the execution timeouts. */
3566 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
3567
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003568 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003569 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003570 }
3571
3572 /* Execute the function. */
3573 switch (hlua_ctx_resume(&s->hlua, 1)) {
3574 /* finished. */
3575 case HLUA_E_OK:
3576 return 1;
3577
3578 /* yield. */
3579 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003580 /* Set timeout in the required channel. */
3581 if (s->hlua.wake_time != TICK_ETERNITY) {
3582 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01003583 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003584 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01003585 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003586 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003587 /* Some actions can be wake up when a "write" event
3588 * is detected on a response channel. This is useful
3589 * only for actions targetted on the requests.
3590 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003591 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01003592 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01003593 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01003594 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003595 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003596 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01003597 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003598 return 0;
3599
3600 /* finished with error. */
3601 case HLUA_E_ERRMSG:
3602 /* Display log. */
3603 send_log(px, LOG_ERR, "Lua function '%s': %s.", rule->fcn.name, lua_tostring(s->hlua.T, -1));
3604 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3605 Alert("Lua function '%s': %s.\n", rule->fcn.name, lua_tostring(s->hlua.T, -1));
3606 lua_pop(s->hlua.T, 1);
3607 return 1;
3608
3609 case HLUA_E_ERR:
3610 /* Display log. */
3611 send_log(px, LOG_ERR, "Lua function '%s' return an unknown error.", rule->fcn.name);
3612 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3613 Alert("Lua function '%s' return an unknown error.\n", rule->fcn.name);
3614
3615 default:
3616 return 1;
3617 }
3618}
3619
3620/* Lua execution wrapper for "tcp-request". This function uses
3621 * "hlua_request_act_wrapper" for executing the LUA code.
3622 */
3623int hlua_tcp_req_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
3624 struct session *s)
3625{
3626 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
3627 px, s, NULL, AN_REQ_INSPECT_FE);
3628}
3629
3630/* Lua execution wrapper for "tcp-response". This function uses
3631 * "hlua_request_act_wrapper" for executing the LUA code.
3632 */
3633int hlua_tcp_res_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
3634 struct session *s)
3635{
3636 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
3637 px, s, NULL, AN_RES_INSPECT);
3638}
3639
3640/* Lua execution wrapper for http-request.
3641 * This function uses "hlua_request_act_wrapper" for executing
3642 * the LUA code.
3643 */
3644int hlua_http_req_act_wrapper(struct http_req_rule *rule, struct proxy *px,
3645 struct session *s, struct http_txn *http_txn)
3646{
3647 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
3648 s, http_txn, AN_REQ_HTTP_PROCESS_FE);
3649}
3650
3651/* Lua execution wrapper for http-response.
3652 * This function uses "hlua_request_act_wrapper" for executing
3653 * the LUA code.
3654 */
3655int hlua_http_res_act_wrapper(struct http_res_rule *rule, struct proxy *px,
3656 struct session *s, struct http_txn *http_txn)
3657{
3658 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
3659 s, http_txn, AN_RES_HTTP_PROCESS_BE);
3660}
3661
3662/* tcp-request <*> configuration wrapper. */
3663static int tcp_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3664 struct tcp_rule *rule, char **err)
3665{
3666 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003667 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003668 rule->action = TCP_ACT_CUSTOM;
3669 rule->action_ptr = hlua_tcp_req_act_wrapper;
3670 return 1;
3671}
3672
3673/* tcp-response <*> configuration wrapper. */
3674static int tcp_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3675 struct tcp_rule *rule, char **err)
3676{
3677 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003678 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003679 rule->action = TCP_ACT_CUSTOM;
3680 rule->action_ptr = hlua_tcp_res_act_wrapper;
3681 return 1;
3682}
3683
3684/* http-request <*> configuration wrapper. */
3685static int http_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3686 struct http_req_rule *rule, char **err)
3687{
3688 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
3689 return -1;
3690 rule->action = HTTP_REQ_ACT_CUSTOM_CONT;
3691 rule->action_ptr = hlua_http_req_act_wrapper;
3692 return 1;
3693}
3694
3695/* http-response <*> configuration wrapper. */
3696static int http_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3697 struct http_res_rule *rule, char **err)
3698{
3699 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
3700 return -1;
3701 rule->action = HTTP_RES_ACT_CUSTOM_CONT;
3702 rule->action_ptr = hlua_http_res_act_wrapper;
3703 return 1;
3704}
3705
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003706static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
3707 struct proxy *defpx, const char *file, int line,
3708 char **err, unsigned int *timeout)
3709{
3710 const char *error;
3711
3712 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
3713 if (error && *error != '\0') {
3714 memprintf(err, "%s: invalid timeout", args[0]);
3715 return -1;
3716 }
3717 return 0;
3718}
3719
3720static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
3721 struct proxy *defpx, const char *file, int line,
3722 char **err)
3723{
3724 return hlua_read_timeout(args, section_type, curpx, defpx,
3725 file, line, err, &hlua_timeout_session);
3726}
3727
3728static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
3729 struct proxy *defpx, const char *file, int line,
3730 char **err)
3731{
3732 return hlua_read_timeout(args, section_type, curpx, defpx,
3733 file, line, err, &hlua_timeout_task);
3734}
3735
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01003736static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
3737 struct proxy *defpx, const char *file, int line,
3738 char **err)
3739{
3740 char *error;
3741
3742 hlua_nb_instruction = strtoll(args[1], &error, 10);
3743 if (*error != '\0') {
3744 memprintf(err, "%s: invalid number", args[0]);
3745 return -1;
3746 }
3747 return 0;
3748}
3749
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01003750/* This function is called by the main configuration key "lua-load". It loads and
3751 * execute an lua file during the parsing of the HAProxy configuration file. It is
3752 * the main lua entry point.
3753 *
3754 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
3755 * occured, otherwise it returns 0.
3756 *
3757 * In some error case, LUA set an error message in top of the stack. This function
3758 * returns this error message in the HAProxy logs and pop it from the stack.
3759 */
3760static int hlua_load(char **args, int section_type, struct proxy *curpx,
3761 struct proxy *defpx, const char *file, int line,
3762 char **err)
3763{
3764 int error;
3765
3766 /* Just load and compile the file. */
3767 error = luaL_loadfile(gL.T, args[1]);
3768 if (error) {
3769 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
3770 lua_pop(gL.T, 1);
3771 return -1;
3772 }
3773
3774 /* If no syntax error where detected, execute the code. */
3775 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
3776 switch (error) {
3777 case LUA_OK:
3778 break;
3779 case LUA_ERRRUN:
3780 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
3781 lua_pop(gL.T, 1);
3782 return -1;
3783 case LUA_ERRMEM:
3784 memprintf(err, "lua out of memory error\n");
3785 return -1;
3786 case LUA_ERRERR:
3787 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
3788 lua_pop(gL.T, 1);
3789 return -1;
3790 case LUA_ERRGCMM:
3791 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
3792 lua_pop(gL.T, 1);
3793 return -1;
3794 default:
3795 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
3796 lua_pop(gL.T, 1);
3797 return -1;
3798 }
3799
3800 return 0;
3801}
3802
3803/* configuration keywords declaration */
3804static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003805 { CFG_GLOBAL, "lua-load", hlua_load },
3806 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
3807 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01003808 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01003809 { 0, NULL, NULL },
3810}};
3811
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003812static struct http_req_action_kw_list http_req_kws = {"lua", { }, {
3813 { "lua", http_req_action_register_lua },
3814 { NULL, NULL }
3815}};
3816
3817static struct http_res_action_kw_list http_res_kws = {"lua", { }, {
3818 { "lua", http_res_action_register_lua },
3819 { NULL, NULL }
3820}};
3821
3822static struct tcp_action_kw_list tcp_req_cont_kws = {"lua", { }, {
3823 { "lua", tcp_req_action_register_lua },
3824 { NULL, NULL }
3825}};
3826
3827static struct tcp_action_kw_list tcp_res_cont_kws = {"lua", { }, {
3828 { "lua", tcp_res_action_register_lua },
3829 { NULL, NULL }
3830}};
3831
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003832int hlua_post_init()
3833{
3834 struct hlua_init_function *init;
3835 const char *msg;
3836 enum hlua_exec ret;
3837
3838 list_for_each_entry(init, &hlua_init_functions, l) {
3839 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
3840 ret = hlua_ctx_resume(&gL, 0);
3841 switch (ret) {
3842 case HLUA_E_OK:
3843 lua_pop(gL.T, -1);
3844 return 1;
3845 case HLUA_E_AGAIN:
3846 Alert("lua init: yield not allowed.\n");
3847 return 0;
3848 case HLUA_E_ERRMSG:
3849 msg = lua_tostring(gL.T, -1);
3850 Alert("lua init: %s.\n", msg);
3851 return 0;
3852 case HLUA_E_ERR:
3853 default:
3854 Alert("lua init: unknown runtime error.\n");
3855 return 0;
3856 }
3857 }
3858 return 1;
3859}
3860
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01003861void hlua_init(void)
3862{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003863 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01003864 int idx;
3865 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003866 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01003867 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003868#ifdef USE_OPENSSL
3869 char *args[4];
3870 struct srv_kw *kw;
3871 int tmp_error;
3872 char *error;
3873#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003874
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01003875 /* Initialise com signals pool session. */
3876 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
3877
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003878 /* Initialise sleep pool. */
3879 pool2_hlua_sleep = create_pool("hlua_sleep", sizeof(struct hlua_sleep), MEM_F_SHARED);
3880
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01003881 /* Register configuration keywords. */
3882 cfg_register_keywords(&cfg_kws);
3883
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003884 /* Register custom HTTP rules. */
3885 http_req_keywords_register(&http_req_kws);
3886 http_res_keywords_register(&http_res_kws);
3887 tcp_req_cont_keywords_register(&tcp_req_cont_kws);
3888 tcp_res_cont_keywords_register(&tcp_res_cont_kws);
3889
Thierry FOURNIER380d0932015-01-23 14:27:52 +01003890 /* Init main lua stack. */
3891 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003892 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01003893 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01003894 gL.T = luaL_newstate();
3895 hlua_sethlua(&gL);
3896 gL.Tref = LUA_REFNIL;
3897 gL.task = NULL;
3898
3899 /* Initialise lua. */
3900 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003901
3902 /*
3903 *
3904 * Create "core" object.
3905 *
3906 */
3907
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01003908 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003909 lua_newtable(gL.T);
3910
3911 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003912 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003913 hlua_class_const_int(gL.T, log_levels[i], i);
3914
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003915 /* Register special functions. */
3916 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003917 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003918 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003919 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003920 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01003921 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003922 hlua_class_function(gL.T, "sleep", hlua_sleep);
3923 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01003924 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
3925 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
3926 hlua_class_function(gL.T, "set_map", hlua_set_map);
3927 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003928 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003929
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003930 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003931
3932 /*
3933 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003934 * Register class Channel
3935 *
3936 */
3937
3938 /* Create and fill the metatable. */
3939 lua_newtable(gL.T);
3940
3941 /* Create and fille the __index entry. */
3942 lua_pushstring(gL.T, "__index");
3943 lua_newtable(gL.T);
3944
3945 /* Register . */
3946 hlua_class_function(gL.T, "get", hlua_channel_get);
3947 hlua_class_function(gL.T, "dup", hlua_channel_dup);
3948 hlua_class_function(gL.T, "getline", hlua_channel_getline);
3949 hlua_class_function(gL.T, "set", hlua_channel_set);
3950 hlua_class_function(gL.T, "append", hlua_channel_append);
3951 hlua_class_function(gL.T, "send", hlua_channel_send);
3952 hlua_class_function(gL.T, "forward", hlua_channel_forward);
3953 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
3954 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
3955
3956 lua_settable(gL.T, -3);
3957
3958 /* Register previous table in the registry with reference and named entry. */
3959 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
3960 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
3961 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
3962
3963 /*
3964 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003965 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003966 *
3967 */
3968
3969 /* Create and fill the metatable. */
3970 lua_newtable(gL.T);
3971
3972 /* Create and fille the __index entry. */
3973 lua_pushstring(gL.T, "__index");
3974 lua_newtable(gL.T);
3975
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01003976 /* Browse existing fetches and create the associated
3977 * object method.
3978 */
3979 sf = NULL;
3980 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
3981
3982 /* Dont register the keywork if the arguments check function are
3983 * not safe during the runtime.
3984 */
3985 if ((sf->val_args != NULL) &&
3986 (sf->val_args != val_payload_lv) &&
3987 (sf->val_args != val_hdr))
3988 continue;
3989
3990 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
3991 * by an underscore.
3992 */
3993 strncpy(trash.str, sf->kw, trash.size);
3994 trash.str[trash.size - 1] = '\0';
3995 for (p = trash.str; *p; p++)
3996 if (*p == '.' || *p == '-' || *p == '+')
3997 *p = '_';
3998
3999 /* Register the function. */
4000 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01004001 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004002 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
4003 lua_settable(gL.T, -3);
4004 }
4005
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004006 lua_settable(gL.T, -3);
4007
4008 /* Register previous table in the registry with reference and named entry. */
4009 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4010 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
4011 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4012
4013 /*
4014 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004015 * Register class Converters
4016 *
4017 */
4018
4019 /* Create and fill the metatable. */
4020 lua_newtable(gL.T);
4021
4022 /* Create and fill the __index entry. */
4023 lua_pushstring(gL.T, "__index");
4024 lua_newtable(gL.T);
4025
4026 /* Browse existing converters and create the associated
4027 * object method.
4028 */
4029 sc = NULL;
4030 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
4031 /* Dont register the keywork if the arguments check function are
4032 * not safe during the runtime.
4033 */
4034 if (sc->val_args != NULL)
4035 continue;
4036
4037 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4038 * by an underscore.
4039 */
4040 strncpy(trash.str, sc->kw, trash.size);
4041 trash.str[trash.size - 1] = '\0';
4042 for (p = trash.str; *p; p++)
4043 if (*p == '.' || *p == '-' || *p == '+')
4044 *p = '_';
4045
4046 /* Register the function. */
4047 lua_pushstring(gL.T, trash.str);
4048 lua_pushlightuserdata(gL.T, sc);
4049 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
4050 lua_settable(gL.T, -3);
4051 }
4052
4053 lua_settable(gL.T, -3);
4054
4055 /* Register previous table in the registry with reference and named entry. */
4056 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4057 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
4058 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4059
4060 /*
4061 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004062 * Register class TXN
4063 *
4064 */
4065
4066 /* Create and fill the metatable. */
4067 lua_newtable(gL.T);
4068
4069 /* Create and fille the __index entry. */
4070 lua_pushstring(gL.T, "__index");
4071 lua_newtable(gL.T);
4072
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004073 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01004074 hlua_class_function(gL.T, "get_headers", hlua_session_get_headers);
4075 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
4076 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004077 hlua_class_function(gL.T, "close", hlua_txn_close);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004078
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004079 lua_settable(gL.T, -3);
4080
4081 /* Register previous table in the registry with reference and named entry. */
4082 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4083 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
4084 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004085
4086 /*
4087 *
4088 * Register class Socket
4089 *
4090 */
4091
4092 /* Create and fill the metatable. */
4093 lua_newtable(gL.T);
4094
4095 /* Create and fille the __index entry. */
4096 lua_pushstring(gL.T, "__index");
4097 lua_newtable(gL.T);
4098
Baptiste Assmann84bb4932015-03-02 21:40:06 +01004099#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004100 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01004101#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004102 hlua_class_function(gL.T, "connect", hlua_socket_connect);
4103 hlua_class_function(gL.T, "send", hlua_socket_send);
4104 hlua_class_function(gL.T, "receive", hlua_socket_receive);
4105 hlua_class_function(gL.T, "close", hlua_socket_close);
4106 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
4107 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
4108 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
4109 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
4110
4111 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
4112
4113 /* Register the garbage collector entry. */
4114 lua_pushstring(gL.T, "__gc");
4115 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
4116 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
4117
4118 /* Register previous table in the registry with reference and named entry. */
4119 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4120 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4121 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
4122 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
4123
4124 /* Proxy and server configuration initialisation. */
4125 memset(&socket_proxy, 0, sizeof(socket_proxy));
4126 init_new_proxy(&socket_proxy);
4127 socket_proxy.parent = NULL;
4128 socket_proxy.last_change = now.tv_sec;
4129 socket_proxy.id = "LUA-SOCKET";
4130 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
4131 socket_proxy.maxconn = 0;
4132 socket_proxy.accept = NULL;
4133 socket_proxy.options2 |= PR_O2_INDEPSTR;
4134 socket_proxy.srv = NULL;
4135 socket_proxy.conn_retries = 0;
4136 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
4137
4138 /* Init TCP server: unchanged parameters */
4139 memset(&socket_tcp, 0, sizeof(socket_tcp));
4140 socket_tcp.next = NULL;
4141 socket_tcp.proxy = &socket_proxy;
4142 socket_tcp.obj_type = OBJ_TYPE_SERVER;
4143 LIST_INIT(&socket_tcp.actconns);
4144 LIST_INIT(&socket_tcp.pendconns);
4145 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
4146 socket_tcp.last_change = 0;
4147 socket_tcp.id = "LUA-TCP-CONN";
4148 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
4149 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
4150 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
4151
4152 /* XXX: Copy default parameter from default server,
4153 * but the default server is not initialized.
4154 */
4155 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
4156 socket_tcp.minconn = socket_proxy.defsrv.minconn;
4157 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
4158 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
4159 socket_tcp.onerror = socket_proxy.defsrv.onerror;
4160 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
4161 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
4162 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
4163 socket_tcp.uweight = socket_proxy.defsrv.iweight;
4164 socket_tcp.iweight = socket_proxy.defsrv.iweight;
4165
4166 socket_tcp.check.status = HCHK_STATUS_INI;
4167 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
4168 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
4169 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
4170 socket_tcp.check.server = &socket_tcp;
4171
4172 socket_tcp.agent.status = HCHK_STATUS_INI;
4173 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
4174 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
4175 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
4176 socket_tcp.agent.server = &socket_tcp;
4177
4178 socket_tcp.xprt = &raw_sock;
4179
4180#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004181 /* Init TCP server: unchanged parameters */
4182 memset(&socket_ssl, 0, sizeof(socket_ssl));
4183 socket_ssl.next = NULL;
4184 socket_ssl.proxy = &socket_proxy;
4185 socket_ssl.obj_type = OBJ_TYPE_SERVER;
4186 LIST_INIT(&socket_ssl.actconns);
4187 LIST_INIT(&socket_ssl.pendconns);
4188 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
4189 socket_ssl.last_change = 0;
4190 socket_ssl.id = "LUA-SSL-CONN";
4191 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
4192 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
4193 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
4194
4195 /* XXX: Copy default parameter from default server,
4196 * but the default server is not initialized.
4197 */
4198 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
4199 socket_ssl.minconn = socket_proxy.defsrv.minconn;
4200 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
4201 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
4202 socket_ssl.onerror = socket_proxy.defsrv.onerror;
4203 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
4204 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
4205 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
4206 socket_ssl.uweight = socket_proxy.defsrv.iweight;
4207 socket_ssl.iweight = socket_proxy.defsrv.iweight;
4208
4209 socket_ssl.check.status = HCHK_STATUS_INI;
4210 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
4211 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
4212 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
4213 socket_ssl.check.server = &socket_ssl;
4214
4215 socket_ssl.agent.status = HCHK_STATUS_INI;
4216 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
4217 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
4218 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
4219 socket_ssl.agent.server = &socket_ssl;
4220
4221 socket_ssl.xprt = &raw_sock;
4222
4223 args[0] = "ssl";
4224 args[1] = "verify";
4225 args[2] = "none";
4226 args[3] = NULL;
4227
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004228 for (idx = 0; idx < 3; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004229 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
4230 /*
4231 *
4232 * If the keyword is not known, we can search in the registered
4233 * server keywords. This is usefull to configure special SSL
4234 * features like client certificates and ssl_verify.
4235 *
4236 */
4237 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
4238 if (tmp_error != 0) {
4239 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
4240 abort(); /* This must be never arrives because the command line
4241 not editable by the user. */
4242 }
4243 idx += kw->skip;
4244 }
4245 }
4246
4247 /* Initialize SSL server. */
4248 if (socket_ssl.xprt == &ssl_sock) {
4249 socket_ssl.use_ssl = 1;
4250 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
4251 }
4252#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01004253}