blob: 7e416f20c1dd90fc947d0962e9fbff9401c52ad7 [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);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100119__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
120 unsigned int mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100121static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100122static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100123static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
124
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100125/* Used to check an Lua function type in the stack. It creates and
126 * returns a reference of the function. This function throws an
127 * error if the rgument is not a "function".
128 */
129__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
130{
131 if (!lua_isfunction(L, argno)) {
132 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
133 WILL_LJMP(luaL_argerror(L, argno, msg));
134 }
135 lua_pushvalue(L, argno);
136 return luaL_ref(L, LUA_REGISTRYINDEX);
137}
138
139/* The three following functions are useful for adding entries
140 * in a table. These functions takes a string and respectively an
141 * integer, a string or a function and add it to the table in the
142 * top of the stack.
143 *
144 * These functions throws an error if no more stack size is
145 * available.
146 */
147__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100148 int value)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100149{
150 if (!lua_checkstack(L, 2))
151 WILL_LJMP(luaL_error(L, "full stack"));
152 lua_pushstring(L, name);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100153 lua_pushinteger(L, value);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100154 lua_settable(L, -3);
155}
156__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
157 const char *value)
158{
159 if (!lua_checkstack(L, 2))
160 WILL_LJMP(luaL_error(L, "full stack"));
161 lua_pushstring(L, name);
162 lua_pushstring(L, value);
163 lua_settable(L, -3);
164}
165__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
166 int (*function)(lua_State *L))
167{
168 if (!lua_checkstack(L, 2))
169 WILL_LJMP(luaL_error(L, "full stack"));
170 lua_pushstring(L, name);
171 lua_pushcclosure(L, function, 0);
172 lua_settable(L, -3);
173}
174
175/* This function check the number of arguments available in the
176 * stack. If the number of arguments available is not the same
177 * then <nb> an error is throwed.
178 */
179__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
180{
181 if (lua_gettop(L) == nb)
182 return;
183 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
184}
185
186/* Return true if the data in stack[<ud>] is an object of
187 * type <class_ref>.
188 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100189static int hlua_metaistype(lua_State *L, int ud, int class_ref)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100190{
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100191 if (!lua_getmetatable(L, ud))
192 return 0;
193
194 lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
195 if (!lua_rawequal(L, -1, -2)) {
196 lua_pop(L, 2);
197 return 0;
198 }
199
200 lua_pop(L, 2);
201 return 1;
202}
203
204/* Return an object of the expected type, or throws an error. */
205__LJMP static void *hlua_checkudata(lua_State *L, int ud, int class_ref)
206{
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100207 void *p;
208
209 /* Check if the stack entry is an array. */
210 if (!lua_istable(L, ud))
211 WILL_LJMP(luaL_argerror(L, ud, NULL));
212 /* Check if the metadata have the expected type. */
213 if (!hlua_metaistype(L, ud, class_ref))
214 WILL_LJMP(luaL_argerror(L, ud, NULL));
215 /* Push on the stack at the entry [0] of the table. */
216 lua_rawgeti(L, ud, 0);
217 /* Check if this entry is userdata. */
218 p = lua_touserdata(L, -1);
219 if (!p)
220 WILL_LJMP(luaL_argerror(L, ud, NULL));
221 /* Remove the entry returned by lua_rawgeti(). */
222 lua_pop(L, 1);
223 /* Return the associated struct. */
224 return p;
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100225}
226
227/* This fucntion push an error string prefixed by the file name
228 * and the line number where the error is encountered.
229 */
230static int hlua_pusherror(lua_State *L, const char *fmt, ...)
231{
232 va_list argp;
233 va_start(argp, fmt);
234 luaL_where(L, 1);
235 lua_pushvfstring(L, fmt, argp);
236 va_end(argp);
237 lua_concat(L, 2);
238 return 1;
239}
240
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100241/* This function register a new signal. "lua" is the current lua
242 * execution context. It contains a pointer to the associated task.
243 * "link" is a list head attached to an other task that must be wake
244 * the lua task if an event occurs. This is useful with external
245 * events like TCP I/O or sleep functions. This funcion allocate
246 * memory for the signal.
247 */
248static int hlua_com_new(struct hlua *lua, struct list *link)
249{
250 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
251 if (!com)
252 return 0;
253 LIST_ADDQ(&lua->com, &com->purge_me);
254 LIST_ADDQ(link, &com->wake_me);
255 com->task = lua->task;
256 return 1;
257}
258
259/* This function purge all the pending signals when the LUA execution
260 * is finished. This prevent than a coprocess try to wake a deleted
261 * task. This function remove the memory associated to the signal.
262 */
263static void hlua_com_purge(struct hlua *lua)
264{
265 struct hlua_com *com, *back;
266
267 /* Delete all pending communication signals. */
268 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
269 LIST_DEL(&com->purge_me);
270 LIST_DEL(&com->wake_me);
271 pool_free2(pool2_hlua_com, com);
272 }
273}
274
275/* This function sends signals. It wakes all the tasks attached
276 * to a list head, and remove the signal, and free the used
277 * memory.
278 */
279static void hlua_com_wake(struct list *wake)
280{
281 struct hlua_com *com, *back;
282
283 /* Wake task and delete all pending communication signals. */
284 list_for_each_entry_safe(com, back, wake, wake_me) {
285 LIST_DEL(&com->purge_me);
286 LIST_DEL(&com->wake_me);
287 task_wakeup(com->task, TASK_WOKEN_MSG);
288 pool_free2(pool2_hlua_com, com);
289 }
290}
291
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100292/* This functions is used with sample fetch and converters. It
293 * converts the HAProxy configuration argument in a lua stack
294 * values.
295 *
296 * It takes an array of "arg", and each entry of the array is
297 * converted and pushed in the LUA stack.
298 */
299static int hlua_arg2lua(lua_State *L, const struct arg *arg)
300{
301 switch (arg->type) {
302 case ARGT_SINT:
303 lua_pushinteger(L, arg->data.sint);
304 break;
305
306 case ARGT_UINT:
307 case ARGT_TIME:
308 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100309 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100310 break;
311
312 case ARGT_STR:
313 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
314 break;
315
316 case ARGT_IPV4:
317 case ARGT_IPV6:
318 case ARGT_MSK4:
319 case ARGT_MSK6:
320 case ARGT_FE:
321 case ARGT_BE:
322 case ARGT_TAB:
323 case ARGT_SRV:
324 case ARGT_USR:
325 case ARGT_MAP:
326 default:
327 lua_pushnil(L);
328 break;
329 }
330 return 1;
331}
332
333/* This function take one entrie in an LUA stack at the index "ud",
334 * and try to convert it in an HAProxy argument entry. This is useful
335 * with sample fetch wrappers. The input arguments are gived to the
336 * lua wrapper and converted as arg list by thi function.
337 */
338static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
339{
340 switch (lua_type(L, ud)) {
341
342 case LUA_TNUMBER:
343 case LUA_TBOOLEAN:
344 arg->type = ARGT_SINT;
345 arg->data.sint = lua_tointeger(L, ud);
346 break;
347
348 case LUA_TSTRING:
349 arg->type = ARGT_STR;
350 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
351 break;
352
353 case LUA_TUSERDATA:
354 case LUA_TNIL:
355 case LUA_TTABLE:
356 case LUA_TFUNCTION:
357 case LUA_TTHREAD:
358 case LUA_TLIGHTUSERDATA:
359 arg->type = ARGT_SINT;
360 arg->data.uint = 0;
361 break;
362 }
363 return 1;
364}
365
366/* the following functions are used to convert a struct sample
367 * in Lua type. This useful to convert the return of the
368 * fetchs or converters.
369 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100370static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100371{
372 switch (smp->type) {
373 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100374 case SMP_T_BOOL:
375 case SMP_T_UINT:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100376 lua_pushinteger(L, smp->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100377 break;
378
379 case SMP_T_BIN:
380 case SMP_T_STR:
381 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
382 break;
383
384 case SMP_T_METH:
385 switch (smp->data.meth.meth) {
386 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
387 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
388 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
389 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
390 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
391 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
392 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
393 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
394 case HTTP_METH_OTHER:
395 lua_pushlstring(L, smp->data.meth.str.str, smp->data.meth.str.len);
396 break;
397 default:
398 lua_pushnil(L);
399 break;
400 }
401 break;
402
403 case SMP_T_IPV4:
404 case SMP_T_IPV6:
405 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100406 if (sample_casts[smp->type][SMP_T_STR] &&
407 sample_casts[smp->type][SMP_T_STR](smp))
408 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
409 else
410 lua_pushnil(L);
411 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100412 default:
413 lua_pushnil(L);
414 break;
415 }
416 return 1;
417}
418
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100419/* the following functions are used to convert a struct sample
420 * in Lua strings. This is useful to convert the return of the
421 * fetchs or converters.
422 */
423static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
424{
425 switch (smp->type) {
426
427 case SMP_T_BIN:
428 case SMP_T_STR:
429 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
430 break;
431
432 case SMP_T_METH:
433 switch (smp->data.meth.meth) {
434 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
435 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
436 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
437 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
438 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
439 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
440 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
441 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
442 case HTTP_METH_OTHER:
443 lua_pushlstring(L, smp->data.meth.str.str, smp->data.meth.str.len);
444 break;
445 default:
446 lua_pushstring(L, "");
447 break;
448 }
449 break;
450
451 case SMP_T_SINT:
452 case SMP_T_BOOL:
453 case SMP_T_UINT:
454 case SMP_T_IPV4:
455 case SMP_T_IPV6:
456 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
457 if (sample_casts[smp->type][SMP_T_STR] &&
458 sample_casts[smp->type][SMP_T_STR](smp))
459 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
460 else
461 lua_pushstring(L, "");
462 break;
463 default:
464 lua_pushstring(L, "");
465 break;
466 }
467 return 1;
468}
469
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100470/* the following functions are used to convert an Lua type in a
471 * struct sample. This is useful to provide data from a converter
472 * to the LUA code.
473 */
474static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
475{
476 switch (lua_type(L, ud)) {
477
478 case LUA_TNUMBER:
479 smp->type = SMP_T_SINT;
480 smp->data.sint = lua_tointeger(L, ud);
481 break;
482
483
484 case LUA_TBOOLEAN:
485 smp->type = SMP_T_BOOL;
486 smp->data.uint = lua_toboolean(L, ud);
487 break;
488
489 case LUA_TSTRING:
490 smp->type = SMP_T_STR;
491 smp->flags |= SMP_F_CONST;
492 smp->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.str.len);
493 break;
494
495 case LUA_TUSERDATA:
496 case LUA_TNIL:
497 case LUA_TTABLE:
498 case LUA_TFUNCTION:
499 case LUA_TTHREAD:
500 case LUA_TLIGHTUSERDATA:
501 smp->type = SMP_T_BOOL;
502 smp->data.uint = 0;
503 break;
504 }
505 return 1;
506}
507
508/* This function check the "argp" builded by another conversion function
509 * is in accord with the expected argp defined by the "mask". The fucntion
510 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100511 *
512 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
513 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100514 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100515__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
516 unsigned int mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100517{
518 int min_arg;
519 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100520 struct proxy *px;
521 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100522
523 idx = 0;
524 min_arg = ARGM(mask);
525 mask >>= ARGM_BITS;
526
527 while (1) {
528
529 /* Check oversize. */
530 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100531 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100532 }
533
534 /* Check for mandatory arguments. */
535 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100536 if (idx < min_arg) {
537
538 /* If miss other argument than the first one, we return an error. */
539 if (idx > 0)
540 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
541
542 /* If first argument have a certain type, some default values
543 * may be used. See the function smp_resolve_args().
544 */
545 switch (mask & ARGT_MASK) {
546
547 case ARGT_FE:
548 if (!(p->cap & PR_CAP_FE))
549 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
550 argp[idx].data.prx = p;
551 argp[idx].type = ARGT_FE;
552 argp[idx+1].type = ARGT_STOP;
553 break;
554
555 case ARGT_BE:
556 if (!(p->cap & PR_CAP_BE))
557 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
558 argp[idx].data.prx = p;
559 argp[idx].type = ARGT_BE;
560 argp[idx+1].type = ARGT_STOP;
561 break;
562
563 case ARGT_TAB:
564 argp[idx].data.prx = p;
565 argp[idx].type = ARGT_TAB;
566 argp[idx+1].type = ARGT_STOP;
567 break;
568
569 default:
570 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
571 break;
572 }
573 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100574 return 0;
575 }
576
577 /* Check for exceed the number of requiered argument. */
578 if ((mask & ARGT_MASK) == ARGT_STOP &&
579 argp[idx].type != ARGT_STOP) {
580 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
581 }
582
583 if ((mask & ARGT_MASK) == ARGT_STOP &&
584 argp[idx].type == ARGT_STOP) {
585 return 0;
586 }
587
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100588 /* Convert some argument types. */
589 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100590 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100591 if (argp[idx].type != ARGT_SINT)
592 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
593 argp[idx].type = ARGT_SINT;
594 break;
595
596 case ARGT_UINT:
597 if (argp[idx].type != ARGT_SINT)
598 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
599 argp[idx].type = ARGT_SINT;
600 break;
601
602 case ARGT_TIME:
603 if (argp[idx].type != ARGT_SINT)
604 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
605 argp[idx].type = ARGT_SINT;
606 break;
607
608 case ARGT_SIZE:
609 if (argp[idx].type != ARGT_SINT)
610 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
611 argp[idx].type = ARGT_SINT;
612 break;
613
614 case ARGT_FE:
615 if (argp[idx].type != ARGT_STR)
616 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
617 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
618 trash.str[argp[idx].data.str.len] = 0;
619 argp[idx].data.prx = findproxy(trash.str, PR_CAP_FE);
620 if (!argp[idx].data.prx)
621 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
622 argp[idx].type = ARGT_FE;
623 break;
624
625 case ARGT_BE:
626 if (argp[idx].type != ARGT_STR)
627 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
628 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
629 trash.str[argp[idx].data.str.len] = 0;
630 argp[idx].data.prx = findproxy(trash.str, PR_CAP_BE);
631 if (!argp[idx].data.prx)
632 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
633 argp[idx].type = ARGT_BE;
634 break;
635
636 case ARGT_TAB:
637 if (argp[idx].type != ARGT_STR)
638 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
639 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
640 trash.str[argp[idx].data.str.len] = 0;
641 argp[idx].data.prx = find_stktable(trash.str);
642 if (!argp[idx].data.prx)
643 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
644 argp[idx].type = ARGT_TAB;
645 break;
646
647 case ARGT_SRV:
648 if (argp[idx].type != ARGT_STR)
649 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
650 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
651 trash.str[argp[idx].data.str.len] = 0;
652 sname = strrchr(trash.str, '/');
653 if (sname) {
654 *sname++ = '\0';
655 pname = trash.str;
656 px = findproxy(pname, PR_CAP_BE);
657 if (!px)
658 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
659 }
660 else {
661 sname = trash.str;
662 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100663 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100664 argp[idx].data.srv = findserver(px, sname);
665 if (!argp[idx].data.srv)
666 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
667 argp[idx].type = ARGT_SRV;
668 break;
669
670 case ARGT_IPV4:
671 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
672 trash.str[argp[idx].data.str.len] = 0;
673 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
674 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
675 argp[idx].type = ARGT_IPV4;
676 break;
677
678 case ARGT_MSK4:
679 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
680 trash.str[argp[idx].data.str.len] = 0;
681 if (!str2mask(trash.str, &argp[idx].data.ipv4))
682 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
683 argp[idx].type = ARGT_MSK4;
684 break;
685
686 case ARGT_IPV6:
687 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
688 trash.str[argp[idx].data.str.len] = 0;
689 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
690 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
691 argp[idx].type = ARGT_IPV6;
692 break;
693
694 case ARGT_MSK6:
695 case ARGT_MAP:
696 case ARGT_REG:
697 case ARGT_USR:
698 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100699 break;
700 }
701
702 /* Check for type of argument. */
703 if ((mask & ARGT_MASK) != argp[idx].type) {
704 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
705 arg_type_names[(mask & ARGT_MASK)],
706 arg_type_names[argp[idx].type & ARGT_MASK]);
707 WILL_LJMP(luaL_argerror(L, first + idx, msg));
708 }
709
710 /* Next argument. */
711 mask >>= ARGT_BITS;
712 idx++;
713 }
714}
715
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100716/*
717 * The following functions are used to make correspondance between the the
718 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100719 *
720 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100721 * - hlua_sethlua : create the association between hlua context and lua_state.
722 */
723static inline struct hlua *hlua_gethlua(lua_State *L)
724{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100725 struct hlua **hlua = lua_getextraspace(L);
726 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100727}
728static inline void hlua_sethlua(struct hlua *hlua)
729{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100730 struct hlua **hlua_store = lua_getextraspace(hlua->T);
731 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100732}
733
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100734/* This function just ensure that the yield will be always
735 * returned with a timeout and permit to set some flags
736 */
737__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100738 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100739{
740 struct hlua *hlua = hlua_gethlua(L);
741
742 /* Set the wake timeout. If timeout is required, we set
743 * the expiration time.
744 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100745 hlua->wake_time = tick_first(timeout, hlua->expire);
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100746
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100747 hlua->flags |= flags;
748
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100749 /* Process the yield. */
750 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
751}
752
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100753/* This function initialises the Lua environment stored in the session.
754 * It must be called at the start of the session. This function creates
755 * an LUA coroutine. It can not be use to crete the main LUA context.
756 */
757int hlua_ctx_init(struct hlua *lua, struct task *task)
758{
759 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100760 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100761 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100762 lua->T = lua_newthread(gL.T);
763 if (!lua->T) {
764 lua->Tref = LUA_REFNIL;
765 return 0;
766 }
767 hlua_sethlua(lua);
768 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
769 lua->task = task;
770 return 1;
771}
772
773/* Used to destroy the Lua coroutine when the attached session or task
774 * is destroyed. The destroy also the memory context. The struct "lua"
775 * is not freed.
776 */
777void hlua_ctx_destroy(struct hlua *lua)
778{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100779 if (!lua->T)
780 return;
781
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100782 /* Purge all the pending signals. */
783 hlua_com_purge(lua);
784
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100785 /* The thread is garbage collected by Lua. */
786 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
787 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
788}
789
790/* This function is used to restore the Lua context when a coroutine
791 * fails. This function copy the common memory between old coroutine
792 * and the new coroutine. The old coroutine is destroyed, and its
793 * replaced by the new coroutine.
794 * If the flag "keep_msg" is set, the last entry of the old is assumed
795 * as string error message and it is copied in the new stack.
796 */
797static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
798{
799 lua_State *T;
800 int new_ref;
801
802 /* Renew the main LUA stack doesn't have sense. */
803 if (lua == &gL)
804 return 0;
805
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100806 /* New Lua coroutine. */
807 T = lua_newthread(gL.T);
808 if (!T)
809 return 0;
810
811 /* Copy last error message. */
812 if (keep_msg)
813 lua_xmove(lua->T, T, 1);
814
815 /* Copy data between the coroutines. */
816 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
817 lua_xmove(lua->T, T, 1);
818 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
819
820 /* Destroy old data. */
821 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
822
823 /* The thread is garbage collected by Lua. */
824 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
825
826 /* Fill the struct with the new coroutine values. */
827 lua->Mref = new_ref;
828 lua->T = T;
829 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
830
831 /* Set context. */
832 hlua_sethlua(lua);
833
834 return 1;
835}
836
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100837void hlua_hook(lua_State *L, lua_Debug *ar)
838{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100839 struct hlua *hlua = hlua_gethlua(L);
840
841 /* Lua cannot yield when its returning from a function,
842 * so, we can fix the interrupt hook to 1 instruction,
843 * expecting that the function is finnished.
844 */
845 if (lua_gethookmask(L) & LUA_MASKRET) {
846 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
847 return;
848 }
849
850 /* restore the interrupt condition. */
851 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
852
853 /* If we interrupt the Lua processing in yieldable state, we yield.
854 * If the state is not yieldable, trying yield causes an error.
855 */
856 if (lua_isyieldable(L))
857 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
858
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +0100859 /* If we cannot yield, update the clock and check the timeout. */
860 tv_update_date(0, 1);
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100861 if (tick_is_expired(hlua->expire, now_ms)) {
862 lua_pushfstring(L, "execution timeout");
863 WILL_LJMP(lua_error(L));
864 }
865
866 /* Try to interrupt the process at the end of the current
867 * unyieldable function.
868 */
869 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100870}
871
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100872/* This function start or resumes the Lua stack execution. If the flag
873 * "yield_allowed" if no set and the LUA stack execution returns a yield
874 * The function return an error.
875 *
876 * The function can returns 4 values:
877 * - HLUA_E_OK : The execution is terminated without any errors.
878 * - HLUA_E_AGAIN : The execution must continue at the next associated
879 * task wakeup.
880 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
881 * the top of the stack.
882 * - HLUA_E_ERR : An error has occured without error message.
883 *
884 * If an error occured, the stack is renewed and it is ready to run new
885 * LUA code.
886 */
887static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
888{
889 int ret;
890 const char *msg;
891
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100892 HLUA_SET_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100893
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100894 /* If we want to resume the task, then check first the execution timeout.
895 * if it is reached, we can interrupt the Lua processing.
896 */
897 if (tick_is_expired(lua->expire, now_ms))
898 goto timeout_reached;
899
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100900resume_execution:
901
902 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
903 * instructions. it is used for preventing infinite loops.
904 */
905 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
906
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +0100907 /* Remove all flags except the running flags. */
908 lua->flags = HLUA_RUN;
909
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100910 /* Call the function. */
911 ret = lua_resume(lua->T, gL.T, lua->nargs);
912 switch (ret) {
913
914 case LUA_OK:
915 ret = HLUA_E_OK;
916 break;
917
918 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100919 /* Check if the execution timeout is expired. It it is the case, we
920 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100921 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100922 if (tick_is_expired(lua->expire, now_ms)) {
923
924timeout_reached:
925
926 lua_settop(lua->T, 0); /* Empty the stack. */
927 if (!lua_checkstack(lua->T, 1)) {
928 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100929 break;
930 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100931 lua_pushfstring(lua->T, "execution timeout");
932 ret = HLUA_E_ERRMSG;
933 break;
934 }
935 /* Process the forced yield. if the general yield is not allowed or
936 * if no task were associated this the current Lua execution
937 * coroutine, we resume the execution. Else we want to return in the
938 * scheduler and we want to be waked up again, to continue the
939 * current Lua execution. So we schedule our own task.
940 */
941 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100942 if (!yield_allowed || !lua->task)
943 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100944 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100945 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100946 if (!yield_allowed) {
947 lua_settop(lua->T, 0); /* Empty the stack. */
948 if (!lua_checkstack(lua->T, 1)) {
949 ret = HLUA_E_ERR;
950 break;
951 }
952 lua_pushfstring(lua->T, "yield not allowed");
953 ret = HLUA_E_ERRMSG;
954 break;
955 }
956 ret = HLUA_E_AGAIN;
957 break;
958
959 case LUA_ERRRUN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100960 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100961 if (!lua_checkstack(lua->T, 1)) {
962 ret = HLUA_E_ERR;
963 break;
964 }
965 msg = lua_tostring(lua->T, -1);
966 lua_settop(lua->T, 0); /* Empty the stack. */
967 lua_pop(lua->T, 1);
968 if (msg)
969 lua_pushfstring(lua->T, "runtime error: %s", msg);
970 else
971 lua_pushfstring(lua->T, "unknown runtime error");
972 ret = HLUA_E_ERRMSG;
973 break;
974
975 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100976 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100977 lua_settop(lua->T, 0); /* Empty the stack. */
978 if (!lua_checkstack(lua->T, 1)) {
979 ret = HLUA_E_ERR;
980 break;
981 }
982 lua_pushfstring(lua->T, "out of memory error");
983 ret = HLUA_E_ERRMSG;
984 break;
985
986 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100987 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100988 if (!lua_checkstack(lua->T, 1)) {
989 ret = HLUA_E_ERR;
990 break;
991 }
992 msg = lua_tostring(lua->T, -1);
993 lua_settop(lua->T, 0); /* Empty the stack. */
994 lua_pop(lua->T, 1);
995 if (msg)
996 lua_pushfstring(lua->T, "message handler error: %s", msg);
997 else
998 lua_pushfstring(lua->T, "message handler error");
999 ret = HLUA_E_ERRMSG;
1000 break;
1001
1002 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001003 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001004 lua_settop(lua->T, 0); /* Empty the stack. */
1005 if (!lua_checkstack(lua->T, 1)) {
1006 ret = HLUA_E_ERR;
1007 break;
1008 }
1009 lua_pushfstring(lua->T, "unknonwn error");
1010 ret = HLUA_E_ERRMSG;
1011 break;
1012 }
1013
1014 switch (ret) {
1015 case HLUA_E_AGAIN:
1016 break;
1017
1018 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001019 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001020 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001021 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001022 break;
1023
1024 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001025 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001026 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001027 hlua_ctx_renew(lua, 0);
1028 break;
1029
1030 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001031 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001032 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001033 break;
1034 }
1035
1036 return ret;
1037}
1038
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001039/* This function is an LUA binding. It provides a function
1040 * for deleting ACL from a referenced ACL file.
1041 */
1042__LJMP static int hlua_del_acl(lua_State *L)
1043{
1044 const char *name;
1045 const char *key;
1046 struct pat_ref *ref;
1047
1048 MAY_LJMP(check_args(L, 2, "del_acl"));
1049
1050 name = MAY_LJMP(luaL_checkstring(L, 1));
1051 key = MAY_LJMP(luaL_checkstring(L, 2));
1052
1053 ref = pat_ref_lookup(name);
1054 if (!ref)
1055 WILL_LJMP(luaL_error(L, "'del_acl': unkown acl file '%s'", name));
1056
1057 pat_ref_delete(ref, key);
1058 return 0;
1059}
1060
1061/* This function is an LUA binding. It provides a function
1062 * for deleting map entry from a referenced map file.
1063 */
1064static int hlua_del_map(lua_State *L)
1065{
1066 const char *name;
1067 const char *key;
1068 struct pat_ref *ref;
1069
1070 MAY_LJMP(check_args(L, 2, "del_map"));
1071
1072 name = MAY_LJMP(luaL_checkstring(L, 1));
1073 key = MAY_LJMP(luaL_checkstring(L, 2));
1074
1075 ref = pat_ref_lookup(name);
1076 if (!ref)
1077 WILL_LJMP(luaL_error(L, "'del_map': unkown acl file '%s'", name));
1078
1079 pat_ref_delete(ref, key);
1080 return 0;
1081}
1082
1083/* This function is an LUA binding. It provides a function
1084 * for adding ACL pattern from a referenced ACL file.
1085 */
1086static int hlua_add_acl(lua_State *L)
1087{
1088 const char *name;
1089 const char *key;
1090 struct pat_ref *ref;
1091
1092 MAY_LJMP(check_args(L, 2, "add_acl"));
1093
1094 name = MAY_LJMP(luaL_checkstring(L, 1));
1095 key = MAY_LJMP(luaL_checkstring(L, 2));
1096
1097 ref = pat_ref_lookup(name);
1098 if (!ref)
1099 WILL_LJMP(luaL_error(L, "'add_acl': unkown acl file '%s'", name));
1100
1101 if (pat_ref_find_elt(ref, key) == NULL)
1102 pat_ref_add(ref, key, NULL, NULL);
1103 return 0;
1104}
1105
1106/* This function is an LUA binding. It provides a function
1107 * for setting map pattern and sample from a referenced map
1108 * file.
1109 */
1110static int hlua_set_map(lua_State *L)
1111{
1112 const char *name;
1113 const char *key;
1114 const char *value;
1115 struct pat_ref *ref;
1116
1117 MAY_LJMP(check_args(L, 3, "set_map"));
1118
1119 name = MAY_LJMP(luaL_checkstring(L, 1));
1120 key = MAY_LJMP(luaL_checkstring(L, 2));
1121 value = MAY_LJMP(luaL_checkstring(L, 3));
1122
1123 ref = pat_ref_lookup(name);
1124 if (!ref)
1125 WILL_LJMP(luaL_error(L, "'set_map': unkown map file '%s'", name));
1126
1127 if (pat_ref_find_elt(ref, key) != NULL)
1128 pat_ref_set(ref, key, value, NULL);
1129 else
1130 pat_ref_add(ref, key, value, NULL);
1131 return 0;
1132}
1133
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001134/* A class is a lot of memory that contain data. This data can be a table,
1135 * an integer or user data. This data is associated with a metatable. This
1136 * metatable have an original version registred in the global context with
1137 * the name of the object (_G[<name>] = <metable> ).
1138 *
1139 * A metable is a table that modify the standard behavior of a standard
1140 * access to the associated data. The entries of this new metatable are
1141 * defined as is:
1142 *
1143 * http://lua-users.org/wiki/MetatableEvents
1144 *
1145 * __index
1146 *
1147 * we access an absent field in a table, the result is nil. This is
1148 * true, but it is not the whole truth. Actually, such access triggers
1149 * the interpreter to look for an __index metamethod: If there is no
1150 * such method, as usually happens, then the access results in nil;
1151 * otherwise, the metamethod will provide the result.
1152 *
1153 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1154 * the key does not appear in the table, but the metatable has an __index
1155 * property:
1156 *
1157 * - if the value is a function, the function is called, passing in the
1158 * table and the key; the return value of that function is returned as
1159 * the result.
1160 *
1161 * - if the value is another table, the value of the key in that table is
1162 * asked for and returned (and if it doesn't exist in that table, but that
1163 * table's metatable has an __index property, then it continues on up)
1164 *
1165 * - Use "rawget(myTable,key)" to skip this metamethod.
1166 *
1167 * http://www.lua.org/pil/13.4.1.html
1168 *
1169 * __newindex
1170 *
1171 * Like __index, but control property assignment.
1172 *
1173 * __mode - Control weak references. A string value with one or both
1174 * of the characters 'k' and 'v' which specifies that the the
1175 * keys and/or values in the table are weak references.
1176 *
1177 * __call - Treat a table like a function. When a table is followed by
1178 * parenthesis such as "myTable( 'foo' )" and the metatable has
1179 * a __call key pointing to a function, that function is invoked
1180 * (passing any specified arguments) and the return value is
1181 * returned.
1182 *
1183 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1184 * called, if the metatable for myTable has a __metatable
1185 * key, the value of that key is returned instead of the
1186 * actual metatable.
1187 *
1188 * __tostring - Control string representation. When the builtin
1189 * "tostring( myTable )" function is called, if the metatable
1190 * for myTable has a __tostring property set to a function,
1191 * that function is invoked (passing myTable to it) and the
1192 * return value is used as the string representation.
1193 *
1194 * __len - Control table length. When the table length is requested using
1195 * the length operator ( '#' ), if the metatable for myTable has
1196 * a __len key pointing to a function, that function is invoked
1197 * (passing myTable to it) and the return value used as the value
1198 * of "#myTable".
1199 *
1200 * __gc - Userdata finalizer code. When userdata is set to be garbage
1201 * collected, if the metatable has a __gc field pointing to a
1202 * function, that function is first invoked, passing the userdata
1203 * to it. The __gc metamethod is not called for tables.
1204 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1205 *
1206 * Special metamethods for redefining standard operators:
1207 * http://www.lua.org/pil/13.1.html
1208 *
1209 * __add "+"
1210 * __sub "-"
1211 * __mul "*"
1212 * __div "/"
1213 * __unm "!"
1214 * __pow "^"
1215 * __concat ".."
1216 *
1217 * Special methods for redfining standar relations
1218 * http://www.lua.org/pil/13.2.html
1219 *
1220 * __eq "=="
1221 * __lt "<"
1222 * __le "<="
1223 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001224
1225/*
1226 *
1227 *
1228 * Class Socket
1229 *
1230 *
1231 */
1232
1233__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1234{
1235 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1236}
1237
1238/* This function is the handler called for each I/O on the established
1239 * connection. It is used for notify space avalaible to send or data
1240 * received.
1241 */
1242static void hlua_socket_handler(struct stream_interface *si)
1243{
1244 struct appctx *appctx = objt_appctx(si->end);
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001245 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001246
1247 /* Wakeup the main session if the client connection is closed. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001248 if (!c || channel_output_closed(si_ic(si)) || channel_input_closed(si_oc(si))) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001249 if (appctx->ctx.hlua.socket) {
1250 appctx->ctx.hlua.socket->s = NULL;
1251 appctx->ctx.hlua.socket = NULL;
1252 }
1253 si_shutw(si);
1254 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001255 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001256 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1257 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1258 return;
1259 }
1260
1261 if (!(c->flags & CO_FL_CONNECTED))
1262 return;
1263
1264 /* This function is called after the connect. */
1265 appctx->ctx.hlua.connected = 1;
1266
1267 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001268 if (channel_may_recv(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001269 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1270
1271 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001272 if (channel_is_empty(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001273 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1274}
1275
1276/* This function is called when the "struct session" is destroyed.
1277 * Remove the link from the object to this session.
1278 * Wake all the pending signals.
1279 */
1280static void hlua_socket_release(struct stream_interface *si)
1281{
1282 struct appctx *appctx = objt_appctx(si->end);
1283
1284 /* Remove my link in the original object. */
1285 if (appctx->ctx.hlua.socket)
1286 appctx->ctx.hlua.socket->s = NULL;
1287
1288 /* Wake all the task waiting for me. */
1289 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1290 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1291}
1292
1293/* If the garbage collectio of the object is launch, nobody
1294 * uses this object. If the session does not exists, just quit.
1295 * Send the shutdown signal to the session. In some cases,
1296 * pending signal can rest in the read and write lists. destroy
1297 * it.
1298 */
1299__LJMP static int hlua_socket_gc(lua_State *L)
1300{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001301 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001302 struct appctx *appctx;
1303
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001304 MAY_LJMP(check_args(L, 1, "__gc"));
1305
1306 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001307 if (!socket->s)
1308 return 0;
1309
1310 /* Remove all reference between the Lua stack and the coroutine session. */
1311 appctx = objt_appctx(socket->s->si[0].end);
1312 session_shutdown(socket->s, SN_ERR_KILLED);
1313 socket->s = NULL;
1314 appctx->ctx.hlua.socket = NULL;
1315
1316 return 0;
1317}
1318
1319/* The close function send shutdown signal and break the
1320 * links between the session and the object.
1321 */
1322__LJMP static int hlua_socket_close(lua_State *L)
1323{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001324 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001325 struct appctx *appctx;
1326
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001327 MAY_LJMP(check_args(L, 1, "close"));
1328
1329 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001330 if (!socket->s)
1331 return 0;
1332
1333 /* Close the session and remove the associated stop task. */
1334 session_shutdown(socket->s, SN_ERR_KILLED);
1335 appctx = objt_appctx(socket->s->si[0].end);
1336 appctx->ctx.hlua.socket = NULL;
1337 socket->s = NULL;
1338
1339 return 0;
1340}
1341
1342/* This Lua function assumes that the stack contain three parameters.
1343 * 1 - USERDATA containing a struct socket
1344 * 2 - INTEGER with values of the macro defined below
1345 * If the integer is -1, we must read at most one line.
1346 * If the integer is -2, we ust read all the data until the
1347 * end of the stream.
1348 * If the integer is positive value, we must read a number of
1349 * bytes corresponding to this value.
1350 */
1351#define HLSR_READ_LINE (-1)
1352#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001353__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001354{
1355 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1356 int wanted = lua_tointeger(L, 2);
1357 struct hlua *hlua = hlua_gethlua(L);
1358 struct appctx *appctx;
1359 int len;
1360 int nblk;
1361 char *blk1;
1362 int len1;
1363 char *blk2;
1364 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001365 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001366 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001367
1368 /* Check if this lua stack is schedulable. */
1369 if (!hlua || !hlua->task)
1370 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1371 "'frontend', 'backend' or 'task'"));
1372
1373 /* check for connection closed. If some data where read, return it. */
1374 if (!socket->s)
1375 goto connection_closed;
1376
Willy Tarreau94aa6172015-03-13 14:19:06 +01001377 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001378 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001379 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001380 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001381 if (nblk < 0) /* Connection close. */
1382 goto connection_closed;
1383 if (nblk == 0) /* No data avalaible. */
1384 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001385
1386 /* remove final \r\n. */
1387 if (nblk == 1) {
1388 if (blk1[len1-1] == '\n') {
1389 len1--;
1390 skip_at_end++;
1391 if (blk1[len1-1] == '\r') {
1392 len1--;
1393 skip_at_end++;
1394 }
1395 }
1396 }
1397 else {
1398 if (blk2[len2-1] == '\n') {
1399 len2--;
1400 skip_at_end++;
1401 if (blk2[len2-1] == '\r') {
1402 len2--;
1403 skip_at_end++;
1404 }
1405 }
1406 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001407 }
1408
1409 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001410 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001411 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001412 if (nblk < 0) /* Connection close. */
1413 goto connection_closed;
1414 if (nblk == 0) /* No data avalaible. */
1415 goto connection_empty;
1416 }
1417
1418 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001419 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001420 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001421 if (nblk < 0) /* Connection close. */
1422 goto connection_closed;
1423 if (nblk == 0) /* No data avalaible. */
1424 goto connection_empty;
1425
1426 if (len1 > wanted) {
1427 nblk = 1;
1428 len1 = wanted;
1429 } if (nblk == 2 && len1 + len2 > wanted)
1430 len2 = wanted - len1;
1431 }
1432
1433 len = len1;
1434
1435 luaL_addlstring(&socket->b, blk1, len1);
1436 if (nblk == 2) {
1437 len += len2;
1438 luaL_addlstring(&socket->b, blk2, len2);
1439 }
1440
1441 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001442 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001443
1444 /* Don't wait anything. */
1445 si_update(&socket->s->si[0]);
1446
1447 /* If the pattern reclaim to read all the data
1448 * in the connection, got out.
1449 */
1450 if (wanted == HLSR_READ_ALL)
1451 goto connection_empty;
1452 else if (wanted >= 0 && len < wanted)
1453 goto connection_empty;
1454
1455 /* Return result. */
1456 luaL_pushresult(&socket->b);
1457 return 1;
1458
1459connection_closed:
1460
1461 /* If the buffer containds data. */
1462 if (socket->b.n > 0) {
1463 luaL_pushresult(&socket->b);
1464 return 1;
1465 }
1466 lua_pushnil(L);
1467 lua_pushstring(L, "connection closed.");
1468 return 2;
1469
1470connection_empty:
1471
1472 appctx = objt_appctx(socket->s->si[0].end);
1473 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1474 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001475 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001476 return 0;
1477}
1478
1479/* This Lus function gets two parameters. The first one can be string
1480 * or a number. If the string is "*l", the user require one line. If
1481 * the string is "*a", the user require all the content of the stream.
1482 * If the value is a number, the user require a number of bytes equal
1483 * to the value. The default value is "*l" (a line).
1484 *
1485 * This paraeter with a variable type is converted in integer. This
1486 * integer takes this values:
1487 * -1 : read a line
1488 * -2 : read all the stream
1489 * >0 : amount if bytes.
1490 *
1491 * The second parameter is optinal. It contains a string that must be
1492 * concatenated with the read data.
1493 */
1494__LJMP static int hlua_socket_receive(struct lua_State *L)
1495{
1496 int wanted = HLSR_READ_LINE;
1497 const char *pattern;
1498 int type;
1499 char *error;
1500 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001501 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001502
1503 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1504 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1505
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001506 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001507
1508 /* check for pattern. */
1509 if (lua_gettop(L) >= 2) {
1510 type = lua_type(L, 2);
1511 if (type == LUA_TSTRING) {
1512 pattern = lua_tostring(L, 2);
1513 if (strcmp(pattern, "*a") == 0)
1514 wanted = HLSR_READ_ALL;
1515 else if (strcmp(pattern, "*l") == 0)
1516 wanted = HLSR_READ_LINE;
1517 else {
1518 wanted = strtoll(pattern, &error, 10);
1519 if (*error != '\0')
1520 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1521 }
1522 }
1523 else if (type == LUA_TNUMBER) {
1524 wanted = lua_tointeger(L, 2);
1525 if (wanted < 0)
1526 WILL_LJMP(luaL_error(L, "Unsupported size."));
1527 }
1528 }
1529
1530 /* Set pattern. */
1531 lua_pushinteger(L, wanted);
1532 lua_replace(L, 2);
1533
1534 /* init bufffer, and fiil it wih prefix. */
1535 luaL_buffinit(L, &socket->b);
1536
1537 /* Check prefix. */
1538 if (lua_gettop(L) >= 3) {
1539 if (lua_type(L, 3) != LUA_TSTRING)
1540 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1541 pattern = lua_tolstring(L, 3, &len);
1542 luaL_addlstring(&socket->b, pattern, len);
1543 }
1544
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001545 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001546}
1547
1548/* Write the Lua input string in the output buffer.
1549 * This fucntion returns a yield if no space are available.
1550 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001551static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001552{
1553 struct hlua_socket *socket;
1554 struct hlua *hlua = hlua_gethlua(L);
1555 struct appctx *appctx;
1556 size_t buf_len;
1557 const char *buf;
1558 int len;
1559 int send_len;
1560 int sent;
1561
1562 /* Check if this lua stack is schedulable. */
1563 if (!hlua || !hlua->task)
1564 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1565 "'frontend', 'backend' or 'task'"));
1566
1567 /* Get object */
1568 socket = MAY_LJMP(hlua_checksocket(L, 1));
1569 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001570 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001571
1572 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001573 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001574 lua_pushinteger(L, -1);
1575 return 1;
1576 }
1577
1578 /* Update the input buffer data. */
1579 buf += sent;
1580 send_len = buf_len - sent;
1581
1582 /* All the data are sent. */
1583 if (sent >= buf_len)
1584 return 1; /* Implicitly return the length sent. */
1585
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001586 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1587 * the request buffer if its not required.
1588 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001589 if (socket->s->req.buf->size == 0) {
Willy Tarreau78955f42014-12-28 13:09:02 +01001590 if (!session_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001591 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001592 goto hlua_socket_write_yield_return;
1593 }
1594 }
1595
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001596 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001597 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001598 if (len <= 0)
1599 goto hlua_socket_write_yield_return;
1600
1601 /* send data */
1602 if (len < send_len)
1603 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001604 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001605
1606 /* "Not enough space" (-1), "Buffer too little to contain
1607 * the data" (-2) are not expected because the available length
1608 * is tested.
1609 * Other unknown error are also not expected.
1610 */
1611 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001612 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001613 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001614
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001615 MAY_LJMP(hlua_socket_close(L));
1616 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001617 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001618 return 1;
1619 }
1620
1621 /* update buffers. */
1622 si_update(&socket->s->si[0]);
Willy Tarreau94aa6172015-03-13 14:19:06 +01001623 socket->s->req.rex = TICK_ETERNITY;
1624 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001625
1626 /* Update length sent. */
1627 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001628 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001629
1630 /* All the data buffer is sent ? */
1631 if (sent + len >= buf_len)
1632 return 1;
1633
1634hlua_socket_write_yield_return:
1635 appctx = objt_appctx(socket->s->si[0].end);
1636 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1637 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001638 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001639 return 0;
1640}
1641
1642/* This function initiate the send of data. It just check the input
1643 * parameters and push an integer in the Lua stack that contain the
1644 * amount of data writed in the buffer. This is used by the function
1645 * "hlua_socket_write_yield" that can yield.
1646 *
1647 * The Lua function gets between 3 and 4 parameters. The first one is
1648 * the associated object. The second is a string buffer. The third is
1649 * a facultative integer that represents where is the buffer position
1650 * of the start of the data that can send. The first byte is the
1651 * position "1". The default value is "1". The fourth argument is a
1652 * facultative integer that represents where is the buffer position
1653 * of the end of the data that can send. The default is the last byte.
1654 */
1655static int hlua_socket_send(struct lua_State *L)
1656{
1657 int i;
1658 int j;
1659 const char *buf;
1660 size_t buf_len;
1661
1662 /* Check number of arguments. */
1663 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1664 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1665
1666 /* Get the string. */
1667 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1668
1669 /* Get and check j. */
1670 if (lua_gettop(L) == 4) {
1671 j = MAY_LJMP(luaL_checkinteger(L, 4));
1672 if (j < 0)
1673 j = buf_len + j + 1;
1674 if (j > buf_len)
1675 j = buf_len + 1;
1676 lua_pop(L, 1);
1677 }
1678 else
1679 j = buf_len;
1680
1681 /* Get and check i. */
1682 if (lua_gettop(L) == 3) {
1683 i = MAY_LJMP(luaL_checkinteger(L, 3));
1684 if (i < 0)
1685 i = buf_len + i + 1;
1686 if (i > buf_len)
1687 i = buf_len + 1;
1688 lua_pop(L, 1);
1689 } else
1690 i = 1;
1691
1692 /* Check bth i and j. */
1693 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001694 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001695 return 1;
1696 }
1697 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001698 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001699 return 1;
1700 }
1701 if (i == 0)
1702 i = 1;
1703 if (j == 0)
1704 j = 1;
1705
1706 /* Pop the string. */
1707 lua_pop(L, 1);
1708
1709 /* Update the buffer length. */
1710 buf += i - 1;
1711 buf_len = j - i + 1;
1712 lua_pushlstring(L, buf, buf_len);
1713
1714 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001715 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001716
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001717 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001718}
1719
1720#define SOCKET_INFO_EXPANDED_FORM "[0000:0000:0000:0000:0000:0000:0000:0000]:12345"
1721static char _socket_info_expanded_form[] = SOCKET_INFO_EXPANDED_FORM;
1722#define SOCKET_INFO_MAX_LEN (sizeof(_socket_info_expanded_form))
1723__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
1724{
1725 static char buffer[SOCKET_INFO_MAX_LEN];
1726 int ret;
1727 int len;
1728 char *p;
1729
1730 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
1731 if (ret <= 0) {
1732 lua_pushnil(L);
1733 return 1;
1734 }
1735
1736 if (ret == AF_UNIX) {
1737 lua_pushstring(L, buffer+1);
1738 return 1;
1739 }
1740 else if (ret == AF_INET6) {
1741 buffer[0] = '[';
1742 len = strlen(buffer);
1743 buffer[len] = ']';
1744 len++;
1745 buffer[len] = ':';
1746 len++;
1747 p = buffer;
1748 }
1749 else if (ret == AF_INET) {
1750 p = buffer + 1;
1751 len = strlen(p);
1752 p[len] = ':';
1753 len++;
1754 }
1755 else {
1756 lua_pushnil(L);
1757 return 1;
1758 }
1759
1760 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
1761 lua_pushnil(L);
1762 return 1;
1763 }
1764
1765 lua_pushstring(L, p);
1766 return 1;
1767}
1768
1769/* Returns information about the peer of the connection. */
1770__LJMP static int hlua_socket_getpeername(struct lua_State *L)
1771{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001772 struct hlua_socket *socket;
1773 struct connection *conn;
1774
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001775 MAY_LJMP(check_args(L, 1, "getpeername"));
1776
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001777 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001778
1779 /* Check if the tcp object is avalaible. */
1780 if (!socket->s) {
1781 lua_pushnil(L);
1782 return 1;
1783 }
1784
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001785 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001786 if (!conn) {
1787 lua_pushnil(L);
1788 return 1;
1789 }
1790
1791 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
1792 unsigned int salen = sizeof(conn->addr.to);
1793 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
1794 lua_pushnil(L);
1795 return 1;
1796 }
1797 conn->flags |= CO_FL_ADDR_TO_SET;
1798 }
1799
1800 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
1801}
1802
1803/* Returns information about my connection side. */
1804static int hlua_socket_getsockname(struct lua_State *L)
1805{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001806 struct hlua_socket *socket;
1807 struct connection *conn;
1808
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001809 MAY_LJMP(check_args(L, 1, "getsockname"));
1810
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001811 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001812
1813 /* Check if the tcp object is avalaible. */
1814 if (!socket->s) {
1815 lua_pushnil(L);
1816 return 1;
1817 }
1818
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001819 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001820 if (!conn) {
1821 lua_pushnil(L);
1822 return 1;
1823 }
1824
1825 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
1826 unsigned int salen = sizeof(conn->addr.from);
1827 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
1828 lua_pushnil(L);
1829 return 1;
1830 }
1831 conn->flags |= CO_FL_ADDR_FROM_SET;
1832 }
1833
1834 return hlua_socket_info(L, &conn->addr.from);
1835}
1836
1837/* This struct define the applet. */
1838static struct si_applet update_applet = {
1839 .obj_type = OBJ_TYPE_APPLET,
1840 .name = "<LUA_TCP>",
1841 .fct = hlua_socket_handler,
1842 .release = hlua_socket_release,
1843};
1844
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001845__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001846{
1847 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1848 struct hlua *hlua = hlua_gethlua(L);
1849 struct appctx *appctx;
1850
1851 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001852 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001853 lua_pushnil(L);
1854 lua_pushstring(L, "Can't connect");
1855 return 2;
1856 }
1857
1858 appctx = objt_appctx(socket->s->si[0].end);
1859
1860 /* Check for connection established. */
1861 if (appctx->ctx.hlua.connected) {
1862 lua_pushinteger(L, 1);
1863 return 1;
1864 }
1865
1866 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1867 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001868 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001869 return 0;
1870}
1871
1872/* This function fail or initite the connection. */
1873__LJMP static int hlua_socket_connect(struct lua_State *L)
1874{
1875 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001876 int port;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001877 const char *ip;
1878 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01001879 struct hlua *hlua;
1880 struct appctx *appctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001881
1882 MAY_LJMP(check_args(L, 3, "connect"));
1883
1884 /* Get args. */
1885 socket = MAY_LJMP(hlua_checksocket(L, 1));
1886 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001887 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001888
Willy Tarreau350f4872014-11-28 14:42:25 +01001889 conn = si_alloc_conn(&socket->s->si[1], 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001890 if (!conn)
1891 WILL_LJMP(luaL_error(L, "connect: internal error"));
1892
1893 /* Parse ip address. */
1894 conn->addr.to.ss_family = AF_UNSPEC;
1895 if (!str2ip2(ip, &conn->addr.to, 0))
1896 WILL_LJMP(luaL_error(L, "connect: cannot parse ip address '%s'", ip));
1897
1898 /* Set port. */
1899 if (conn->addr.to.ss_family == AF_INET)
1900 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
1901 else if (conn->addr.to.ss_family == AF_INET6)
1902 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
1903
1904 /* it is important not to call the wakeup function directly but to
1905 * pass through task_wakeup(), because this one knows how to apply
1906 * priorities to tasks.
1907 */
1908 task_wakeup(socket->s->task, TASK_WOKEN_INIT);
1909
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01001910 hlua = hlua_gethlua(L);
1911 appctx = objt_appctx(socket->s->si[0].end);
1912 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1913 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001914 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001915
1916 return 0;
1917}
1918
Baptiste Assmann84bb4932015-03-02 21:40:06 +01001919#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001920__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
1921{
1922 struct hlua_socket *socket;
1923
1924 MAY_LJMP(check_args(L, 3, "connect_ssl"));
1925 socket = MAY_LJMP(hlua_checksocket(L, 1));
1926 socket->s->target = &socket_ssl.obj_type;
1927 return MAY_LJMP(hlua_socket_connect(L));
1928}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01001929#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001930
1931__LJMP static int hlua_socket_setoption(struct lua_State *L)
1932{
1933 return 0;
1934}
1935
1936__LJMP static int hlua_socket_settimeout(struct lua_State *L)
1937{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001938 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001939 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001940
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001941 MAY_LJMP(check_args(L, 2, "settimeout"));
1942
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001943 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001944 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001945
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001946 socket->s->req.rto = tmout;
1947 socket->s->req.wto = tmout;
1948 socket->s->res.rto = tmout;
1949 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001950
1951 return 0;
1952}
1953
1954__LJMP static int hlua_socket_new(lua_State *L)
1955{
1956 struct hlua_socket *socket;
1957 struct appctx *appctx;
1958
1959 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01001960 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001961 hlua_pusherror(L, "socket: full stack");
1962 goto out_fail_conf;
1963 }
1964
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01001965 /* Create the object: obj[0] = userdata. */
1966 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001967 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01001968 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001969 memset(socket, 0, sizeof(*socket));
1970
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01001971 /* Check if the various memory pools are intialized. */
Willy Tarreaua27dc192014-11-27 22:10:04 +01001972 if (!pool2_session || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01001973 hlua_pusherror(L, "socket: uninitialized pools.");
1974 goto out_fail_conf;
1975 }
1976
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001977 /* Pop a class session metatable and affect it to the userdata. */
1978 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
1979 lua_setmetatable(L, -2);
1980
1981 /*
1982 *
1983 * Get memory for the request.
1984 *
1985 */
1986
1987 socket->s = pool_alloc2(pool2_session);
1988 if (!socket->s) {
1989 hlua_pusherror(L, "socket: out of memory");
1990 goto out_fail_conf;
1991 }
1992
1993 socket->s->task = task_new();
1994 if (!socket->s->task) {
1995 hlua_pusherror(L, "socket: out of memory");
1996 goto out_free_session;
1997 }
1998
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001999 socket->s->req.buf = pool_alloc2(pool2_buffer);
2000 if (!socket->s->req.buf) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002001 hlua_pusherror(L, "socket: out of memory");
2002 goto out_fail_req_buf;
2003 }
2004
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002005 socket->s->res.buf = pool_alloc2(pool2_buffer);
2006 if (!socket->s->res.buf) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002007 hlua_pusherror(L, "socket: out of memory");
2008 goto out_fail_rep_buf;
2009 }
2010
2011 /* Configura empty Lua for the session. */
2012 socket->s->hlua.T = NULL;
2013 socket->s->hlua.Tref = LUA_REFNIL;
2014 socket->s->hlua.Mref = LUA_REFNIL;
2015 socket->s->hlua.nargs = 0;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01002016 socket->s->hlua.flags = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002017 LIST_INIT(&socket->s->hlua.com);
2018
2019 /* session initialisation. */
2020 session_init_srv_conn(socket->s);
2021
2022 /*
2023 *
2024 * Configure the associated task.
2025 *
2026 */
2027
2028 /* This is the dedicated function to process the session. This function
2029 * is able to establish the conection, process the timeouts, etc ...
2030 */
2031 socket->s->task->process = process_session;
2032
2033 /* Back reference to session. This is used by process_session(). */
2034 socket->s->task->context = socket->s;
2035
2036 /* The priority of the task is normal. */
2037 socket->s->task->nice = 0;
2038
2039 /* Init the next run to eternity. Later in this function, this task is
2040 * waked.
2041 */
2042 socket->s->task->expire = TICK_ETERNITY;
2043
2044 /*
2045 *
2046 * Initialize the attached buffers
2047 *
2048 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002049 socket->s->req.buf->size = global.tune.bufsize;
2050 socket->s->res.buf->size = global.tune.bufsize;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002051
2052 /*
2053 *
2054 * Initialize channels.
2055 *
2056 */
2057
2058 /* This function reset the struct. It must be called
2059 * before the configuration.
2060 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002061 channel_init(&socket->s->req);
2062 channel_init(&socket->s->res);
Willy Tarreauef573c02014-11-28 14:17:09 +01002063 socket->s->res.flags |= CF_ISRESP;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002064
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002065 socket->s->req.analysers = 0;
2066 socket->s->req.rto = socket_proxy.timeout.client;
2067 socket->s->req.wto = socket_proxy.timeout.server;
2068 socket->s->req.rex = TICK_ETERNITY;
2069 socket->s->req.wex = TICK_ETERNITY;
2070 socket->s->req.analyse_exp = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002071
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002072 socket->s->res.analysers = 0;
2073 socket->s->res.rto = socket_proxy.timeout.server;
2074 socket->s->res.wto = socket_proxy.timeout.client;
2075 socket->s->res.rex = TICK_ETERNITY;
2076 socket->s->res.wex = TICK_ETERNITY;
2077 socket->s->res.analyse_exp = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002078
2079 /*
2080 *
2081 * Configure the session.
2082 *
2083 */
2084
2085 /* The session dont have listener. The listener is used with real
2086 * proxies.
2087 */
2088 socket->s->listener = NULL;
2089
2090 /* The flags are initialized to 0. Values are setted later. */
2091 socket->s->flags = 0;
2092
2093 /* Assign the configured proxy to the new session. */
2094 socket->s->be = &socket_proxy;
2095 socket->s->fe = &socket_proxy;
2096
2097 /* XXX: Set namy variables */
2098 socket->s->store_count = 0;
2099 memset(socket->s->stkctr, 0, sizeof(socket->s->stkctr));
2100
2101 /* Configure logs. */
2102 socket->s->logs.logwait = 0;
2103 socket->s->logs.level = 0;
2104 socket->s->logs.accept_date = date; /* user-visible date for logging */
2105 socket->s->logs.tv_accept = now; /* corrected date for internal use */
2106 socket->s->do_log = NULL;
2107
2108 /* Function used if an error is occured. */
2109 socket->s->srv_error = default_srv_error;
2110
2111 /* Init the list of buffers. */
2112 LIST_INIT(&socket->s->buffer_wait);
2113
2114 /* Dont configure the unique ID. */
2115 socket->s->uniq_id = 0;
2116 socket->s->unique_id = NULL;
2117
2118 /* XXX: ? */
2119 socket->s->pend_pos = NULL;
2120
2121 /* XXX: See later. */
2122 socket->s->txn.sessid = NULL;
2123 socket->s->txn.srv_cookie = NULL;
2124 socket->s->txn.cli_cookie = NULL;
2125 socket->s->txn.uri = NULL;
2126 socket->s->txn.req.cap = NULL;
2127 socket->s->txn.rsp.cap = NULL;
2128 socket->s->txn.hdr_idx.v = NULL;
2129 socket->s->txn.hdr_idx.size = 0;
2130 socket->s->txn.hdr_idx.used = 0;
2131
2132 /* Configure "left" stream interface as applet. This "si" produce
2133 * and use the data received from the server. The applet is initialized
2134 * and is attached to the stream interface.
2135 */
2136
2137 /* The data producer is already connected. It is the applet. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002138 socket->s->req.flags = CF_READ_ATTACHED;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002139
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002140 channel_auto_connect(&socket->s->req); /* don't wait to establish connection */
2141 channel_auto_close(&socket->s->req); /* let the producer forward close requests */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002142
Willy Tarreaua5f5d8d2014-11-28 11:26:07 +01002143 socket->s->si[0].flags = SI_FL_NONE;
Willy Tarreau819d3322014-11-28 12:12:34 +01002144 si_reset(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002145 si_set_state(&socket->s->si[0], SI_ST_EST); /* connection established (resource exists) */
2146
2147 appctx = stream_int_register_handler(&socket->s->si[0], &update_applet);
2148 if (!appctx)
2149 goto out_fail_conn1;
2150 appctx->ctx.hlua.socket = socket;
2151 appctx->ctx.hlua.connected = 0;
2152 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2153 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
2154
2155 /* Configure "right" stream interface. this "si" is used to connect
2156 * and retrieve data from the server. The connection is initialized
2157 * with the "struct server".
2158 */
Willy Tarreaua5f5d8d2014-11-28 11:26:07 +01002159 socket->s->si[1].flags = SI_FL_ISBACK;
Willy Tarreau819d3322014-11-28 12:12:34 +01002160 si_reset(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002161 si_set_state(&socket->s->si[1], SI_ST_INI);
2162 socket->s->si[1].conn_retries = socket_proxy.conn_retries;
2163
2164 /* Force destination server. */
2165 socket->s->flags |= SN_DIRECT | SN_ASSIGNED | SN_ADDR_SET | SN_BE_ASSIGNED;
2166 socket->s->target = &socket_tcp.obj_type;
2167
2168 /* This session is added to te lists of alive sessions. */
2169 LIST_ADDQ(&sessions, &socket->s->list);
2170
2171 /* XXX: I think that this list is used by stats. */
2172 LIST_INIT(&socket->s->back_refs);
2173
2174 /* Update statistics counters. */
2175 socket_proxy.feconn++; /* beconn will be increased later */
2176 jobs++;
2177 totalconn++;
2178
2179 /* Return yield waiting for connection. */
2180 return 1;
2181
2182out_fail_conn1:
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002183 pool_free2(pool2_buffer, socket->s->res.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002184out_fail_rep_buf:
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002185 pool_free2(pool2_buffer, socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002186out_fail_req_buf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002187 task_free(socket->s->task);
2188out_free_session:
2189 pool_free2(pool2_session, socket->s);
2190out_fail_conf:
2191 WILL_LJMP(lua_error(L));
2192 return 0;
2193}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002194
2195/*
2196 *
2197 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002198 * Class Channel
2199 *
2200 *
2201 */
2202
2203/* Returns the struct hlua_channel join to the class channel in the
2204 * stack entry "ud" or throws an argument error.
2205 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002206__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002207{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002208 return (struct channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002209}
2210
Willy Tarreau47860ed2015-03-10 14:07:50 +01002211/* Pushes the channel onto the top of the stack. If the stask does not have a
2212 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002213 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002214static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002215{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002216 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002217 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002218 return 0;
2219
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002220 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002221 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002222 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002223
2224 /* Pop a class sesison metatable and affect it to the userdata. */
2225 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2226 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002227 return 1;
2228}
2229
2230/* Duplicate all the data present in the input channel and put it
2231 * in a string LUA variables. Returns -1 and push a nil value in
2232 * the stack if the channel is closed and all the data are consumed,
2233 * returns 0 if no data are available, otherwise it returns the length
2234 * of the builded string.
2235 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002236static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002237{
2238 char *blk1;
2239 char *blk2;
2240 int len1;
2241 int len2;
2242 int ret;
2243 luaL_Buffer b;
2244
Willy Tarreau47860ed2015-03-10 14:07:50 +01002245 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002246 if (unlikely(ret == 0))
2247 return 0;
2248
2249 if (unlikely(ret < 0)) {
2250 lua_pushnil(L);
2251 return -1;
2252 }
2253
2254 luaL_buffinit(L, &b);
2255 luaL_addlstring(&b, blk1, len1);
2256 if (unlikely(ret == 2))
2257 luaL_addlstring(&b, blk2, len2);
2258 luaL_pushresult(&b);
2259
2260 if (unlikely(ret == 2))
2261 return len1 + len2;
2262 return len1;
2263}
2264
2265/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2266 * a yield. This function keep the data in the buffer.
2267 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002268__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002269{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002270 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002271
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002272 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2273
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002274 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002275 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002276 return 1;
2277}
2278
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002279/* Check arguments for the function "hlua_channel_dup_yield". */
2280__LJMP static int hlua_channel_dup(lua_State *L)
2281{
2282 MAY_LJMP(check_args(L, 1, "dup"));
2283 MAY_LJMP(hlua_checkchannel(L, 1));
2284 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2285}
2286
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002287/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2288 * a yield. This function consumes the data in the buffer. It returns
2289 * a string containing the data or a nil pointer if no data are available
2290 * and the channel is closed.
2291 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002292__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002293{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002294 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002295 int ret;
2296
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002297 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002298
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002299 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002300 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002301 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002302
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002303 if (unlikely(ret == -1))
2304 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002305
Willy Tarreau47860ed2015-03-10 14:07:50 +01002306 chn->buf->i -= ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002307 return 1;
2308}
2309
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002310/* Check arguments for the fucntion "hlua_channel_get_yield". */
2311__LJMP static int hlua_channel_get(lua_State *L)
2312{
2313 MAY_LJMP(check_args(L, 1, "get"));
2314 MAY_LJMP(hlua_checkchannel(L, 1));
2315 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2316}
2317
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002318/* This functions consumes and returns one line. If the channel is closed,
2319 * and the last data does not contains a final '\n', the data are returned
2320 * without the final '\n'. When no more data are avalaible, it returns nil
2321 * value.
2322 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002323__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002324{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002325 char *blk1;
2326 char *blk2;
2327 int len1;
2328 int len2;
2329 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002330 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002331 int ret;
2332 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002333
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002334 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2335
Willy Tarreau47860ed2015-03-10 14:07:50 +01002336 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002337 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002338 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002339
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002340 if (ret == -1) {
2341 lua_pushnil(L);
2342 return 1;
2343 }
2344
2345 luaL_buffinit(L, &b);
2346 luaL_addlstring(&b, blk1, len1);
2347 len = len1;
2348 if (unlikely(ret == 2)) {
2349 luaL_addlstring(&b, blk2, len2);
2350 len += len2;
2351 }
2352 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002353 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002354 return 1;
2355}
2356
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002357/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2358__LJMP static int hlua_channel_getline(lua_State *L)
2359{
2360 MAY_LJMP(check_args(L, 1, "getline"));
2361 MAY_LJMP(hlua_checkchannel(L, 1));
2362 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2363}
2364
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002365/* This function takes a string as input, and append it at the
2366 * input side of channel. If the data is too big, but a space
2367 * is probably available after sending some data, the function
2368 * yield. If the data is bigger than the buffer, or if the
2369 * channel is closed, it returns -1. otherwise, it returns the
2370 * amount of data writed.
2371 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002372__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002373{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002374 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002375 size_t len;
2376 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2377 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2378 int ret;
2379 int max;
2380
Willy Tarreau47860ed2015-03-10 14:07:50 +01002381 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002382 if (max > len - l)
2383 max = len - l;
2384
Willy Tarreau47860ed2015-03-10 14:07:50 +01002385 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002386 if (ret == -2 || ret == -3) {
2387 lua_pushinteger(L, -1);
2388 return 1;
2389 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002390 if (ret == -1) {
2391 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002392 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002393 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002394 l += ret;
2395 lua_pop(L, 1);
2396 lua_pushinteger(L, l);
2397
Willy Tarreau47860ed2015-03-10 14:07:50 +01002398 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2399 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002400 /* There are no space avalaible, and the output buffer is empty.
2401 * in this case, we cannot add more data, so we cannot yield,
2402 * we return the amount of copyied data.
2403 */
2404 return 1;
2405 }
2406 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002407 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002408 return 1;
2409}
2410
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002411/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002412 * of the writed string, or -1 if the channel is closed or if the
2413 * buffer size is too little for the data.
2414 */
2415__LJMP static int hlua_channel_append(lua_State *L)
2416{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002417 size_t len;
2418
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002419 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002420 MAY_LJMP(hlua_checkchannel(L, 1));
2421 MAY_LJMP(luaL_checklstring(L, 2, &len));
2422 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002423 lua_pushinteger(L, 0);
2424
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002425 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002426}
2427
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002428/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002429 * his process by cleaning the buffer. The result is a replacement
2430 * of the current data. It returns the length of the writed string,
2431 * or -1 if the channel is closed or if the buffer size is too
2432 * little for the data.
2433 */
2434__LJMP static int hlua_channel_set(lua_State *L)
2435{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002436 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002437
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002438 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002439 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002440 lua_pushinteger(L, 0);
2441
Willy Tarreau47860ed2015-03-10 14:07:50 +01002442 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002443
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002444 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002445}
2446
2447/* Append data in the output side of the buffer. This data is immediatly
2448 * sent. The fcuntion returns the ammount of data writed. If the buffer
2449 * cannot contains the data, the function yield. The function returns -1
2450 * if the channel is closed.
2451 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002452__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002453{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002454 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002455 size_t len;
2456 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2457 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2458 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002459 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002460
Willy Tarreau47860ed2015-03-10 14:07:50 +01002461 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002462 lua_pushinteger(L, -1);
2463 return 1;
2464 }
2465
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002466 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2467 * the request buffer if its not required.
2468 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002469 if (chn->buf->size == 0) {
2470 if (!session_alloc_recv_buffer(chn)) {
2471 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002472 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002473 }
2474 }
2475
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002476 /* the writed data will be immediatly sent, so we can check
2477 * the avalaible space without taking in account the reserve.
2478 * The reserve is guaranted for the processing of incoming
2479 * data, because the buffer will be flushed.
2480 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002481 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002482
2483 /* If there are no space avalaible, and the output buffer is empty.
2484 * in this case, we cannot add more data, so we cannot yield,
2485 * we return the amount of copyied data.
2486 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002487 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002488 return 1;
2489
2490 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002491 if (max > len - l)
2492 max = len - l;
2493
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002494 /* The buffer avalaible size may be not contiguous. This test
2495 * detects a non contiguous buffer and realign it.
2496 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002497 if (bi_space_for_replace(chn->buf) < max)
2498 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002499
2500 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002501 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002502
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002503 /* buffer replace considers that the input part is filled.
2504 * so, I must forward these new data in the output part.
2505 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002506 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002507
2508 l += max;
2509 lua_pop(L, 1);
2510 lua_pushinteger(L, l);
2511
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002512 /* If there are no space avalaible, and the output buffer is empty.
2513 * in this case, we cannot add more data, so we cannot yield,
2514 * we return the amount of copyied data.
2515 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002516 max = chn->buf->size - buffer_len(chn->buf);
2517 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002518 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002519
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002520 if (l < len) {
2521 /* If we are waiting for space in the response buffer, we
2522 * must set the flag WAKERESWR. This flag required the task
2523 * wake up if any activity is detected on the response buffer.
2524 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002525 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002526 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002527 else
2528 HLUA_SET_WAKEREQWR(hlua);
2529 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002530 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002531
2532 return 1;
2533}
2534
2535/* Just a wraper of "_hlua_channel_send". This wrapper permits
2536 * yield the LUA process, and resume it without checking the
2537 * input arguments.
2538 */
2539__LJMP static int hlua_channel_send(lua_State *L)
2540{
2541 MAY_LJMP(check_args(L, 2, "send"));
2542 lua_pushinteger(L, 0);
2543
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002544 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002545}
2546
2547/* This function forward and amount of butes. The data pass from
2548 * the input side of the buffer to the output side, and can be
2549 * forwarded. This function never fails.
2550 *
2551 * The Lua function takes an amount of bytes to be forwarded in
2552 * imput. It returns the number of bytes forwarded.
2553 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002554__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002555{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002556 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002557 int len;
2558 int l;
2559 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002560 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002561
2562 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2563 len = MAY_LJMP(luaL_checkinteger(L, 2));
2564 l = MAY_LJMP(luaL_checkinteger(L, -1));
2565
2566 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002567 if (max > chn->buf->i)
2568 max = chn->buf->i;
2569 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002570 l += max;
2571
2572 lua_pop(L, 1);
2573 lua_pushinteger(L, l);
2574
2575 /* Check if it miss bytes to forward. */
2576 if (l < len) {
2577 /* The the input channel or the output channel are closed, we
2578 * must return the amount of data forwarded.
2579 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002580 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002581 return 1;
2582
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002583 /* If we are waiting for space data in the response buffer, we
2584 * must set the flag WAKERESWR. This flag required the task
2585 * wake up if any activity is detected on the response buffer.
2586 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002587 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002588 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002589 else
2590 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002591
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002592 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002593 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002594 }
2595
2596 return 1;
2597}
2598
2599/* Just check the input and prepare the stack for the previous
2600 * function "hlua_channel_forward_yield"
2601 */
2602__LJMP static int hlua_channel_forward(lua_State *L)
2603{
2604 MAY_LJMP(check_args(L, 2, "forward"));
2605 MAY_LJMP(hlua_checkchannel(L, 1));
2606 MAY_LJMP(luaL_checkinteger(L, 2));
2607
2608 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002609 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002610}
2611
2612/* Just returns the number of bytes available in the input
2613 * side of the buffer. This function never fails.
2614 */
2615__LJMP static int hlua_channel_get_in_len(lua_State *L)
2616{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002617 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002618
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002619 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002620 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002621 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002622 return 1;
2623}
2624
2625/* Just returns the number of bytes available in the output
2626 * side of the buffer. This function never fails.
2627 */
2628__LJMP static int hlua_channel_get_out_len(lua_State *L)
2629{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002630 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002631
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002632 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002633 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002634 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002635 return 1;
2636}
2637
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002638/*
2639 *
2640 *
2641 * Class Fetches
2642 *
2643 *
2644 */
2645
2646/* Returns a struct hlua_session if the stack entry "ud" is
2647 * a class session, otherwise it throws an error.
2648 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002649__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002650{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002651 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002652}
2653
2654/* This function creates and push in the stack a fetch object according
2655 * with a current TXN.
2656 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002657static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002658{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002659 struct hlua_smp *hs;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002660
2661 /* Check stack size. */
2662 if (!lua_checkstack(L, 3))
2663 return 0;
2664
2665 /* Create the object: obj[0] = userdata.
2666 * Note that the base of the Fetches object is the
2667 * transaction object.
2668 */
2669 lua_newtable(L);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002670 hs = lua_newuserdata(L, sizeof(struct hlua_smp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002671 lua_rawseti(L, -2, 0);
2672
2673 hs->s = txn->s;
2674 hs->p = txn->p;
2675 hs->l7 = txn->l7;
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002676 hs->stringsafe = stringsafe;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002677
2678 /* Pop a class sesison metatable and affect it to the userdata. */
2679 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2680 lua_setmetatable(L, -2);
2681
2682 return 1;
2683}
2684
2685/* This function is an LUA binding. It is called with each sample-fetch.
2686 * It uses closure argument to store the associated sample-fetch. It
2687 * returns only one argument or throws an error. An error is thrown
2688 * only if an error is encountered during the argument parsing. If
2689 * the "sample-fetch" function fails, nil is returned.
2690 */
2691__LJMP static int hlua_run_sample_fetch(lua_State *L)
2692{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002693 struct hlua_smp *s;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002694 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002695 struct arg args[ARGM_NBARGS + 1];
2696 int i;
2697 struct sample smp;
2698
2699 /* Get closure arguments. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002700 f = (struct sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002701
2702 /* Get traditionnal arguments. */
2703 s = MAY_LJMP(hlua_checkfetches(L, 1));
2704
2705 /* Get extra arguments. */
2706 for (i = 0; i < lua_gettop(L) - 1; i++) {
2707 if (i >= ARGM_NBARGS)
2708 break;
2709 hlua_lua2arg(L, i + 2, &args[i]);
2710 }
2711 args[i].type = ARGT_STOP;
2712
2713 /* Check arguments. */
Thierry FOURNIER53dd3cf2015-03-12 18:27:10 +01002714 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, s->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002715
2716 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002717 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002718 lua_pushfstring(L, "error in arguments");
2719 WILL_LJMP(lua_error(L));
2720 }
2721
2722 /* Initialise the sample. */
2723 memset(&smp, 0, sizeof(smp));
2724
2725 /* Run the sample fetch process. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002726 if (!f->process(s->p, s->s, s->l7, 0, args, &smp, f->kw, f->private)) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002727 if (s->stringsafe)
2728 lua_pushstring(L, "");
2729 else
2730 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002731 return 1;
2732 }
2733
2734 /* Convert the returned sample in lua value. */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002735 if (s->stringsafe)
2736 hlua_smp2lua_str(L, &smp);
2737 else
2738 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002739 return 1;
2740}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002741
2742/*
2743 *
2744 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002745 * Class Converters
2746 *
2747 *
2748 */
2749
2750/* Returns a struct hlua_session if the stack entry "ud" is
2751 * a class session, otherwise it throws an error.
2752 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002753__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002754{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002755 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002756}
2757
2758/* This function creates and push in the stack a Converters object
2759 * according with a current TXN.
2760 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002761static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002762{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002763 struct hlua_smp *hs;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002764
2765 /* Check stack size. */
2766 if (!lua_checkstack(L, 3))
2767 return 0;
2768
2769 /* Create the object: obj[0] = userdata.
2770 * Note that the base of the Converters object is the
2771 * same than the TXN object.
2772 */
2773 lua_newtable(L);
2774 hs = lua_newuserdata(L, sizeof(struct hlua_txn));
2775 lua_rawseti(L, -2, 0);
2776
2777 hs->s = txn->s;
2778 hs->p = txn->p;
2779 hs->l7 = txn->l7;
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002780 hs->stringsafe = stringsafe;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002781
2782 /* Pop a class session metatable and affect it to the table. */
2783 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
2784 lua_setmetatable(L, -2);
2785
2786 return 1;
2787}
2788
2789/* This function is an LUA binding. It is called with each converter.
2790 * It uses closure argument to store the associated converter. It
2791 * returns only one argument or throws an error. An error is thrown
2792 * only if an error is encountered during the argument parsing. If
2793 * the converter function function fails, nil is returned.
2794 */
2795__LJMP static int hlua_run_sample_conv(lua_State *L)
2796{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002797 struct hlua_smp *sc;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002798 struct sample_conv *conv;
2799 struct arg args[ARGM_NBARGS + 1];
2800 int i;
2801 struct sample smp;
2802
2803 /* Get closure arguments. */
2804 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
2805
2806 /* Get traditionnal arguments. */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002807 sc = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002808
2809 /* Get extra arguments. */
2810 for (i = 0; i < lua_gettop(L) - 2; i++) {
2811 if (i >= ARGM_NBARGS)
2812 break;
2813 hlua_lua2arg(L, i + 3, &args[i]);
2814 }
2815 args[i].type = ARGT_STOP;
2816
2817 /* Check arguments. */
Thierry FOURNIER53dd3cf2015-03-12 18:27:10 +01002818 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, sc->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002819
2820 /* Run the special args checker. */
2821 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
2822 hlua_pusherror(L, "error in arguments");
2823 WILL_LJMP(lua_error(L));
2824 }
2825
2826 /* Initialise the sample. */
2827 if (!hlua_lua2smp(L, 2, &smp)) {
2828 hlua_pusherror(L, "error in the input argument");
2829 WILL_LJMP(lua_error(L));
2830 }
2831
2832 /* Apply expected cast. */
2833 if (!sample_casts[smp.type][conv->in_type]) {
2834 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
2835 smp_to_type[smp.type], smp_to_type[conv->in_type]);
2836 WILL_LJMP(lua_error(L));
2837 }
2838 if (sample_casts[smp.type][conv->in_type] != c_none &&
2839 !sample_casts[smp.type][conv->in_type](&smp)) {
2840 hlua_pusherror(L, "error during the input argument casting");
2841 WILL_LJMP(lua_error(L));
2842 }
2843
2844 /* Run the sample conversion process. */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002845 if (!conv->process(sc->s, args, &smp, conv->private)) {
2846 if (sc->stringsafe)
2847 lua_pushstring(L, "");
2848 else
2849 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002850 return 1;
2851 }
2852
2853 /* Convert the returned sample in lua value. */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002854 if (sc->stringsafe)
2855 hlua_smp2lua_str(L, &smp);
2856 else
2857 hlua_smp2lua(L, &smp);
2858 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002859}
2860
2861/*
2862 *
2863 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002864 * Class TXN
2865 *
2866 *
2867 */
2868
2869/* Returns a struct hlua_session if the stack entry "ud" is
2870 * a class session, otherwise it throws an error.
2871 */
2872__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
2873{
2874 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
2875}
2876
Willy Tarreau59551662015-03-10 14:23:13 +01002877__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002878{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002879 struct hlua *hlua;
2880
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002881 MAY_LJMP(check_args(L, 2, "set_priv"));
2882
2883 /* It is useles to retrieve the session, but this function
2884 * runs only in a session context.
2885 */
2886 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002887 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002888
2889 /* Remove previous value. */
2890 if (hlua->Mref != -1)
2891 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
2892
2893 /* Get and store new value. */
2894 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
2895 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
2896
2897 return 0;
2898}
2899
Willy Tarreau59551662015-03-10 14:23:13 +01002900__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002901{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002902 struct hlua *hlua;
2903
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002904 MAY_LJMP(check_args(L, 1, "get_priv"));
2905
2906 /* It is useles to retrieve the session, but this function
2907 * runs only in a session context.
2908 */
2909 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002910 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002911
2912 /* Push configuration index in the stack. */
2913 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
2914
2915 return 1;
2916}
2917
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002918/* Create stack entry containing a class TXN. This function
2919 * return 0 if the stack does not contains free slots,
2920 * otherwise it returns 1.
2921 */
2922static int hlua_txn_new(lua_State *L, struct session *s, struct proxy *p, void *l7)
2923{
2924 struct hlua_txn *hs;
2925
2926 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002927 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002928 return 0;
2929
2930 /* NOTE: The allocation never fails. The failure
2931 * throw an error, and the function never returns.
2932 * if the throw is not avalaible, the process is aborted.
2933 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002934 /* Create the object: obj[0] = userdata. */
2935 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002936 hs = lua_newuserdata(L, sizeof(struct hlua_txn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002937 lua_rawseti(L, -2, 0);
2938
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002939 hs->s = s;
2940 hs->p = p;
2941 hs->l7 = l7;
2942
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002943 /* Create the "f" field that contains a list of fetches. */
2944 lua_pushstring(L, "f");
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002945 if (!hlua_fetches_new(L, hs, 0))
2946 return 0;
2947 lua_settable(L, -3);
2948
2949 /* Create the "sf" field that contains a list of stringsafe fetches. */
2950 lua_pushstring(L, "sf");
2951 if (!hlua_fetches_new(L, hs, 1))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002952 return 0;
2953 lua_settable(L, -3);
2954
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002955 /* Create the "c" field that contains a list of converters. */
2956 lua_pushstring(L, "c");
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002957 if (!hlua_converters_new(L, hs, 0))
2958 return 0;
2959 lua_settable(L, -3);
2960
2961 /* Create the "sc" field that contains a list of stringsafe converters. */
2962 lua_pushstring(L, "sc");
2963 if (!hlua_converters_new(L, hs, 1))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002964 return 0;
2965 lua_settable(L, -3);
2966
Thierry FOURNIER397826a2015-03-11 19:39:09 +01002967 /* Create the "req" field that contains the request channel object. */
2968 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01002969 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01002970 return 0;
2971 lua_settable(L, -3);
2972
2973 /* Create the "res" field that contains the response channel object. */
2974 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01002975 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01002976 return 0;
2977 lua_settable(L, -3);
2978
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002979 /* Pop a class sesison metatable and affect it to the userdata. */
2980 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
2981 lua_setmetatable(L, -2);
2982
2983 return 1;
2984}
2985
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002986/* This function is an Lua binding that send pending data
2987 * to the client, and close the stream interface.
2988 */
2989__LJMP static int hlua_txn_close(lua_State *L)
2990{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002991 struct hlua_txn *s;
Willy Tarreau81389672015-03-10 12:03:52 +01002992 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002993
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002994 MAY_LJMP(check_args(L, 1, "close"));
2995 s = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002996
Willy Tarreau94aa6172015-03-13 14:19:06 +01002997 ic = &s->s->req;
2998 oc = &s->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01002999
3000 channel_abort(ic);
3001 channel_auto_close(ic);
3002 channel_erase(ic);
3003 channel_auto_read(oc);
3004 channel_auto_close(oc);
3005 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003006
3007 return 0;
3008}
3009
Thierry FOURNIER9a819e72015-02-16 20:22:55 +01003010/* This function is an LUA binding. It creates ans returns
3011 * an array of HTTP headers. This function does not fails.
3012 */
Willy Tarreau59551662015-03-10 14:23:13 +01003013static int hlua_session_get_headers(lua_State *L)
Thierry FOURNIER9a819e72015-02-16 20:22:55 +01003014{
3015 struct hlua_txn *s = MAY_LJMP(hlua_checktxn(L, 1));
3016 struct session *sess = s->s;
3017 const char *cur_ptr, *cur_next, *p;
3018 int old_idx, cur_idx;
3019 struct hdr_idx_elem *cur_hdr;
3020 const char *hn, *hv;
3021 int hnl, hvl;
3022
3023 /* Create the table. */
3024 lua_newtable(L);
3025
3026 /* Build array of headers. */
3027 old_idx = 0;
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01003028 cur_next = sess->req.buf->p + hdr_idx_first_pos(&sess->txn.hdr_idx);
Thierry FOURNIER9a819e72015-02-16 20:22:55 +01003029
3030 while (1) {
3031 cur_idx = sess->txn.hdr_idx.v[old_idx].next;
3032 if (!cur_idx)
3033 break;
3034 old_idx = cur_idx;
3035
3036 cur_hdr = &sess->txn.hdr_idx.v[cur_idx];
3037 cur_ptr = cur_next;
3038 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
3039
3040 /* Now we have one full header at cur_ptr of len cur_hdr->len,
3041 * and the next header starts at cur_next. We'll check
3042 * this header in the list as well as against the default
3043 * rule.
3044 */
3045
3046 /* look for ': *'. */
3047 hn = cur_ptr;
3048 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
3049 if (p >= cur_ptr+cur_hdr->len)
3050 continue;
3051 hnl = p - hn;
3052 p++;
3053 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
3054 p++;
3055 if (p >= cur_ptr+cur_hdr->len)
3056 continue;
3057 hv = p;
3058 hvl = cur_ptr+cur_hdr->len-p;
3059
3060 /* Push values in the table. */
3061 lua_pushlstring(L, hn, hnl);
3062 lua_pushlstring(L, hv, hvl);
3063 lua_settable(L, -3);
3064 }
3065
3066 return 1;
3067}
3068
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003069__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003070{
3071 int wakeup_ms = lua_tointeger(L, -1);
3072 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003073 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003074 return 0;
3075}
3076
3077__LJMP static int hlua_sleep(lua_State *L)
3078{
3079 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003080 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003081
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003082 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003083
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003084 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003085 wakeup_ms = tick_add(now_ms, delay);
3086 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003087
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003088 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3089 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003090}
3091
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003092__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003093{
3094 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003095 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003096
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003097 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003098
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003099 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003100 wakeup_ms = tick_add(now_ms, delay);
3101 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003102
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003103 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3104 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003105}
3106
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003107/* This functionis an LUA binding. it permits to give back
3108 * the hand at the HAProxy scheduler. It is used when the
3109 * LUA processing consumes a lot of time.
3110 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003111__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003112{
3113 return 0;
3114}
3115
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003116__LJMP static int hlua_yield(lua_State *L)
3117{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003118 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
3119 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003120}
3121
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003122/* This function change the nice of the currently executed
3123 * task. It is used set low or high priority at the current
3124 * task.
3125 */
Willy Tarreau59551662015-03-10 14:23:13 +01003126__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003127{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003128 struct hlua *hlua;
3129 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003130
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003131 MAY_LJMP(check_args(L, 1, "set_nice"));
3132 hlua = hlua_gethlua(L);
3133 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003134
3135 /* If he task is not set, I'm in a start mode. */
3136 if (!hlua || !hlua->task)
3137 return 0;
3138
3139 if (nice < -1024)
3140 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003141 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003142 nice = 1024;
3143
3144 hlua->task->nice = nice;
3145 return 0;
3146}
3147
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003148/* This function is used as a calback of a task. It is called by the
3149 * HAProxy task subsystem when the task is awaked. The LUA runtime can
3150 * return an E_AGAIN signal, the emmiter of this signal must set a
3151 * signal to wake the task.
3152 */
3153static struct task *hlua_process_task(struct task *task)
3154{
3155 struct hlua *hlua = task->context;
3156 enum hlua_exec status;
3157
3158 /* We need to remove the task from the wait queue before executing
3159 * the Lua code because we don't know if it needs to wait for
3160 * another timer or not in the case of E_AGAIN.
3161 */
3162 task_delete(task);
3163
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003164 /* If it is the first call to the task, we must initialize the
3165 * execution timeouts.
3166 */
3167 if (!HLUA_IS_RUNNING(hlua))
3168 hlua->expire = tick_add(now_ms, hlua_timeout_task);
3169
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003170 /* Execute the Lua code. */
3171 status = hlua_ctx_resume(hlua, 1);
3172
3173 switch (status) {
3174 /* finished or yield */
3175 case HLUA_E_OK:
3176 hlua_ctx_destroy(hlua);
3177 task_delete(task);
3178 task_free(task);
3179 break;
3180
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003181 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
3182 if (hlua->wake_time != TICK_ETERNITY)
3183 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003184 break;
3185
3186 /* finished with error. */
3187 case HLUA_E_ERRMSG:
3188 send_log(NULL, LOG_ERR, "Lua task: %s.", lua_tostring(hlua->T, -1));
3189 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3190 Alert("Lua task: %s.\n", lua_tostring(hlua->T, -1));
3191 hlua_ctx_destroy(hlua);
3192 task_delete(task);
3193 task_free(task);
3194 break;
3195
3196 case HLUA_E_ERR:
3197 default:
3198 send_log(NULL, LOG_ERR, "Lua task: unknown error.");
3199 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3200 Alert("Lua task: unknown error.\n");
3201 hlua_ctx_destroy(hlua);
3202 task_delete(task);
3203 task_free(task);
3204 break;
3205 }
3206 return NULL;
3207}
3208
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003209/* This function is an LUA binding that register LUA function to be
3210 * executed after the HAProxy configuration parsing and before the
3211 * HAProxy scheduler starts. This function expect only one LUA
3212 * argument that is a function. This function returns nothing, but
3213 * throws if an error is encountered.
3214 */
3215__LJMP static int hlua_register_init(lua_State *L)
3216{
3217 struct hlua_init_function *init;
3218 int ref;
3219
3220 MAY_LJMP(check_args(L, 1, "register_init"));
3221
3222 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3223
3224 init = malloc(sizeof(*init));
3225 if (!init)
3226 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3227
3228 init->function_ref = ref;
3229 LIST_ADDQ(&hlua_init_functions, &init->l);
3230 return 0;
3231}
3232
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003233/* This functio is an LUA binding. It permits to register a task
3234 * executed in parallel of the main HAroxy activity. The task is
3235 * created and it is set in the HAProxy scheduler. It can be called
3236 * from the "init" section, "post init" or during the runtime.
3237 *
3238 * Lua prototype:
3239 *
3240 * <none> core.register_task(<function>)
3241 */
3242static int hlua_register_task(lua_State *L)
3243{
3244 struct hlua *hlua;
3245 struct task *task;
3246 int ref;
3247
3248 MAY_LJMP(check_args(L, 1, "register_task"));
3249
3250 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3251
3252 hlua = malloc(sizeof(*hlua));
3253 if (!hlua)
3254 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3255
3256 task = task_new();
3257 task->context = hlua;
3258 task->process = hlua_process_task;
3259
3260 if (!hlua_ctx_init(hlua, task))
3261 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3262
3263 /* Restore the function in the stack. */
3264 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
3265 hlua->nargs = 0;
3266
3267 /* Schedule task. */
3268 task_schedule(task, now_ms);
3269
3270 return 0;
3271}
3272
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003273/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
3274 * doesn't allow "yield" functions because the HAProxy engine cannot
3275 * resume converters.
3276 */
3277static int hlua_sample_conv_wrapper(struct session *session, const struct arg *arg_p,
3278 struct sample *smp, void *private)
3279{
3280 struct hlua_function *fcn = (struct hlua_function *)private;
3281
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003282 /* In the execution wrappers linked with a session, the
3283 * Lua context can be not initialized. This behavior
3284 * permits to save performances because a systematic
3285 * Lua initialization cause 5% performances loss.
3286 */
3287 if (!session->hlua.T && !hlua_ctx_init(&session->hlua, session->task)) {
3288 send_log(session->be, LOG_ERR, "Lua converter '%s': can't initialize Lua context.", fcn->name);
3289 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3290 Alert("Lua converter '%s': can't initialize Lua context.\n", fcn->name);
3291 return 0;
3292 }
3293
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003294 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003295 if (!HLUA_IS_RUNNING(&session->hlua)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003296 /* Check stack available size. */
3297 if (!lua_checkstack(session->hlua.T, 1)) {
3298 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
3299 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3300 Alert("Lua converter '%s': full stack.\n", fcn->name);
3301 return 0;
3302 }
3303
3304 /* Restore the function in the stack. */
3305 lua_rawgeti(session->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
3306
3307 /* convert input sample and pust-it in the stack. */
3308 if (!lua_checkstack(session->hlua.T, 1)) {
3309 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
3310 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3311 Alert("Lua converter '%s': full stack.\n", fcn->name);
3312 return 0;
3313 }
3314 hlua_smp2lua(session->hlua.T, smp);
3315 session->hlua.nargs = 2;
3316
3317 /* push keywords in the stack. */
3318 if (arg_p) {
3319 for (; arg_p->type != ARGT_STOP; arg_p++) {
3320 if (!lua_checkstack(session->hlua.T, 1)) {
3321 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
3322 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3323 Alert("Lua converter '%s': full stack.\n", fcn->name);
3324 return 0;
3325 }
3326 hlua_arg2lua(session->hlua.T, arg_p);
3327 session->hlua.nargs++;
3328 }
3329 }
3330
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003331 /* We must initialize the execution timeouts. */
3332 session->hlua.expire = tick_add(now_ms, hlua_timeout_session);
3333
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003334 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003335 HLUA_SET_RUN(&session->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003336 }
3337
3338 /* Execute the function. */
3339 switch (hlua_ctx_resume(&session->hlua, 0)) {
3340 /* finished. */
3341 case HLUA_E_OK:
3342 /* Convert the returned value in sample. */
3343 hlua_lua2smp(session->hlua.T, -1, smp);
3344 lua_pop(session->hlua.T, 1);
3345 return 1;
3346
3347 /* yield. */
3348 case HLUA_E_AGAIN:
3349 send_log(session->be, LOG_ERR, "Lua converter '%s': cannot use yielded functions.", fcn->name);
3350 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3351 Alert("Lua converter '%s': cannot use yielded functions.\n", fcn->name);
3352 return 0;
3353
3354 /* finished with error. */
3355 case HLUA_E_ERRMSG:
3356 /* Display log. */
3357 send_log(session->be, LOG_ERR, "Lua converter '%s': %s.", fcn->name, lua_tostring(session->hlua.T, -1));
3358 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3359 Alert("Lua converter '%s': %s.\n", fcn->name, lua_tostring(session->hlua.T, -1));
3360 lua_pop(session->hlua.T, 1);
3361 return 0;
3362
3363 case HLUA_E_ERR:
3364 /* Display log. */
3365 send_log(session->be, LOG_ERR, "Lua converter '%s' returns an unknown error.", fcn->name);
3366 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3367 Alert("Lua converter '%s' returns an unknown error.\n", fcn->name);
3368
3369 default:
3370 return 0;
3371 }
3372}
3373
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003374/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
3375 * doesn't allow "yield" functions because the HAProxy engine cannot
3376 * resume sample-fetches.
3377 */
3378static int hlua_sample_fetch_wrapper(struct proxy *px, struct session *s, void *l7,
3379 unsigned int opt, const struct arg *arg_p,
3380 struct sample *smp, const char *kw, void *private)
3381{
3382 struct hlua_function *fcn = (struct hlua_function *)private;
3383
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003384 /* In the execution wrappers linked with a session, the
3385 * Lua context can be not initialized. This behavior
3386 * permits to save performances because a systematic
3387 * Lua initialization cause 5% performances loss.
3388 */
3389 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
3390 send_log(s->be, LOG_ERR, "Lua sample-fetch '%s': can't initialize Lua context.", fcn->name);
3391 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3392 Alert("Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
3393 return 0;
3394 }
3395
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003396 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003397 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003398 /* Check stack available size. */
3399 if (!lua_checkstack(s->hlua.T, 2)) {
3400 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3401 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3402 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3403 return 0;
3404 }
3405
3406 /* Restore the function in the stack. */
3407 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
3408
3409 /* push arguments in the stack. */
3410 if (!hlua_txn_new(s->hlua.T, s, px, l7)) {
3411 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3412 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3413 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3414 return 0;
3415 }
3416 s->hlua.nargs = 1;
3417
3418 /* push keywords in the stack. */
3419 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
3420 /* Check stack available size. */
3421 if (!lua_checkstack(s->hlua.T, 1)) {
3422 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3423 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3424 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3425 return 0;
3426 }
3427 if (!lua_checkstack(s->hlua.T, 1)) {
3428 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3429 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3430 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3431 return 0;
3432 }
3433 hlua_arg2lua(s->hlua.T, arg_p);
3434 s->hlua.nargs++;
3435 }
3436
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003437 /* We must initialize the execution timeouts. */
3438 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
3439
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003440 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003441 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003442 }
3443
3444 /* Execute the function. */
3445 switch (hlua_ctx_resume(&s->hlua, 0)) {
3446 /* finished. */
3447 case HLUA_E_OK:
3448 /* Convert the returned value in sample. */
3449 hlua_lua2smp(s->hlua.T, -1, smp);
3450 lua_pop(s->hlua.T, 1);
3451
3452 /* Set the end of execution flag. */
3453 smp->flags &= ~SMP_F_MAY_CHANGE;
3454 return 1;
3455
3456 /* yield. */
3457 case HLUA_E_AGAIN:
3458 send_log(px, LOG_ERR, "Lua sample-fetch '%s': cannot use yielded functions.", fcn->name);
3459 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3460 Alert("Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
3461 return 0;
3462
3463 /* finished with error. */
3464 case HLUA_E_ERRMSG:
3465 /* Display log. */
3466 send_log(px, LOG_ERR, "Lua sample-fetch '%s': %s.", fcn->name, lua_tostring(s->hlua.T, -1));
3467 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3468 Alert("Lua sample-fetch '%s': %s.\n", fcn->name, lua_tostring(s->hlua.T, -1));
3469 lua_pop(s->hlua.T, 1);
3470 return 0;
3471
3472 case HLUA_E_ERR:
3473 /* Display log. */
3474 send_log(px, LOG_ERR, "Lua sample-fetch '%s' returns an unknown error.", fcn->name);
3475 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3476 Alert("Lua sample-fetch '%s': returns an unknown error.\n", fcn->name);
3477
3478 default:
3479 return 0;
3480 }
3481}
3482
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003483/* This function is an LUA binding used for registering
3484 * "sample-conv" functions. It expects a converter name used
3485 * in the haproxy configuration file, and an LUA function.
3486 */
3487__LJMP static int hlua_register_converters(lua_State *L)
3488{
3489 struct sample_conv_kw_list *sck;
3490 const char *name;
3491 int ref;
3492 int len;
3493 struct hlua_function *fcn;
3494
3495 MAY_LJMP(check_args(L, 2, "register_converters"));
3496
3497 /* First argument : converter name. */
3498 name = MAY_LJMP(luaL_checkstring(L, 1));
3499
3500 /* Second argument : lua function. */
3501 ref = MAY_LJMP(hlua_checkfunction(L, 2));
3502
3503 /* Allocate and fill the sample fetch keyword struct. */
3504 sck = malloc(sizeof(struct sample_conv_kw_list) +
3505 sizeof(struct sample_conv) * 2);
3506 if (!sck)
3507 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3508 fcn = malloc(sizeof(*fcn));
3509 if (!fcn)
3510 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3511
3512 /* Fill fcn. */
3513 fcn->name = strdup(name);
3514 if (!fcn->name)
3515 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3516 fcn->function_ref = ref;
3517
3518 /* List head */
3519 sck->list.n = sck->list.p = NULL;
3520
3521 /* converter keyword. */
3522 len = strlen("lua.") + strlen(name) + 1;
3523 sck->kw[0].kw = malloc(len);
3524 if (!sck->kw[0].kw)
3525 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3526
3527 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
3528 sck->kw[0].process = hlua_sample_conv_wrapper;
3529 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
3530 sck->kw[0].val_args = NULL;
3531 sck->kw[0].in_type = SMP_T_STR;
3532 sck->kw[0].out_type = SMP_T_STR;
3533 sck->kw[0].private = fcn;
3534
3535 /* End of array. */
3536 memset(&sck->kw[1], 0, sizeof(struct sample_conv));
3537
3538 /* Register this new converter */
3539 sample_register_convs(sck);
3540
3541 return 0;
3542}
3543
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003544/* This fucntion is an LUA binding used for registering
3545 * "sample-fetch" functions. It expects a converter name used
3546 * in the haproxy configuration file, and an LUA function.
3547 */
3548__LJMP static int hlua_register_fetches(lua_State *L)
3549{
3550 const char *name;
3551 int ref;
3552 int len;
3553 struct sample_fetch_kw_list *sfk;
3554 struct hlua_function *fcn;
3555
3556 MAY_LJMP(check_args(L, 2, "register_fetches"));
3557
3558 /* First argument : sample-fetch name. */
3559 name = MAY_LJMP(luaL_checkstring(L, 1));
3560
3561 /* Second argument : lua function. */
3562 ref = MAY_LJMP(hlua_checkfunction(L, 2));
3563
3564 /* Allocate and fill the sample fetch keyword struct. */
3565 sfk = malloc(sizeof(struct sample_fetch_kw_list) +
3566 sizeof(struct sample_fetch) * 2);
3567 if (!sfk)
3568 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3569 fcn = malloc(sizeof(*fcn));
3570 if (!fcn)
3571 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3572
3573 /* Fill fcn. */
3574 fcn->name = strdup(name);
3575 if (!fcn->name)
3576 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3577 fcn->function_ref = ref;
3578
3579 /* List head */
3580 sfk->list.n = sfk->list.p = NULL;
3581
3582 /* sample-fetch keyword. */
3583 len = strlen("lua.") + strlen(name) + 1;
3584 sfk->kw[0].kw = malloc(len);
3585 if (!sfk->kw[0].kw)
3586 return luaL_error(L, "lua out of memory error.");
3587
3588 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
3589 sfk->kw[0].process = hlua_sample_fetch_wrapper;
3590 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
3591 sfk->kw[0].val_args = NULL;
3592 sfk->kw[0].out_type = SMP_T_STR;
3593 sfk->kw[0].use = SMP_USE_HTTP_ANY;
3594 sfk->kw[0].val = 0;
3595 sfk->kw[0].private = fcn;
3596
3597 /* End of array. */
3598 memset(&sfk->kw[1], 0, sizeof(struct sample_fetch));
3599
3600 /* Register this new fetch. */
3601 sample_register_fetches(sfk);
3602
3603 return 0;
3604}
3605
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003606/* global {tcp|http}-request parser. Return 1 in succes case, else return 0. */
3607static int hlua_parse_rule(const char **args, int *cur_arg, struct proxy *px,
3608 struct hlua_rule **rule_p, char **err)
3609{
3610 struct hlua_rule *rule;
3611
3612 /* Memory for the rule. */
3613 rule = malloc(sizeof(*rule));
3614 if (!rule) {
3615 memprintf(err, "out of memory error");
3616 return 0;
3617 }
3618 *rule_p = rule;
3619
3620 /* The requiered arg is a function name. */
3621 if (!args[*cur_arg]) {
3622 memprintf(err, "expect Lua function name");
3623 return 0;
3624 }
3625
3626 /* Lookup for the symbol, and check if it is a function. */
3627 lua_getglobal(gL.T, args[*cur_arg]);
3628 if (lua_isnil(gL.T, -1)) {
3629 lua_pop(gL.T, 1);
3630 memprintf(err, "Lua function '%s' not found", args[*cur_arg]);
3631 return 0;
3632 }
3633 if (!lua_isfunction(gL.T, -1)) {
3634 lua_pop(gL.T, 1);
3635 memprintf(err, "'%s' is not a function", args[*cur_arg]);
3636 return 0;
3637 }
3638
3639 /* Reference the Lua function and store the reference. */
3640 rule->fcn.function_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
3641 rule->fcn.name = strdup(args[*cur_arg]);
3642 if (!rule->fcn.name) {
3643 memprintf(err, "out of memory error.");
3644 return 0;
3645 }
3646 (*cur_arg)++;
3647
3648 /* TODO: later accept arguments. */
3649 rule->args = NULL;
3650
3651 return 1;
3652}
3653
3654/* This function is a wrapper to execute each LUA function declared
3655 * as an action wrapper during the initialisation period. This function
3656 * return 1 if the processing is finished (with oe without error) and
3657 * return 0 if the function must be called again because the LUA
3658 * returns a yield.
3659 */
3660static int hlua_request_act_wrapper(struct hlua_rule *rule, struct proxy *px,
3661 struct session *s, struct http_txn *http_txn,
3662 unsigned int analyzer)
3663{
3664 char **arg;
3665
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003666 /* In the execution wrappers linked with a session, the
3667 * Lua context can be not initialized. This behavior
3668 * permits to save performances because a systematic
3669 * Lua initialization cause 5% performances loss.
3670 */
3671 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
3672 send_log(px, LOG_ERR, "Lua action '%s': can't initialize Lua context.", rule->fcn.name);
3673 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3674 Alert("Lua action '%s': can't initialize Lua context.\n", rule->fcn.name);
3675 return 0;
3676 }
3677
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003678 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003679 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003680 /* Check stack available size. */
3681 if (!lua_checkstack(s->hlua.T, 1)) {
3682 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
3683 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3684 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
3685 return 0;
3686 }
3687
3688 /* Restore the function in the stack. */
3689 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->fcn.function_ref);
3690
3691 /* Create and and push object session in the stack. */
3692 if (!hlua_txn_new(s->hlua.T, s, px, http_txn)) {
3693 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
3694 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3695 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
3696 return 0;
3697 }
3698 s->hlua.nargs = 1;
3699
3700 /* push keywords in the stack. */
3701 for (arg = rule->args; arg && *arg; arg++) {
3702 if (!lua_checkstack(s->hlua.T, 1)) {
3703 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
3704 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3705 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
3706 return 0;
3707 }
3708 lua_pushstring(s->hlua.T, *arg);
3709 s->hlua.nargs++;
3710 }
3711
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003712 /* We must initialize the execution timeouts. */
3713 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
3714
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003715 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003716 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003717 }
3718
3719 /* Execute the function. */
3720 switch (hlua_ctx_resume(&s->hlua, 1)) {
3721 /* finished. */
3722 case HLUA_E_OK:
3723 return 1;
3724
3725 /* yield. */
3726 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003727 /* Set timeout in the required channel. */
3728 if (s->hlua.wake_time != TICK_ETERNITY) {
3729 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01003730 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003731 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01003732 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003733 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003734 /* Some actions can be wake up when a "write" event
3735 * is detected on a response channel. This is useful
3736 * only for actions targetted on the requests.
3737 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003738 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01003739 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01003740 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01003741 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003742 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003743 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01003744 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003745 return 0;
3746
3747 /* finished with error. */
3748 case HLUA_E_ERRMSG:
3749 /* Display log. */
3750 send_log(px, LOG_ERR, "Lua function '%s': %s.", rule->fcn.name, lua_tostring(s->hlua.T, -1));
3751 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3752 Alert("Lua function '%s': %s.\n", rule->fcn.name, lua_tostring(s->hlua.T, -1));
3753 lua_pop(s->hlua.T, 1);
3754 return 1;
3755
3756 case HLUA_E_ERR:
3757 /* Display log. */
3758 send_log(px, LOG_ERR, "Lua function '%s' return an unknown error.", rule->fcn.name);
3759 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3760 Alert("Lua function '%s' return an unknown error.\n", rule->fcn.name);
3761
3762 default:
3763 return 1;
3764 }
3765}
3766
3767/* Lua execution wrapper for "tcp-request". This function uses
3768 * "hlua_request_act_wrapper" for executing the LUA code.
3769 */
3770int hlua_tcp_req_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
3771 struct session *s)
3772{
3773 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
3774 px, s, NULL, AN_REQ_INSPECT_FE);
3775}
3776
3777/* Lua execution wrapper for "tcp-response". This function uses
3778 * "hlua_request_act_wrapper" for executing the LUA code.
3779 */
3780int hlua_tcp_res_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
3781 struct session *s)
3782{
3783 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
3784 px, s, NULL, AN_RES_INSPECT);
3785}
3786
3787/* Lua execution wrapper for http-request.
3788 * This function uses "hlua_request_act_wrapper" for executing
3789 * the LUA code.
3790 */
3791int hlua_http_req_act_wrapper(struct http_req_rule *rule, struct proxy *px,
3792 struct session *s, struct http_txn *http_txn)
3793{
3794 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
3795 s, http_txn, AN_REQ_HTTP_PROCESS_FE);
3796}
3797
3798/* Lua execution wrapper for http-response.
3799 * This function uses "hlua_request_act_wrapper" for executing
3800 * the LUA code.
3801 */
3802int hlua_http_res_act_wrapper(struct http_res_rule *rule, struct proxy *px,
3803 struct session *s, struct http_txn *http_txn)
3804{
3805 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
3806 s, http_txn, AN_RES_HTTP_PROCESS_BE);
3807}
3808
3809/* tcp-request <*> configuration wrapper. */
3810static int tcp_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3811 struct tcp_rule *rule, char **err)
3812{
3813 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003814 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003815 rule->action = TCP_ACT_CUSTOM;
3816 rule->action_ptr = hlua_tcp_req_act_wrapper;
3817 return 1;
3818}
3819
3820/* tcp-response <*> configuration wrapper. */
3821static int tcp_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3822 struct tcp_rule *rule, char **err)
3823{
3824 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003825 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003826 rule->action = TCP_ACT_CUSTOM;
3827 rule->action_ptr = hlua_tcp_res_act_wrapper;
3828 return 1;
3829}
3830
3831/* http-request <*> configuration wrapper. */
3832static int http_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3833 struct http_req_rule *rule, char **err)
3834{
3835 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
3836 return -1;
3837 rule->action = HTTP_REQ_ACT_CUSTOM_CONT;
3838 rule->action_ptr = hlua_http_req_act_wrapper;
3839 return 1;
3840}
3841
3842/* http-response <*> configuration wrapper. */
3843static int http_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3844 struct http_res_rule *rule, char **err)
3845{
3846 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
3847 return -1;
3848 rule->action = HTTP_RES_ACT_CUSTOM_CONT;
3849 rule->action_ptr = hlua_http_res_act_wrapper;
3850 return 1;
3851}
3852
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003853static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
3854 struct proxy *defpx, const char *file, int line,
3855 char **err, unsigned int *timeout)
3856{
3857 const char *error;
3858
3859 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
3860 if (error && *error != '\0') {
3861 memprintf(err, "%s: invalid timeout", args[0]);
3862 return -1;
3863 }
3864 return 0;
3865}
3866
3867static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
3868 struct proxy *defpx, const char *file, int line,
3869 char **err)
3870{
3871 return hlua_read_timeout(args, section_type, curpx, defpx,
3872 file, line, err, &hlua_timeout_session);
3873}
3874
3875static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
3876 struct proxy *defpx, const char *file, int line,
3877 char **err)
3878{
3879 return hlua_read_timeout(args, section_type, curpx, defpx,
3880 file, line, err, &hlua_timeout_task);
3881}
3882
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01003883static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
3884 struct proxy *defpx, const char *file, int line,
3885 char **err)
3886{
3887 char *error;
3888
3889 hlua_nb_instruction = strtoll(args[1], &error, 10);
3890 if (*error != '\0') {
3891 memprintf(err, "%s: invalid number", args[0]);
3892 return -1;
3893 }
3894 return 0;
3895}
3896
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01003897/* This function is called by the main configuration key "lua-load". It loads and
3898 * execute an lua file during the parsing of the HAProxy configuration file. It is
3899 * the main lua entry point.
3900 *
3901 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
3902 * occured, otherwise it returns 0.
3903 *
3904 * In some error case, LUA set an error message in top of the stack. This function
3905 * returns this error message in the HAProxy logs and pop it from the stack.
3906 */
3907static int hlua_load(char **args, int section_type, struct proxy *curpx,
3908 struct proxy *defpx, const char *file, int line,
3909 char **err)
3910{
3911 int error;
3912
3913 /* Just load and compile the file. */
3914 error = luaL_loadfile(gL.T, args[1]);
3915 if (error) {
3916 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
3917 lua_pop(gL.T, 1);
3918 return -1;
3919 }
3920
3921 /* If no syntax error where detected, execute the code. */
3922 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
3923 switch (error) {
3924 case LUA_OK:
3925 break;
3926 case LUA_ERRRUN:
3927 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
3928 lua_pop(gL.T, 1);
3929 return -1;
3930 case LUA_ERRMEM:
3931 memprintf(err, "lua out of memory error\n");
3932 return -1;
3933 case LUA_ERRERR:
3934 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
3935 lua_pop(gL.T, 1);
3936 return -1;
3937 case LUA_ERRGCMM:
3938 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
3939 lua_pop(gL.T, 1);
3940 return -1;
3941 default:
3942 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
3943 lua_pop(gL.T, 1);
3944 return -1;
3945 }
3946
3947 return 0;
3948}
3949
3950/* configuration keywords declaration */
3951static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003952 { CFG_GLOBAL, "lua-load", hlua_load },
3953 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
3954 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01003955 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01003956 { 0, NULL, NULL },
3957}};
3958
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003959static struct http_req_action_kw_list http_req_kws = {"lua", { }, {
3960 { "lua", http_req_action_register_lua },
3961 { NULL, NULL }
3962}};
3963
3964static struct http_res_action_kw_list http_res_kws = {"lua", { }, {
3965 { "lua", http_res_action_register_lua },
3966 { NULL, NULL }
3967}};
3968
3969static struct tcp_action_kw_list tcp_req_cont_kws = {"lua", { }, {
3970 { "lua", tcp_req_action_register_lua },
3971 { NULL, NULL }
3972}};
3973
3974static struct tcp_action_kw_list tcp_res_cont_kws = {"lua", { }, {
3975 { "lua", tcp_res_action_register_lua },
3976 { NULL, NULL }
3977}};
3978
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003979int hlua_post_init()
3980{
3981 struct hlua_init_function *init;
3982 const char *msg;
3983 enum hlua_exec ret;
3984
3985 list_for_each_entry(init, &hlua_init_functions, l) {
3986 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
3987 ret = hlua_ctx_resume(&gL, 0);
3988 switch (ret) {
3989 case HLUA_E_OK:
3990 lua_pop(gL.T, -1);
3991 return 1;
3992 case HLUA_E_AGAIN:
3993 Alert("lua init: yield not allowed.\n");
3994 return 0;
3995 case HLUA_E_ERRMSG:
3996 msg = lua_tostring(gL.T, -1);
3997 Alert("lua init: %s.\n", msg);
3998 return 0;
3999 case HLUA_E_ERR:
4000 default:
4001 Alert("lua init: unknown runtime error.\n");
4002 return 0;
4003 }
4004 }
4005 return 1;
4006}
4007
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01004008void hlua_init(void)
4009{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004010 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004011 int idx;
4012 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004013 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004014 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004015#ifdef USE_OPENSSL
4016 char *args[4];
4017 struct srv_kw *kw;
4018 int tmp_error;
4019 char *error;
4020#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004021
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004022 /* Initialise com signals pool session. */
4023 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
4024
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004025 /* Initialise sleep pool. */
4026 pool2_hlua_sleep = create_pool("hlua_sleep", sizeof(struct hlua_sleep), MEM_F_SHARED);
4027
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004028 /* Register configuration keywords. */
4029 cfg_register_keywords(&cfg_kws);
4030
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004031 /* Register custom HTTP rules. */
4032 http_req_keywords_register(&http_req_kws);
4033 http_res_keywords_register(&http_res_kws);
4034 tcp_req_cont_keywords_register(&tcp_req_cont_kws);
4035 tcp_res_cont_keywords_register(&tcp_res_cont_kws);
4036
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004037 /* Init main lua stack. */
4038 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004039 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004040 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004041 gL.T = luaL_newstate();
4042 hlua_sethlua(&gL);
4043 gL.Tref = LUA_REFNIL;
4044 gL.task = NULL;
4045
4046 /* Initialise lua. */
4047 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004048
4049 /*
4050 *
4051 * Create "core" object.
4052 *
4053 */
4054
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01004055 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004056 lua_newtable(gL.T);
4057
4058 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004059 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004060 hlua_class_const_int(gL.T, log_levels[i], i);
4061
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004062 /* Register special functions. */
4063 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004064 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004065 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004066 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004067 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01004068 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004069 hlua_class_function(gL.T, "sleep", hlua_sleep);
4070 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01004071 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
4072 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
4073 hlua_class_function(gL.T, "set_map", hlua_set_map);
4074 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004075 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004076
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004077 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004078
4079 /*
4080 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004081 * Register class Channel
4082 *
4083 */
4084
4085 /* Create and fill the metatable. */
4086 lua_newtable(gL.T);
4087
4088 /* Create and fille the __index entry. */
4089 lua_pushstring(gL.T, "__index");
4090 lua_newtable(gL.T);
4091
4092 /* Register . */
4093 hlua_class_function(gL.T, "get", hlua_channel_get);
4094 hlua_class_function(gL.T, "dup", hlua_channel_dup);
4095 hlua_class_function(gL.T, "getline", hlua_channel_getline);
4096 hlua_class_function(gL.T, "set", hlua_channel_set);
4097 hlua_class_function(gL.T, "append", hlua_channel_append);
4098 hlua_class_function(gL.T, "send", hlua_channel_send);
4099 hlua_class_function(gL.T, "forward", hlua_channel_forward);
4100 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
4101 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
4102
4103 lua_settable(gL.T, -3);
4104
4105 /* Register previous table in the registry with reference and named entry. */
4106 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4107 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
4108 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4109
4110 /*
4111 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004112 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004113 *
4114 */
4115
4116 /* Create and fill the metatable. */
4117 lua_newtable(gL.T);
4118
4119 /* Create and fille the __index entry. */
4120 lua_pushstring(gL.T, "__index");
4121 lua_newtable(gL.T);
4122
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004123 /* Browse existing fetches and create the associated
4124 * object method.
4125 */
4126 sf = NULL;
4127 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
4128
4129 /* Dont register the keywork if the arguments check function are
4130 * not safe during the runtime.
4131 */
4132 if ((sf->val_args != NULL) &&
4133 (sf->val_args != val_payload_lv) &&
4134 (sf->val_args != val_hdr))
4135 continue;
4136
4137 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4138 * by an underscore.
4139 */
4140 strncpy(trash.str, sf->kw, trash.size);
4141 trash.str[trash.size - 1] = '\0';
4142 for (p = trash.str; *p; p++)
4143 if (*p == '.' || *p == '-' || *p == '+')
4144 *p = '_';
4145
4146 /* Register the function. */
4147 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01004148 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004149 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
4150 lua_settable(gL.T, -3);
4151 }
4152
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004153 lua_settable(gL.T, -3);
4154
4155 /* Register previous table in the registry with reference and named entry. */
4156 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4157 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
4158 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4159
4160 /*
4161 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004162 * Register class Converters
4163 *
4164 */
4165
4166 /* Create and fill the metatable. */
4167 lua_newtable(gL.T);
4168
4169 /* Create and fill the __index entry. */
4170 lua_pushstring(gL.T, "__index");
4171 lua_newtable(gL.T);
4172
4173 /* Browse existing converters and create the associated
4174 * object method.
4175 */
4176 sc = NULL;
4177 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
4178 /* Dont register the keywork if the arguments check function are
4179 * not safe during the runtime.
4180 */
4181 if (sc->val_args != NULL)
4182 continue;
4183
4184 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4185 * by an underscore.
4186 */
4187 strncpy(trash.str, sc->kw, trash.size);
4188 trash.str[trash.size - 1] = '\0';
4189 for (p = trash.str; *p; p++)
4190 if (*p == '.' || *p == '-' || *p == '+')
4191 *p = '_';
4192
4193 /* Register the function. */
4194 lua_pushstring(gL.T, trash.str);
4195 lua_pushlightuserdata(gL.T, sc);
4196 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
4197 lua_settable(gL.T, -3);
4198 }
4199
4200 lua_settable(gL.T, -3);
4201
4202 /* Register previous table in the registry with reference and named entry. */
4203 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4204 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
4205 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4206
4207 /*
4208 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004209 * Register class TXN
4210 *
4211 */
4212
4213 /* Create and fill the metatable. */
4214 lua_newtable(gL.T);
4215
4216 /* Create and fille the __index entry. */
4217 lua_pushstring(gL.T, "__index");
4218 lua_newtable(gL.T);
4219
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004220 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01004221 hlua_class_function(gL.T, "get_headers", hlua_session_get_headers);
4222 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
4223 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004224 hlua_class_function(gL.T, "close", hlua_txn_close);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004225
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004226 lua_settable(gL.T, -3);
4227
4228 /* Register previous table in the registry with reference and named entry. */
4229 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4230 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
4231 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004232
4233 /*
4234 *
4235 * Register class Socket
4236 *
4237 */
4238
4239 /* Create and fill the metatable. */
4240 lua_newtable(gL.T);
4241
4242 /* Create and fille the __index entry. */
4243 lua_pushstring(gL.T, "__index");
4244 lua_newtable(gL.T);
4245
Baptiste Assmann84bb4932015-03-02 21:40:06 +01004246#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004247 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01004248#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004249 hlua_class_function(gL.T, "connect", hlua_socket_connect);
4250 hlua_class_function(gL.T, "send", hlua_socket_send);
4251 hlua_class_function(gL.T, "receive", hlua_socket_receive);
4252 hlua_class_function(gL.T, "close", hlua_socket_close);
4253 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
4254 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
4255 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
4256 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
4257
4258 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
4259
4260 /* Register the garbage collector entry. */
4261 lua_pushstring(gL.T, "__gc");
4262 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
4263 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
4264
4265 /* Register previous table in the registry with reference and named entry. */
4266 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4267 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4268 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
4269 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
4270
4271 /* Proxy and server configuration initialisation. */
4272 memset(&socket_proxy, 0, sizeof(socket_proxy));
4273 init_new_proxy(&socket_proxy);
4274 socket_proxy.parent = NULL;
4275 socket_proxy.last_change = now.tv_sec;
4276 socket_proxy.id = "LUA-SOCKET";
4277 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
4278 socket_proxy.maxconn = 0;
4279 socket_proxy.accept = NULL;
4280 socket_proxy.options2 |= PR_O2_INDEPSTR;
4281 socket_proxy.srv = NULL;
4282 socket_proxy.conn_retries = 0;
4283 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
4284
4285 /* Init TCP server: unchanged parameters */
4286 memset(&socket_tcp, 0, sizeof(socket_tcp));
4287 socket_tcp.next = NULL;
4288 socket_tcp.proxy = &socket_proxy;
4289 socket_tcp.obj_type = OBJ_TYPE_SERVER;
4290 LIST_INIT(&socket_tcp.actconns);
4291 LIST_INIT(&socket_tcp.pendconns);
4292 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
4293 socket_tcp.last_change = 0;
4294 socket_tcp.id = "LUA-TCP-CONN";
4295 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
4296 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
4297 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
4298
4299 /* XXX: Copy default parameter from default server,
4300 * but the default server is not initialized.
4301 */
4302 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
4303 socket_tcp.minconn = socket_proxy.defsrv.minconn;
4304 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
4305 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
4306 socket_tcp.onerror = socket_proxy.defsrv.onerror;
4307 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
4308 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
4309 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
4310 socket_tcp.uweight = socket_proxy.defsrv.iweight;
4311 socket_tcp.iweight = socket_proxy.defsrv.iweight;
4312
4313 socket_tcp.check.status = HCHK_STATUS_INI;
4314 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
4315 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
4316 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
4317 socket_tcp.check.server = &socket_tcp;
4318
4319 socket_tcp.agent.status = HCHK_STATUS_INI;
4320 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
4321 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
4322 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
4323 socket_tcp.agent.server = &socket_tcp;
4324
4325 socket_tcp.xprt = &raw_sock;
4326
4327#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004328 /* Init TCP server: unchanged parameters */
4329 memset(&socket_ssl, 0, sizeof(socket_ssl));
4330 socket_ssl.next = NULL;
4331 socket_ssl.proxy = &socket_proxy;
4332 socket_ssl.obj_type = OBJ_TYPE_SERVER;
4333 LIST_INIT(&socket_ssl.actconns);
4334 LIST_INIT(&socket_ssl.pendconns);
4335 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
4336 socket_ssl.last_change = 0;
4337 socket_ssl.id = "LUA-SSL-CONN";
4338 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
4339 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
4340 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
4341
4342 /* XXX: Copy default parameter from default server,
4343 * but the default server is not initialized.
4344 */
4345 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
4346 socket_ssl.minconn = socket_proxy.defsrv.minconn;
4347 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
4348 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
4349 socket_ssl.onerror = socket_proxy.defsrv.onerror;
4350 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
4351 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
4352 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
4353 socket_ssl.uweight = socket_proxy.defsrv.iweight;
4354 socket_ssl.iweight = socket_proxy.defsrv.iweight;
4355
4356 socket_ssl.check.status = HCHK_STATUS_INI;
4357 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
4358 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
4359 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
4360 socket_ssl.check.server = &socket_ssl;
4361
4362 socket_ssl.agent.status = HCHK_STATUS_INI;
4363 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
4364 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
4365 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
4366 socket_ssl.agent.server = &socket_ssl;
4367
4368 socket_ssl.xprt = &raw_sock;
4369
4370 args[0] = "ssl";
4371 args[1] = "verify";
4372 args[2] = "none";
4373 args[3] = NULL;
4374
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004375 for (idx = 0; idx < 3; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004376 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
4377 /*
4378 *
4379 * If the keyword is not known, we can search in the registered
4380 * server keywords. This is usefull to configure special SSL
4381 * features like client certificates and ssl_verify.
4382 *
4383 */
4384 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
4385 if (tmp_error != 0) {
4386 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
4387 abort(); /* This must be never arrives because the command line
4388 not editable by the user. */
4389 }
4390 idx += kw->skip;
4391 }
4392 }
4393
4394 /* Initialize SSL server. */
4395 if (socket_ssl.xprt == &ssl_sock) {
4396 socket_ssl.use_ssl = 1;
4397 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
4398 }
4399#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01004400}