blob: c76eb1ea72c68f84aa56671be74f05ffdf02ce82 [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
859 /* If we cannot yield, check the timeout. */
860 if (tick_is_expired(hlua->expire, now_ms)) {
861 lua_pushfstring(L, "execution timeout");
862 WILL_LJMP(lua_error(L));
863 }
864
865 /* Try to interrupt the process at the end of the current
866 * unyieldable function.
867 */
868 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100869}
870
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100871/* This function start or resumes the Lua stack execution. If the flag
872 * "yield_allowed" if no set and the LUA stack execution returns a yield
873 * The function return an error.
874 *
875 * The function can returns 4 values:
876 * - HLUA_E_OK : The execution is terminated without any errors.
877 * - HLUA_E_AGAIN : The execution must continue at the next associated
878 * task wakeup.
879 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
880 * the top of the stack.
881 * - HLUA_E_ERR : An error has occured without error message.
882 *
883 * If an error occured, the stack is renewed and it is ready to run new
884 * LUA code.
885 */
886static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
887{
888 int ret;
889 const char *msg;
890
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100891 HLUA_SET_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100892
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100893 /* If we want to resume the task, then check first the execution timeout.
894 * if it is reached, we can interrupt the Lua processing.
895 */
896 if (tick_is_expired(lua->expire, now_ms))
897 goto timeout_reached;
898
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100899resume_execution:
900
901 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
902 * instructions. it is used for preventing infinite loops.
903 */
904 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
905
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +0100906 /* Remove all flags except the running flags. */
907 lua->flags = HLUA_RUN;
908
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100909 /* Call the function. */
910 ret = lua_resume(lua->T, gL.T, lua->nargs);
911 switch (ret) {
912
913 case LUA_OK:
914 ret = HLUA_E_OK;
915 break;
916
917 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100918 /* Check if the execution timeout is expired. It it is the case, we
919 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100920 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100921 if (tick_is_expired(lua->expire, now_ms)) {
922
923timeout_reached:
924
925 lua_settop(lua->T, 0); /* Empty the stack. */
926 if (!lua_checkstack(lua->T, 1)) {
927 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100928 break;
929 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100930 lua_pushfstring(lua->T, "execution timeout");
931 ret = HLUA_E_ERRMSG;
932 break;
933 }
934 /* Process the forced yield. if the general yield is not allowed or
935 * if no task were associated this the current Lua execution
936 * coroutine, we resume the execution. Else we want to return in the
937 * scheduler and we want to be waked up again, to continue the
938 * current Lua execution. So we schedule our own task.
939 */
940 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100941 if (!yield_allowed || !lua->task)
942 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100943 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100944 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100945 if (!yield_allowed) {
946 lua_settop(lua->T, 0); /* Empty the stack. */
947 if (!lua_checkstack(lua->T, 1)) {
948 ret = HLUA_E_ERR;
949 break;
950 }
951 lua_pushfstring(lua->T, "yield not allowed");
952 ret = HLUA_E_ERRMSG;
953 break;
954 }
955 ret = HLUA_E_AGAIN;
956 break;
957
958 case LUA_ERRRUN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100959 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100960 if (!lua_checkstack(lua->T, 1)) {
961 ret = HLUA_E_ERR;
962 break;
963 }
964 msg = lua_tostring(lua->T, -1);
965 lua_settop(lua->T, 0); /* Empty the stack. */
966 lua_pop(lua->T, 1);
967 if (msg)
968 lua_pushfstring(lua->T, "runtime error: %s", msg);
969 else
970 lua_pushfstring(lua->T, "unknown runtime error");
971 ret = HLUA_E_ERRMSG;
972 break;
973
974 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100975 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100976 lua_settop(lua->T, 0); /* Empty the stack. */
977 if (!lua_checkstack(lua->T, 1)) {
978 ret = HLUA_E_ERR;
979 break;
980 }
981 lua_pushfstring(lua->T, "out of memory error");
982 ret = HLUA_E_ERRMSG;
983 break;
984
985 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100986 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100987 if (!lua_checkstack(lua->T, 1)) {
988 ret = HLUA_E_ERR;
989 break;
990 }
991 msg = lua_tostring(lua->T, -1);
992 lua_settop(lua->T, 0); /* Empty the stack. */
993 lua_pop(lua->T, 1);
994 if (msg)
995 lua_pushfstring(lua->T, "message handler error: %s", msg);
996 else
997 lua_pushfstring(lua->T, "message handler error");
998 ret = HLUA_E_ERRMSG;
999 break;
1000
1001 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001002 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001003 lua_settop(lua->T, 0); /* Empty the stack. */
1004 if (!lua_checkstack(lua->T, 1)) {
1005 ret = HLUA_E_ERR;
1006 break;
1007 }
1008 lua_pushfstring(lua->T, "unknonwn error");
1009 ret = HLUA_E_ERRMSG;
1010 break;
1011 }
1012
1013 switch (ret) {
1014 case HLUA_E_AGAIN:
1015 break;
1016
1017 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001018 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001019 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001020 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001021 break;
1022
1023 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001024 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001025 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001026 hlua_ctx_renew(lua, 0);
1027 break;
1028
1029 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001030 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001031 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001032 break;
1033 }
1034
1035 return ret;
1036}
1037
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001038/* This function is an LUA binding. It provides a function
1039 * for deleting ACL from a referenced ACL file.
1040 */
1041__LJMP static int hlua_del_acl(lua_State *L)
1042{
1043 const char *name;
1044 const char *key;
1045 struct pat_ref *ref;
1046
1047 MAY_LJMP(check_args(L, 2, "del_acl"));
1048
1049 name = MAY_LJMP(luaL_checkstring(L, 1));
1050 key = MAY_LJMP(luaL_checkstring(L, 2));
1051
1052 ref = pat_ref_lookup(name);
1053 if (!ref)
1054 WILL_LJMP(luaL_error(L, "'del_acl': unkown acl file '%s'", name));
1055
1056 pat_ref_delete(ref, key);
1057 return 0;
1058}
1059
1060/* This function is an LUA binding. It provides a function
1061 * for deleting map entry from a referenced map file.
1062 */
1063static int hlua_del_map(lua_State *L)
1064{
1065 const char *name;
1066 const char *key;
1067 struct pat_ref *ref;
1068
1069 MAY_LJMP(check_args(L, 2, "del_map"));
1070
1071 name = MAY_LJMP(luaL_checkstring(L, 1));
1072 key = MAY_LJMP(luaL_checkstring(L, 2));
1073
1074 ref = pat_ref_lookup(name);
1075 if (!ref)
1076 WILL_LJMP(luaL_error(L, "'del_map': unkown acl file '%s'", name));
1077
1078 pat_ref_delete(ref, key);
1079 return 0;
1080}
1081
1082/* This function is an LUA binding. It provides a function
1083 * for adding ACL pattern from a referenced ACL file.
1084 */
1085static int hlua_add_acl(lua_State *L)
1086{
1087 const char *name;
1088 const char *key;
1089 struct pat_ref *ref;
1090
1091 MAY_LJMP(check_args(L, 2, "add_acl"));
1092
1093 name = MAY_LJMP(luaL_checkstring(L, 1));
1094 key = MAY_LJMP(luaL_checkstring(L, 2));
1095
1096 ref = pat_ref_lookup(name);
1097 if (!ref)
1098 WILL_LJMP(luaL_error(L, "'add_acl': unkown acl file '%s'", name));
1099
1100 if (pat_ref_find_elt(ref, key) == NULL)
1101 pat_ref_add(ref, key, NULL, NULL);
1102 return 0;
1103}
1104
1105/* This function is an LUA binding. It provides a function
1106 * for setting map pattern and sample from a referenced map
1107 * file.
1108 */
1109static int hlua_set_map(lua_State *L)
1110{
1111 const char *name;
1112 const char *key;
1113 const char *value;
1114 struct pat_ref *ref;
1115
1116 MAY_LJMP(check_args(L, 3, "set_map"));
1117
1118 name = MAY_LJMP(luaL_checkstring(L, 1));
1119 key = MAY_LJMP(luaL_checkstring(L, 2));
1120 value = MAY_LJMP(luaL_checkstring(L, 3));
1121
1122 ref = pat_ref_lookup(name);
1123 if (!ref)
1124 WILL_LJMP(luaL_error(L, "'set_map': unkown map file '%s'", name));
1125
1126 if (pat_ref_find_elt(ref, key) != NULL)
1127 pat_ref_set(ref, key, value, NULL);
1128 else
1129 pat_ref_add(ref, key, value, NULL);
1130 return 0;
1131}
1132
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001133/* A class is a lot of memory that contain data. This data can be a table,
1134 * an integer or user data. This data is associated with a metatable. This
1135 * metatable have an original version registred in the global context with
1136 * the name of the object (_G[<name>] = <metable> ).
1137 *
1138 * A metable is a table that modify the standard behavior of a standard
1139 * access to the associated data. The entries of this new metatable are
1140 * defined as is:
1141 *
1142 * http://lua-users.org/wiki/MetatableEvents
1143 *
1144 * __index
1145 *
1146 * we access an absent field in a table, the result is nil. This is
1147 * true, but it is not the whole truth. Actually, such access triggers
1148 * the interpreter to look for an __index metamethod: If there is no
1149 * such method, as usually happens, then the access results in nil;
1150 * otherwise, the metamethod will provide the result.
1151 *
1152 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1153 * the key does not appear in the table, but the metatable has an __index
1154 * property:
1155 *
1156 * - if the value is a function, the function is called, passing in the
1157 * table and the key; the return value of that function is returned as
1158 * the result.
1159 *
1160 * - if the value is another table, the value of the key in that table is
1161 * asked for and returned (and if it doesn't exist in that table, but that
1162 * table's metatable has an __index property, then it continues on up)
1163 *
1164 * - Use "rawget(myTable,key)" to skip this metamethod.
1165 *
1166 * http://www.lua.org/pil/13.4.1.html
1167 *
1168 * __newindex
1169 *
1170 * Like __index, but control property assignment.
1171 *
1172 * __mode - Control weak references. A string value with one or both
1173 * of the characters 'k' and 'v' which specifies that the the
1174 * keys and/or values in the table are weak references.
1175 *
1176 * __call - Treat a table like a function. When a table is followed by
1177 * parenthesis such as "myTable( 'foo' )" and the metatable has
1178 * a __call key pointing to a function, that function is invoked
1179 * (passing any specified arguments) and the return value is
1180 * returned.
1181 *
1182 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1183 * called, if the metatable for myTable has a __metatable
1184 * key, the value of that key is returned instead of the
1185 * actual metatable.
1186 *
1187 * __tostring - Control string representation. When the builtin
1188 * "tostring( myTable )" function is called, if the metatable
1189 * for myTable has a __tostring property set to a function,
1190 * that function is invoked (passing myTable to it) and the
1191 * return value is used as the string representation.
1192 *
1193 * __len - Control table length. When the table length is requested using
1194 * the length operator ( '#' ), if the metatable for myTable has
1195 * a __len key pointing to a function, that function is invoked
1196 * (passing myTable to it) and the return value used as the value
1197 * of "#myTable".
1198 *
1199 * __gc - Userdata finalizer code. When userdata is set to be garbage
1200 * collected, if the metatable has a __gc field pointing to a
1201 * function, that function is first invoked, passing the userdata
1202 * to it. The __gc metamethod is not called for tables.
1203 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1204 *
1205 * Special metamethods for redefining standard operators:
1206 * http://www.lua.org/pil/13.1.html
1207 *
1208 * __add "+"
1209 * __sub "-"
1210 * __mul "*"
1211 * __div "/"
1212 * __unm "!"
1213 * __pow "^"
1214 * __concat ".."
1215 *
1216 * Special methods for redfining standar relations
1217 * http://www.lua.org/pil/13.2.html
1218 *
1219 * __eq "=="
1220 * __lt "<"
1221 * __le "<="
1222 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001223
1224/*
1225 *
1226 *
1227 * Class Socket
1228 *
1229 *
1230 */
1231
1232__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1233{
1234 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1235}
1236
1237/* This function is the handler called for each I/O on the established
1238 * connection. It is used for notify space avalaible to send or data
1239 * received.
1240 */
1241static void hlua_socket_handler(struct stream_interface *si)
1242{
1243 struct appctx *appctx = objt_appctx(si->end);
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001244 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001245
1246 /* Wakeup the main session if the client connection is closed. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001247 if (!c || channel_output_closed(si_ic(si)) || channel_input_closed(si_oc(si))) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001248 if (appctx->ctx.hlua.socket) {
1249 appctx->ctx.hlua.socket->s = NULL;
1250 appctx->ctx.hlua.socket = NULL;
1251 }
1252 si_shutw(si);
1253 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001254 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001255 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1256 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1257 return;
1258 }
1259
1260 if (!(c->flags & CO_FL_CONNECTED))
1261 return;
1262
1263 /* This function is called after the connect. */
1264 appctx->ctx.hlua.connected = 1;
1265
1266 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001267 if (channel_may_recv(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001268 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1269
1270 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001271 if (channel_is_empty(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001272 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1273}
1274
1275/* This function is called when the "struct session" is destroyed.
1276 * Remove the link from the object to this session.
1277 * Wake all the pending signals.
1278 */
1279static void hlua_socket_release(struct stream_interface *si)
1280{
1281 struct appctx *appctx = objt_appctx(si->end);
1282
1283 /* Remove my link in the original object. */
1284 if (appctx->ctx.hlua.socket)
1285 appctx->ctx.hlua.socket->s = NULL;
1286
1287 /* Wake all the task waiting for me. */
1288 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1289 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1290}
1291
1292/* If the garbage collectio of the object is launch, nobody
1293 * uses this object. If the session does not exists, just quit.
1294 * Send the shutdown signal to the session. In some cases,
1295 * pending signal can rest in the read and write lists. destroy
1296 * it.
1297 */
1298__LJMP static int hlua_socket_gc(lua_State *L)
1299{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001300 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001301 struct appctx *appctx;
1302
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001303 MAY_LJMP(check_args(L, 1, "__gc"));
1304
1305 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001306 if (!socket->s)
1307 return 0;
1308
1309 /* Remove all reference between the Lua stack and the coroutine session. */
1310 appctx = objt_appctx(socket->s->si[0].end);
1311 session_shutdown(socket->s, SN_ERR_KILLED);
1312 socket->s = NULL;
1313 appctx->ctx.hlua.socket = NULL;
1314
1315 return 0;
1316}
1317
1318/* The close function send shutdown signal and break the
1319 * links between the session and the object.
1320 */
1321__LJMP static int hlua_socket_close(lua_State *L)
1322{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001323 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001324 struct appctx *appctx;
1325
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001326 MAY_LJMP(check_args(L, 1, "close"));
1327
1328 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001329 if (!socket->s)
1330 return 0;
1331
1332 /* Close the session and remove the associated stop task. */
1333 session_shutdown(socket->s, SN_ERR_KILLED);
1334 appctx = objt_appctx(socket->s->si[0].end);
1335 appctx->ctx.hlua.socket = NULL;
1336 socket->s = NULL;
1337
1338 return 0;
1339}
1340
1341/* This Lua function assumes that the stack contain three parameters.
1342 * 1 - USERDATA containing a struct socket
1343 * 2 - INTEGER with values of the macro defined below
1344 * If the integer is -1, we must read at most one line.
1345 * If the integer is -2, we ust read all the data until the
1346 * end of the stream.
1347 * If the integer is positive value, we must read a number of
1348 * bytes corresponding to this value.
1349 */
1350#define HLSR_READ_LINE (-1)
1351#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001352__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001353{
1354 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1355 int wanted = lua_tointeger(L, 2);
1356 struct hlua *hlua = hlua_gethlua(L);
1357 struct appctx *appctx;
1358 int len;
1359 int nblk;
1360 char *blk1;
1361 int len1;
1362 char *blk2;
1363 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001364 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001365 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001366
1367 /* Check if this lua stack is schedulable. */
1368 if (!hlua || !hlua->task)
1369 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1370 "'frontend', 'backend' or 'task'"));
1371
1372 /* check for connection closed. If some data where read, return it. */
1373 if (!socket->s)
1374 goto connection_closed;
1375
Willy Tarreau94aa6172015-03-13 14:19:06 +01001376 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001377 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001378 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001379 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001380 if (nblk < 0) /* Connection close. */
1381 goto connection_closed;
1382 if (nblk == 0) /* No data avalaible. */
1383 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001384
1385 /* remove final \r\n. */
1386 if (nblk == 1) {
1387 if (blk1[len1-1] == '\n') {
1388 len1--;
1389 skip_at_end++;
1390 if (blk1[len1-1] == '\r') {
1391 len1--;
1392 skip_at_end++;
1393 }
1394 }
1395 }
1396 else {
1397 if (blk2[len2-1] == '\n') {
1398 len2--;
1399 skip_at_end++;
1400 if (blk2[len2-1] == '\r') {
1401 len2--;
1402 skip_at_end++;
1403 }
1404 }
1405 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001406 }
1407
1408 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001409 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001410 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001411 if (nblk < 0) /* Connection close. */
1412 goto connection_closed;
1413 if (nblk == 0) /* No data avalaible. */
1414 goto connection_empty;
1415 }
1416
1417 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001418 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001419 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001420 if (nblk < 0) /* Connection close. */
1421 goto connection_closed;
1422 if (nblk == 0) /* No data avalaible. */
1423 goto connection_empty;
1424
1425 if (len1 > wanted) {
1426 nblk = 1;
1427 len1 = wanted;
1428 } if (nblk == 2 && len1 + len2 > wanted)
1429 len2 = wanted - len1;
1430 }
1431
1432 len = len1;
1433
1434 luaL_addlstring(&socket->b, blk1, len1);
1435 if (nblk == 2) {
1436 len += len2;
1437 luaL_addlstring(&socket->b, blk2, len2);
1438 }
1439
1440 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001441 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001442
1443 /* Don't wait anything. */
1444 si_update(&socket->s->si[0]);
1445
1446 /* If the pattern reclaim to read all the data
1447 * in the connection, got out.
1448 */
1449 if (wanted == HLSR_READ_ALL)
1450 goto connection_empty;
1451 else if (wanted >= 0 && len < wanted)
1452 goto connection_empty;
1453
1454 /* Return result. */
1455 luaL_pushresult(&socket->b);
1456 return 1;
1457
1458connection_closed:
1459
1460 /* If the buffer containds data. */
1461 if (socket->b.n > 0) {
1462 luaL_pushresult(&socket->b);
1463 return 1;
1464 }
1465 lua_pushnil(L);
1466 lua_pushstring(L, "connection closed.");
1467 return 2;
1468
1469connection_empty:
1470
1471 appctx = objt_appctx(socket->s->si[0].end);
1472 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1473 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001474 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001475 return 0;
1476}
1477
1478/* This Lus function gets two parameters. The first one can be string
1479 * or a number. If the string is "*l", the user require one line. If
1480 * the string is "*a", the user require all the content of the stream.
1481 * If the value is a number, the user require a number of bytes equal
1482 * to the value. The default value is "*l" (a line).
1483 *
1484 * This paraeter with a variable type is converted in integer. This
1485 * integer takes this values:
1486 * -1 : read a line
1487 * -2 : read all the stream
1488 * >0 : amount if bytes.
1489 *
1490 * The second parameter is optinal. It contains a string that must be
1491 * concatenated with the read data.
1492 */
1493__LJMP static int hlua_socket_receive(struct lua_State *L)
1494{
1495 int wanted = HLSR_READ_LINE;
1496 const char *pattern;
1497 int type;
1498 char *error;
1499 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001500 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001501
1502 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1503 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1504
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001505 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001506
1507 /* check for pattern. */
1508 if (lua_gettop(L) >= 2) {
1509 type = lua_type(L, 2);
1510 if (type == LUA_TSTRING) {
1511 pattern = lua_tostring(L, 2);
1512 if (strcmp(pattern, "*a") == 0)
1513 wanted = HLSR_READ_ALL;
1514 else if (strcmp(pattern, "*l") == 0)
1515 wanted = HLSR_READ_LINE;
1516 else {
1517 wanted = strtoll(pattern, &error, 10);
1518 if (*error != '\0')
1519 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1520 }
1521 }
1522 else if (type == LUA_TNUMBER) {
1523 wanted = lua_tointeger(L, 2);
1524 if (wanted < 0)
1525 WILL_LJMP(luaL_error(L, "Unsupported size."));
1526 }
1527 }
1528
1529 /* Set pattern. */
1530 lua_pushinteger(L, wanted);
1531 lua_replace(L, 2);
1532
1533 /* init bufffer, and fiil it wih prefix. */
1534 luaL_buffinit(L, &socket->b);
1535
1536 /* Check prefix. */
1537 if (lua_gettop(L) >= 3) {
1538 if (lua_type(L, 3) != LUA_TSTRING)
1539 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1540 pattern = lua_tolstring(L, 3, &len);
1541 luaL_addlstring(&socket->b, pattern, len);
1542 }
1543
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001544 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001545}
1546
1547/* Write the Lua input string in the output buffer.
1548 * This fucntion returns a yield if no space are available.
1549 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001550static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001551{
1552 struct hlua_socket *socket;
1553 struct hlua *hlua = hlua_gethlua(L);
1554 struct appctx *appctx;
1555 size_t buf_len;
1556 const char *buf;
1557 int len;
1558 int send_len;
1559 int sent;
1560
1561 /* Check if this lua stack is schedulable. */
1562 if (!hlua || !hlua->task)
1563 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1564 "'frontend', 'backend' or 'task'"));
1565
1566 /* Get object */
1567 socket = MAY_LJMP(hlua_checksocket(L, 1));
1568 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001569 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001570
1571 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001572 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001573 lua_pushinteger(L, -1);
1574 return 1;
1575 }
1576
1577 /* Update the input buffer data. */
1578 buf += sent;
1579 send_len = buf_len - sent;
1580
1581 /* All the data are sent. */
1582 if (sent >= buf_len)
1583 return 1; /* Implicitly return the length sent. */
1584
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001585 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1586 * the request buffer if its not required.
1587 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001588 if (socket->s->req.buf->size == 0) {
Willy Tarreau78955f42014-12-28 13:09:02 +01001589 if (!session_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001590 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001591 goto hlua_socket_write_yield_return;
1592 }
1593 }
1594
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001595 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001596 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001597 if (len <= 0)
1598 goto hlua_socket_write_yield_return;
1599
1600 /* send data */
1601 if (len < send_len)
1602 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001603 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001604
1605 /* "Not enough space" (-1), "Buffer too little to contain
1606 * the data" (-2) are not expected because the available length
1607 * is tested.
1608 * Other unknown error are also not expected.
1609 */
1610 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001611 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001612 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001613
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001614 MAY_LJMP(hlua_socket_close(L));
1615 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001616 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001617 return 1;
1618 }
1619
1620 /* update buffers. */
1621 si_update(&socket->s->si[0]);
Willy Tarreau94aa6172015-03-13 14:19:06 +01001622 socket->s->req.rex = TICK_ETERNITY;
1623 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001624
1625 /* Update length sent. */
1626 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001627 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001628
1629 /* All the data buffer is sent ? */
1630 if (sent + len >= buf_len)
1631 return 1;
1632
1633hlua_socket_write_yield_return:
1634 appctx = objt_appctx(socket->s->si[0].end);
1635 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1636 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001637 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001638 return 0;
1639}
1640
1641/* This function initiate the send of data. It just check the input
1642 * parameters and push an integer in the Lua stack that contain the
1643 * amount of data writed in the buffer. This is used by the function
1644 * "hlua_socket_write_yield" that can yield.
1645 *
1646 * The Lua function gets between 3 and 4 parameters. The first one is
1647 * the associated object. The second is a string buffer. The third is
1648 * a facultative integer that represents where is the buffer position
1649 * of the start of the data that can send. The first byte is the
1650 * position "1". The default value is "1". The fourth argument is a
1651 * facultative integer that represents where is the buffer position
1652 * of the end of the data that can send. The default is the last byte.
1653 */
1654static int hlua_socket_send(struct lua_State *L)
1655{
1656 int i;
1657 int j;
1658 const char *buf;
1659 size_t buf_len;
1660
1661 /* Check number of arguments. */
1662 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1663 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1664
1665 /* Get the string. */
1666 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1667
1668 /* Get and check j. */
1669 if (lua_gettop(L) == 4) {
1670 j = MAY_LJMP(luaL_checkinteger(L, 4));
1671 if (j < 0)
1672 j = buf_len + j + 1;
1673 if (j > buf_len)
1674 j = buf_len + 1;
1675 lua_pop(L, 1);
1676 }
1677 else
1678 j = buf_len;
1679
1680 /* Get and check i. */
1681 if (lua_gettop(L) == 3) {
1682 i = MAY_LJMP(luaL_checkinteger(L, 3));
1683 if (i < 0)
1684 i = buf_len + i + 1;
1685 if (i > buf_len)
1686 i = buf_len + 1;
1687 lua_pop(L, 1);
1688 } else
1689 i = 1;
1690
1691 /* Check bth i and j. */
1692 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001693 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001694 return 1;
1695 }
1696 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001697 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001698 return 1;
1699 }
1700 if (i == 0)
1701 i = 1;
1702 if (j == 0)
1703 j = 1;
1704
1705 /* Pop the string. */
1706 lua_pop(L, 1);
1707
1708 /* Update the buffer length. */
1709 buf += i - 1;
1710 buf_len = j - i + 1;
1711 lua_pushlstring(L, buf, buf_len);
1712
1713 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001714 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001715
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001716 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001717}
1718
1719#define SOCKET_INFO_EXPANDED_FORM "[0000:0000:0000:0000:0000:0000:0000:0000]:12345"
1720static char _socket_info_expanded_form[] = SOCKET_INFO_EXPANDED_FORM;
1721#define SOCKET_INFO_MAX_LEN (sizeof(_socket_info_expanded_form))
1722__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
1723{
1724 static char buffer[SOCKET_INFO_MAX_LEN];
1725 int ret;
1726 int len;
1727 char *p;
1728
1729 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
1730 if (ret <= 0) {
1731 lua_pushnil(L);
1732 return 1;
1733 }
1734
1735 if (ret == AF_UNIX) {
1736 lua_pushstring(L, buffer+1);
1737 return 1;
1738 }
1739 else if (ret == AF_INET6) {
1740 buffer[0] = '[';
1741 len = strlen(buffer);
1742 buffer[len] = ']';
1743 len++;
1744 buffer[len] = ':';
1745 len++;
1746 p = buffer;
1747 }
1748 else if (ret == AF_INET) {
1749 p = buffer + 1;
1750 len = strlen(p);
1751 p[len] = ':';
1752 len++;
1753 }
1754 else {
1755 lua_pushnil(L);
1756 return 1;
1757 }
1758
1759 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
1760 lua_pushnil(L);
1761 return 1;
1762 }
1763
1764 lua_pushstring(L, p);
1765 return 1;
1766}
1767
1768/* Returns information about the peer of the connection. */
1769__LJMP static int hlua_socket_getpeername(struct lua_State *L)
1770{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001771 struct hlua_socket *socket;
1772 struct connection *conn;
1773
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001774 MAY_LJMP(check_args(L, 1, "getpeername"));
1775
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001776 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001777
1778 /* Check if the tcp object is avalaible. */
1779 if (!socket->s) {
1780 lua_pushnil(L);
1781 return 1;
1782 }
1783
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001784 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001785 if (!conn) {
1786 lua_pushnil(L);
1787 return 1;
1788 }
1789
1790 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
1791 unsigned int salen = sizeof(conn->addr.to);
1792 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
1793 lua_pushnil(L);
1794 return 1;
1795 }
1796 conn->flags |= CO_FL_ADDR_TO_SET;
1797 }
1798
1799 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
1800}
1801
1802/* Returns information about my connection side. */
1803static int hlua_socket_getsockname(struct lua_State *L)
1804{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001805 struct hlua_socket *socket;
1806 struct connection *conn;
1807
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001808 MAY_LJMP(check_args(L, 1, "getsockname"));
1809
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001810 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001811
1812 /* Check if the tcp object is avalaible. */
1813 if (!socket->s) {
1814 lua_pushnil(L);
1815 return 1;
1816 }
1817
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001818 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001819 if (!conn) {
1820 lua_pushnil(L);
1821 return 1;
1822 }
1823
1824 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
1825 unsigned int salen = sizeof(conn->addr.from);
1826 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
1827 lua_pushnil(L);
1828 return 1;
1829 }
1830 conn->flags |= CO_FL_ADDR_FROM_SET;
1831 }
1832
1833 return hlua_socket_info(L, &conn->addr.from);
1834}
1835
1836/* This struct define the applet. */
1837static struct si_applet update_applet = {
1838 .obj_type = OBJ_TYPE_APPLET,
1839 .name = "<LUA_TCP>",
1840 .fct = hlua_socket_handler,
1841 .release = hlua_socket_release,
1842};
1843
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001844__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001845{
1846 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1847 struct hlua *hlua = hlua_gethlua(L);
1848 struct appctx *appctx;
1849
1850 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001851 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001852 lua_pushnil(L);
1853 lua_pushstring(L, "Can't connect");
1854 return 2;
1855 }
1856
1857 appctx = objt_appctx(socket->s->si[0].end);
1858
1859 /* Check for connection established. */
1860 if (appctx->ctx.hlua.connected) {
1861 lua_pushinteger(L, 1);
1862 return 1;
1863 }
1864
1865 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1866 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001867 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001868 return 0;
1869}
1870
1871/* This function fail or initite the connection. */
1872__LJMP static int hlua_socket_connect(struct lua_State *L)
1873{
1874 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001875 int port;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001876 const char *ip;
1877 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01001878 struct hlua *hlua;
1879 struct appctx *appctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001880
1881 MAY_LJMP(check_args(L, 3, "connect"));
1882
1883 /* Get args. */
1884 socket = MAY_LJMP(hlua_checksocket(L, 1));
1885 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001886 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001887
Willy Tarreau350f4872014-11-28 14:42:25 +01001888 conn = si_alloc_conn(&socket->s->si[1], 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001889 if (!conn)
1890 WILL_LJMP(luaL_error(L, "connect: internal error"));
1891
1892 /* Parse ip address. */
1893 conn->addr.to.ss_family = AF_UNSPEC;
1894 if (!str2ip2(ip, &conn->addr.to, 0))
1895 WILL_LJMP(luaL_error(L, "connect: cannot parse ip address '%s'", ip));
1896
1897 /* Set port. */
1898 if (conn->addr.to.ss_family == AF_INET)
1899 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
1900 else if (conn->addr.to.ss_family == AF_INET6)
1901 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
1902
1903 /* it is important not to call the wakeup function directly but to
1904 * pass through task_wakeup(), because this one knows how to apply
1905 * priorities to tasks.
1906 */
1907 task_wakeup(socket->s->task, TASK_WOKEN_INIT);
1908
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01001909 hlua = hlua_gethlua(L);
1910 appctx = objt_appctx(socket->s->si[0].end);
1911 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1912 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001913 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001914
1915 return 0;
1916}
1917
Baptiste Assmann84bb4932015-03-02 21:40:06 +01001918#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001919__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
1920{
1921 struct hlua_socket *socket;
1922
1923 MAY_LJMP(check_args(L, 3, "connect_ssl"));
1924 socket = MAY_LJMP(hlua_checksocket(L, 1));
1925 socket->s->target = &socket_ssl.obj_type;
1926 return MAY_LJMP(hlua_socket_connect(L));
1927}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01001928#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001929
1930__LJMP static int hlua_socket_setoption(struct lua_State *L)
1931{
1932 return 0;
1933}
1934
1935__LJMP static int hlua_socket_settimeout(struct lua_State *L)
1936{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001937 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001938 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001939
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001940 MAY_LJMP(check_args(L, 2, "settimeout"));
1941
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001942 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001943 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001944
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001945 socket->s->req.rto = tmout;
1946 socket->s->req.wto = tmout;
1947 socket->s->res.rto = tmout;
1948 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001949
1950 return 0;
1951}
1952
1953__LJMP static int hlua_socket_new(lua_State *L)
1954{
1955 struct hlua_socket *socket;
1956 struct appctx *appctx;
1957
1958 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01001959 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001960 hlua_pusherror(L, "socket: full stack");
1961 goto out_fail_conf;
1962 }
1963
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01001964 /* Create the object: obj[0] = userdata. */
1965 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001966 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01001967 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001968 memset(socket, 0, sizeof(*socket));
1969
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01001970 /* Check if the various memory pools are intialized. */
Willy Tarreaua27dc192014-11-27 22:10:04 +01001971 if (!pool2_session || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01001972 hlua_pusherror(L, "socket: uninitialized pools.");
1973 goto out_fail_conf;
1974 }
1975
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001976 /* Pop a class session metatable and affect it to the userdata. */
1977 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
1978 lua_setmetatable(L, -2);
1979
1980 /*
1981 *
1982 * Get memory for the request.
1983 *
1984 */
1985
1986 socket->s = pool_alloc2(pool2_session);
1987 if (!socket->s) {
1988 hlua_pusherror(L, "socket: out of memory");
1989 goto out_fail_conf;
1990 }
1991
1992 socket->s->task = task_new();
1993 if (!socket->s->task) {
1994 hlua_pusherror(L, "socket: out of memory");
1995 goto out_free_session;
1996 }
1997
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001998 socket->s->req.buf = pool_alloc2(pool2_buffer);
1999 if (!socket->s->req.buf) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002000 hlua_pusherror(L, "socket: out of memory");
2001 goto out_fail_req_buf;
2002 }
2003
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002004 socket->s->res.buf = pool_alloc2(pool2_buffer);
2005 if (!socket->s->res.buf) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002006 hlua_pusherror(L, "socket: out of memory");
2007 goto out_fail_rep_buf;
2008 }
2009
2010 /* Configura empty Lua for the session. */
2011 socket->s->hlua.T = NULL;
2012 socket->s->hlua.Tref = LUA_REFNIL;
2013 socket->s->hlua.Mref = LUA_REFNIL;
2014 socket->s->hlua.nargs = 0;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01002015 socket->s->hlua.flags = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002016 LIST_INIT(&socket->s->hlua.com);
2017
2018 /* session initialisation. */
2019 session_init_srv_conn(socket->s);
2020
2021 /*
2022 *
2023 * Configure the associated task.
2024 *
2025 */
2026
2027 /* This is the dedicated function to process the session. This function
2028 * is able to establish the conection, process the timeouts, etc ...
2029 */
2030 socket->s->task->process = process_session;
2031
2032 /* Back reference to session. This is used by process_session(). */
2033 socket->s->task->context = socket->s;
2034
2035 /* The priority of the task is normal. */
2036 socket->s->task->nice = 0;
2037
2038 /* Init the next run to eternity. Later in this function, this task is
2039 * waked.
2040 */
2041 socket->s->task->expire = TICK_ETERNITY;
2042
2043 /*
2044 *
2045 * Initialize the attached buffers
2046 *
2047 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002048 socket->s->req.buf->size = global.tune.bufsize;
2049 socket->s->res.buf->size = global.tune.bufsize;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002050
2051 /*
2052 *
2053 * Initialize channels.
2054 *
2055 */
2056
2057 /* This function reset the struct. It must be called
2058 * before the configuration.
2059 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002060 channel_init(&socket->s->req);
2061 channel_init(&socket->s->res);
Willy Tarreauef573c02014-11-28 14:17:09 +01002062 socket->s->res.flags |= CF_ISRESP;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002063
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002064 socket->s->req.analysers = 0;
2065 socket->s->req.rto = socket_proxy.timeout.client;
2066 socket->s->req.wto = socket_proxy.timeout.server;
2067 socket->s->req.rex = TICK_ETERNITY;
2068 socket->s->req.wex = TICK_ETERNITY;
2069 socket->s->req.analyse_exp = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002070
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002071 socket->s->res.analysers = 0;
2072 socket->s->res.rto = socket_proxy.timeout.server;
2073 socket->s->res.wto = socket_proxy.timeout.client;
2074 socket->s->res.rex = TICK_ETERNITY;
2075 socket->s->res.wex = TICK_ETERNITY;
2076 socket->s->res.analyse_exp = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002077
2078 /*
2079 *
2080 * Configure the session.
2081 *
2082 */
2083
2084 /* The session dont have listener. The listener is used with real
2085 * proxies.
2086 */
2087 socket->s->listener = NULL;
2088
2089 /* The flags are initialized to 0. Values are setted later. */
2090 socket->s->flags = 0;
2091
2092 /* Assign the configured proxy to the new session. */
2093 socket->s->be = &socket_proxy;
2094 socket->s->fe = &socket_proxy;
2095
2096 /* XXX: Set namy variables */
2097 socket->s->store_count = 0;
2098 memset(socket->s->stkctr, 0, sizeof(socket->s->stkctr));
2099
2100 /* Configure logs. */
2101 socket->s->logs.logwait = 0;
2102 socket->s->logs.level = 0;
2103 socket->s->logs.accept_date = date; /* user-visible date for logging */
2104 socket->s->logs.tv_accept = now; /* corrected date for internal use */
2105 socket->s->do_log = NULL;
2106
2107 /* Function used if an error is occured. */
2108 socket->s->srv_error = default_srv_error;
2109
2110 /* Init the list of buffers. */
2111 LIST_INIT(&socket->s->buffer_wait);
2112
2113 /* Dont configure the unique ID. */
2114 socket->s->uniq_id = 0;
2115 socket->s->unique_id = NULL;
2116
2117 /* XXX: ? */
2118 socket->s->pend_pos = NULL;
2119
2120 /* XXX: See later. */
2121 socket->s->txn.sessid = NULL;
2122 socket->s->txn.srv_cookie = NULL;
2123 socket->s->txn.cli_cookie = NULL;
2124 socket->s->txn.uri = NULL;
2125 socket->s->txn.req.cap = NULL;
2126 socket->s->txn.rsp.cap = NULL;
2127 socket->s->txn.hdr_idx.v = NULL;
2128 socket->s->txn.hdr_idx.size = 0;
2129 socket->s->txn.hdr_idx.used = 0;
2130
2131 /* Configure "left" stream interface as applet. This "si" produce
2132 * and use the data received from the server. The applet is initialized
2133 * and is attached to the stream interface.
2134 */
2135
2136 /* The data producer is already connected. It is the applet. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002137 socket->s->req.flags = CF_READ_ATTACHED;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002138
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002139 channel_auto_connect(&socket->s->req); /* don't wait to establish connection */
2140 channel_auto_close(&socket->s->req); /* let the producer forward close requests */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002141
Willy Tarreaua5f5d8d2014-11-28 11:26:07 +01002142 socket->s->si[0].flags = SI_FL_NONE;
Willy Tarreau819d3322014-11-28 12:12:34 +01002143 si_reset(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002144 si_set_state(&socket->s->si[0], SI_ST_EST); /* connection established (resource exists) */
2145
2146 appctx = stream_int_register_handler(&socket->s->si[0], &update_applet);
2147 if (!appctx)
2148 goto out_fail_conn1;
2149 appctx->ctx.hlua.socket = socket;
2150 appctx->ctx.hlua.connected = 0;
2151 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2152 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
2153
2154 /* Configure "right" stream interface. this "si" is used to connect
2155 * and retrieve data from the server. The connection is initialized
2156 * with the "struct server".
2157 */
Willy Tarreaua5f5d8d2014-11-28 11:26:07 +01002158 socket->s->si[1].flags = SI_FL_ISBACK;
Willy Tarreau819d3322014-11-28 12:12:34 +01002159 si_reset(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002160 si_set_state(&socket->s->si[1], SI_ST_INI);
2161 socket->s->si[1].conn_retries = socket_proxy.conn_retries;
2162
2163 /* Force destination server. */
2164 socket->s->flags |= SN_DIRECT | SN_ASSIGNED | SN_ADDR_SET | SN_BE_ASSIGNED;
2165 socket->s->target = &socket_tcp.obj_type;
2166
2167 /* This session is added to te lists of alive sessions. */
2168 LIST_ADDQ(&sessions, &socket->s->list);
2169
2170 /* XXX: I think that this list is used by stats. */
2171 LIST_INIT(&socket->s->back_refs);
2172
2173 /* Update statistics counters. */
2174 socket_proxy.feconn++; /* beconn will be increased later */
2175 jobs++;
2176 totalconn++;
2177
2178 /* Return yield waiting for connection. */
2179 return 1;
2180
2181out_fail_conn1:
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002182 pool_free2(pool2_buffer, socket->s->res.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002183out_fail_rep_buf:
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002184 pool_free2(pool2_buffer, socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002185out_fail_req_buf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002186 task_free(socket->s->task);
2187out_free_session:
2188 pool_free2(pool2_session, socket->s);
2189out_fail_conf:
2190 WILL_LJMP(lua_error(L));
2191 return 0;
2192}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002193
2194/*
2195 *
2196 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002197 * Class Channel
2198 *
2199 *
2200 */
2201
2202/* Returns the struct hlua_channel join to the class channel in the
2203 * stack entry "ud" or throws an argument error.
2204 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002205__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002206{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002207 return (struct channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002208}
2209
Willy Tarreau47860ed2015-03-10 14:07:50 +01002210/* Pushes the channel onto the top of the stack. If the stask does not have a
2211 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002212 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002213static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002214{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002215 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002216 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002217 return 0;
2218
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002219 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002220 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002221 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002222
2223 /* Pop a class sesison metatable and affect it to the userdata. */
2224 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2225 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002226 return 1;
2227}
2228
2229/* Duplicate all the data present in the input channel and put it
2230 * in a string LUA variables. Returns -1 and push a nil value in
2231 * the stack if the channel is closed and all the data are consumed,
2232 * returns 0 if no data are available, otherwise it returns the length
2233 * of the builded string.
2234 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002235static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002236{
2237 char *blk1;
2238 char *blk2;
2239 int len1;
2240 int len2;
2241 int ret;
2242 luaL_Buffer b;
2243
Willy Tarreau47860ed2015-03-10 14:07:50 +01002244 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002245 if (unlikely(ret == 0))
2246 return 0;
2247
2248 if (unlikely(ret < 0)) {
2249 lua_pushnil(L);
2250 return -1;
2251 }
2252
2253 luaL_buffinit(L, &b);
2254 luaL_addlstring(&b, blk1, len1);
2255 if (unlikely(ret == 2))
2256 luaL_addlstring(&b, blk2, len2);
2257 luaL_pushresult(&b);
2258
2259 if (unlikely(ret == 2))
2260 return len1 + len2;
2261 return len1;
2262}
2263
2264/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2265 * a yield. This function keep the data in the buffer.
2266 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002267__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002268{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002269 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002270
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002271 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2272
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002273 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002274 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002275 return 1;
2276}
2277
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002278/* Check arguments for the function "hlua_channel_dup_yield". */
2279__LJMP static int hlua_channel_dup(lua_State *L)
2280{
2281 MAY_LJMP(check_args(L, 1, "dup"));
2282 MAY_LJMP(hlua_checkchannel(L, 1));
2283 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2284}
2285
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002286/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2287 * a yield. This function consumes the data in the buffer. It returns
2288 * a string containing the data or a nil pointer if no data are available
2289 * and the channel is closed.
2290 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002291__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002292{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002293 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002294 int ret;
2295
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002296 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002297
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002298 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002299 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002300 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002301
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002302 if (unlikely(ret == -1))
2303 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002304
Willy Tarreau47860ed2015-03-10 14:07:50 +01002305 chn->buf->i -= ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002306 return 1;
2307}
2308
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002309/* Check arguments for the fucntion "hlua_channel_get_yield". */
2310__LJMP static int hlua_channel_get(lua_State *L)
2311{
2312 MAY_LJMP(check_args(L, 1, "get"));
2313 MAY_LJMP(hlua_checkchannel(L, 1));
2314 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2315}
2316
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002317/* This functions consumes and returns one line. If the channel is closed,
2318 * and the last data does not contains a final '\n', the data are returned
2319 * without the final '\n'. When no more data are avalaible, it returns nil
2320 * value.
2321 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002322__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002323{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002324 char *blk1;
2325 char *blk2;
2326 int len1;
2327 int len2;
2328 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002329 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002330 int ret;
2331 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002332
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002333 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2334
Willy Tarreau47860ed2015-03-10 14:07:50 +01002335 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002336 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002337 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002338
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002339 if (ret == -1) {
2340 lua_pushnil(L);
2341 return 1;
2342 }
2343
2344 luaL_buffinit(L, &b);
2345 luaL_addlstring(&b, blk1, len1);
2346 len = len1;
2347 if (unlikely(ret == 2)) {
2348 luaL_addlstring(&b, blk2, len2);
2349 len += len2;
2350 }
2351 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002352 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002353 return 1;
2354}
2355
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002356/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2357__LJMP static int hlua_channel_getline(lua_State *L)
2358{
2359 MAY_LJMP(check_args(L, 1, "getline"));
2360 MAY_LJMP(hlua_checkchannel(L, 1));
2361 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2362}
2363
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002364/* This function takes a string as input, and append it at the
2365 * input side of channel. If the data is too big, but a space
2366 * is probably available after sending some data, the function
2367 * yield. If the data is bigger than the buffer, or if the
2368 * channel is closed, it returns -1. otherwise, it returns the
2369 * amount of data writed.
2370 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002371__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002372{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002373 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002374 size_t len;
2375 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2376 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2377 int ret;
2378 int max;
2379
Willy Tarreau47860ed2015-03-10 14:07:50 +01002380 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002381 if (max > len - l)
2382 max = len - l;
2383
Willy Tarreau47860ed2015-03-10 14:07:50 +01002384 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002385 if (ret == -2 || ret == -3) {
2386 lua_pushinteger(L, -1);
2387 return 1;
2388 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002389 if (ret == -1) {
2390 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002391 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002392 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002393 l += ret;
2394 lua_pop(L, 1);
2395 lua_pushinteger(L, l);
2396
Willy Tarreau47860ed2015-03-10 14:07:50 +01002397 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2398 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002399 /* There are no space avalaible, and the output buffer is empty.
2400 * in this case, we cannot add more data, so we cannot yield,
2401 * we return the amount of copyied data.
2402 */
2403 return 1;
2404 }
2405 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002406 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002407 return 1;
2408}
2409
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002410/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002411 * of the writed string, or -1 if the channel is closed or if the
2412 * buffer size is too little for the data.
2413 */
2414__LJMP static int hlua_channel_append(lua_State *L)
2415{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002416 size_t len;
2417
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002418 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002419 MAY_LJMP(hlua_checkchannel(L, 1));
2420 MAY_LJMP(luaL_checklstring(L, 2, &len));
2421 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002422 lua_pushinteger(L, 0);
2423
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002424 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002425}
2426
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002427/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002428 * his process by cleaning the buffer. The result is a replacement
2429 * of the current data. It returns the length of the writed string,
2430 * or -1 if the channel is closed or if the buffer size is too
2431 * little for the data.
2432 */
2433__LJMP static int hlua_channel_set(lua_State *L)
2434{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002435 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002436
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002437 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002438 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002439 lua_pushinteger(L, 0);
2440
Willy Tarreau47860ed2015-03-10 14:07:50 +01002441 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002442
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002443 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002444}
2445
2446/* Append data in the output side of the buffer. This data is immediatly
2447 * sent. The fcuntion returns the ammount of data writed. If the buffer
2448 * cannot contains the data, the function yield. The function returns -1
2449 * if the channel is closed.
2450 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002451__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002452{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002453 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002454 size_t len;
2455 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2456 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2457 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002458 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002459
Willy Tarreau47860ed2015-03-10 14:07:50 +01002460 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002461 lua_pushinteger(L, -1);
2462 return 1;
2463 }
2464
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002465 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2466 * the request buffer if its not required.
2467 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002468 if (chn->buf->size == 0) {
2469 if (!session_alloc_recv_buffer(chn)) {
2470 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002471 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002472 }
2473 }
2474
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002475 /* the writed data will be immediatly sent, so we can check
2476 * the avalaible space without taking in account the reserve.
2477 * The reserve is guaranted for the processing of incoming
2478 * data, because the buffer will be flushed.
2479 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002480 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002481
2482 /* If there are no space avalaible, and the output buffer is empty.
2483 * in this case, we cannot add more data, so we cannot yield,
2484 * we return the amount of copyied data.
2485 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002486 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002487 return 1;
2488
2489 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002490 if (max > len - l)
2491 max = len - l;
2492
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002493 /* The buffer avalaible size may be not contiguous. This test
2494 * detects a non contiguous buffer and realign it.
2495 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002496 if (bi_space_for_replace(chn->buf) < max)
2497 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002498
2499 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002500 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002501
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002502 /* buffer replace considers that the input part is filled.
2503 * so, I must forward these new data in the output part.
2504 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002505 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002506
2507 l += max;
2508 lua_pop(L, 1);
2509 lua_pushinteger(L, l);
2510
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002511 /* If there are no space avalaible, and the output buffer is empty.
2512 * in this case, we cannot add more data, so we cannot yield,
2513 * we return the amount of copyied data.
2514 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002515 max = chn->buf->size - buffer_len(chn->buf);
2516 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002517 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002518
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002519 if (l < len) {
2520 /* If we are waiting for space in the response buffer, we
2521 * must set the flag WAKERESWR. This flag required the task
2522 * wake up if any activity is detected on the response buffer.
2523 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002524 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002525 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002526 else
2527 HLUA_SET_WAKEREQWR(hlua);
2528 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002529 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002530
2531 return 1;
2532}
2533
2534/* Just a wraper of "_hlua_channel_send". This wrapper permits
2535 * yield the LUA process, and resume it without checking the
2536 * input arguments.
2537 */
2538__LJMP static int hlua_channel_send(lua_State *L)
2539{
2540 MAY_LJMP(check_args(L, 2, "send"));
2541 lua_pushinteger(L, 0);
2542
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002543 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002544}
2545
2546/* This function forward and amount of butes. The data pass from
2547 * the input side of the buffer to the output side, and can be
2548 * forwarded. This function never fails.
2549 *
2550 * The Lua function takes an amount of bytes to be forwarded in
2551 * imput. It returns the number of bytes forwarded.
2552 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002553__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002554{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002555 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002556 int len;
2557 int l;
2558 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002559 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002560
2561 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2562 len = MAY_LJMP(luaL_checkinteger(L, 2));
2563 l = MAY_LJMP(luaL_checkinteger(L, -1));
2564
2565 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002566 if (max > chn->buf->i)
2567 max = chn->buf->i;
2568 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002569 l += max;
2570
2571 lua_pop(L, 1);
2572 lua_pushinteger(L, l);
2573
2574 /* Check if it miss bytes to forward. */
2575 if (l < len) {
2576 /* The the input channel or the output channel are closed, we
2577 * must return the amount of data forwarded.
2578 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002579 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002580 return 1;
2581
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002582 /* If we are waiting for space data in the response buffer, we
2583 * must set the flag WAKERESWR. This flag required the task
2584 * wake up if any activity is detected on the response buffer.
2585 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002586 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002587 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002588 else
2589 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002590
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002591 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002592 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002593 }
2594
2595 return 1;
2596}
2597
2598/* Just check the input and prepare the stack for the previous
2599 * function "hlua_channel_forward_yield"
2600 */
2601__LJMP static int hlua_channel_forward(lua_State *L)
2602{
2603 MAY_LJMP(check_args(L, 2, "forward"));
2604 MAY_LJMP(hlua_checkchannel(L, 1));
2605 MAY_LJMP(luaL_checkinteger(L, 2));
2606
2607 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002608 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002609}
2610
2611/* Just returns the number of bytes available in the input
2612 * side of the buffer. This function never fails.
2613 */
2614__LJMP static int hlua_channel_get_in_len(lua_State *L)
2615{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002616 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002617
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002618 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002619 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002620 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002621 return 1;
2622}
2623
2624/* Just returns the number of bytes available in the output
2625 * side of the buffer. This function never fails.
2626 */
2627__LJMP static int hlua_channel_get_out_len(lua_State *L)
2628{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002629 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002630
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002631 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002632 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002633 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002634 return 1;
2635}
2636
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002637/*
2638 *
2639 *
2640 * Class Fetches
2641 *
2642 *
2643 */
2644
2645/* Returns a struct hlua_session if the stack entry "ud" is
2646 * a class session, otherwise it throws an error.
2647 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002648__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002649{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002650 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002651}
2652
2653/* This function creates and push in the stack a fetch object according
2654 * with a current TXN.
2655 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002656static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002657{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002658 struct hlua_smp *hs;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002659
2660 /* Check stack size. */
2661 if (!lua_checkstack(L, 3))
2662 return 0;
2663
2664 /* Create the object: obj[0] = userdata.
2665 * Note that the base of the Fetches object is the
2666 * transaction object.
2667 */
2668 lua_newtable(L);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002669 hs = lua_newuserdata(L, sizeof(struct hlua_smp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002670 lua_rawseti(L, -2, 0);
2671
2672 hs->s = txn->s;
2673 hs->p = txn->p;
2674 hs->l7 = txn->l7;
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002675 hs->stringsafe = stringsafe;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002676
2677 /* Pop a class sesison metatable and affect it to the userdata. */
2678 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2679 lua_setmetatable(L, -2);
2680
2681 return 1;
2682}
2683
2684/* This function is an LUA binding. It is called with each sample-fetch.
2685 * It uses closure argument to store the associated sample-fetch. It
2686 * returns only one argument or throws an error. An error is thrown
2687 * only if an error is encountered during the argument parsing. If
2688 * the "sample-fetch" function fails, nil is returned.
2689 */
2690__LJMP static int hlua_run_sample_fetch(lua_State *L)
2691{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002692 struct hlua_smp *s;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002693 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002694 struct arg args[ARGM_NBARGS + 1];
2695 int i;
2696 struct sample smp;
2697
2698 /* Get closure arguments. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002699 f = (struct sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002700
2701 /* Get traditionnal arguments. */
2702 s = MAY_LJMP(hlua_checkfetches(L, 1));
2703
2704 /* Get extra arguments. */
2705 for (i = 0; i < lua_gettop(L) - 1; i++) {
2706 if (i >= ARGM_NBARGS)
2707 break;
2708 hlua_lua2arg(L, i + 2, &args[i]);
2709 }
2710 args[i].type = ARGT_STOP;
2711
2712 /* Check arguments. */
Thierry FOURNIER53dd3cf2015-03-12 18:27:10 +01002713 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, s->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002714
2715 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002716 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002717 lua_pushfstring(L, "error in arguments");
2718 WILL_LJMP(lua_error(L));
2719 }
2720
2721 /* Initialise the sample. */
2722 memset(&smp, 0, sizeof(smp));
2723
2724 /* Run the sample fetch process. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002725 if (!f->process(s->p, s->s, s->l7, 0, args, &smp, f->kw, f->private)) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002726 if (s->stringsafe)
2727 lua_pushstring(L, "");
2728 else
2729 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002730 return 1;
2731 }
2732
2733 /* Convert the returned sample in lua value. */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002734 if (s->stringsafe)
2735 hlua_smp2lua_str(L, &smp);
2736 else
2737 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002738 return 1;
2739}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002740
2741/*
2742 *
2743 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002744 * Class Converters
2745 *
2746 *
2747 */
2748
2749/* Returns a struct hlua_session if the stack entry "ud" is
2750 * a class session, otherwise it throws an error.
2751 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002752__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002753{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002754 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002755}
2756
2757/* This function creates and push in the stack a Converters object
2758 * according with a current TXN.
2759 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002760static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002761{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002762 struct hlua_smp *hs;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002763
2764 /* Check stack size. */
2765 if (!lua_checkstack(L, 3))
2766 return 0;
2767
2768 /* Create the object: obj[0] = userdata.
2769 * Note that the base of the Converters object is the
2770 * same than the TXN object.
2771 */
2772 lua_newtable(L);
2773 hs = lua_newuserdata(L, sizeof(struct hlua_txn));
2774 lua_rawseti(L, -2, 0);
2775
2776 hs->s = txn->s;
2777 hs->p = txn->p;
2778 hs->l7 = txn->l7;
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002779 hs->stringsafe = stringsafe;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002780
2781 /* Pop a class session metatable and affect it to the table. */
2782 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
2783 lua_setmetatable(L, -2);
2784
2785 return 1;
2786}
2787
2788/* This function is an LUA binding. It is called with each converter.
2789 * It uses closure argument to store the associated converter. It
2790 * returns only one argument or throws an error. An error is thrown
2791 * only if an error is encountered during the argument parsing. If
2792 * the converter function function fails, nil is returned.
2793 */
2794__LJMP static int hlua_run_sample_conv(lua_State *L)
2795{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002796 struct hlua_smp *sc;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002797 struct sample_conv *conv;
2798 struct arg args[ARGM_NBARGS + 1];
2799 int i;
2800 struct sample smp;
2801
2802 /* Get closure arguments. */
2803 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
2804
2805 /* Get traditionnal arguments. */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002806 sc = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002807
2808 /* Get extra arguments. */
2809 for (i = 0; i < lua_gettop(L) - 2; i++) {
2810 if (i >= ARGM_NBARGS)
2811 break;
2812 hlua_lua2arg(L, i + 3, &args[i]);
2813 }
2814 args[i].type = ARGT_STOP;
2815
2816 /* Check arguments. */
Thierry FOURNIER53dd3cf2015-03-12 18:27:10 +01002817 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, sc->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002818
2819 /* Run the special args checker. */
2820 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
2821 hlua_pusherror(L, "error in arguments");
2822 WILL_LJMP(lua_error(L));
2823 }
2824
2825 /* Initialise the sample. */
2826 if (!hlua_lua2smp(L, 2, &smp)) {
2827 hlua_pusherror(L, "error in the input argument");
2828 WILL_LJMP(lua_error(L));
2829 }
2830
2831 /* Apply expected cast. */
2832 if (!sample_casts[smp.type][conv->in_type]) {
2833 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
2834 smp_to_type[smp.type], smp_to_type[conv->in_type]);
2835 WILL_LJMP(lua_error(L));
2836 }
2837 if (sample_casts[smp.type][conv->in_type] != c_none &&
2838 !sample_casts[smp.type][conv->in_type](&smp)) {
2839 hlua_pusherror(L, "error during the input argument casting");
2840 WILL_LJMP(lua_error(L));
2841 }
2842
2843 /* Run the sample conversion process. */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002844 if (!conv->process(sc->s, args, &smp, conv->private)) {
2845 if (sc->stringsafe)
2846 lua_pushstring(L, "");
2847 else
2848 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002849 return 1;
2850 }
2851
2852 /* Convert the returned sample in lua value. */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002853 if (sc->stringsafe)
2854 hlua_smp2lua_str(L, &smp);
2855 else
2856 hlua_smp2lua(L, &smp);
2857 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002858}
2859
2860/*
2861 *
2862 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002863 * Class TXN
2864 *
2865 *
2866 */
2867
2868/* Returns a struct hlua_session if the stack entry "ud" is
2869 * a class session, otherwise it throws an error.
2870 */
2871__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
2872{
2873 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
2874}
2875
Willy Tarreau59551662015-03-10 14:23:13 +01002876__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002877{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002878 struct hlua *hlua;
2879
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002880 MAY_LJMP(check_args(L, 2, "set_priv"));
2881
2882 /* It is useles to retrieve the session, but this function
2883 * runs only in a session context.
2884 */
2885 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002886 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002887
2888 /* Remove previous value. */
2889 if (hlua->Mref != -1)
2890 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
2891
2892 /* Get and store new value. */
2893 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
2894 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
2895
2896 return 0;
2897}
2898
Willy Tarreau59551662015-03-10 14:23:13 +01002899__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002900{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002901 struct hlua *hlua;
2902
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002903 MAY_LJMP(check_args(L, 1, "get_priv"));
2904
2905 /* It is useles to retrieve the session, but this function
2906 * runs only in a session context.
2907 */
2908 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002909 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002910
2911 /* Push configuration index in the stack. */
2912 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
2913
2914 return 1;
2915}
2916
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002917/* Create stack entry containing a class TXN. This function
2918 * return 0 if the stack does not contains free slots,
2919 * otherwise it returns 1.
2920 */
2921static int hlua_txn_new(lua_State *L, struct session *s, struct proxy *p, void *l7)
2922{
2923 struct hlua_txn *hs;
2924
2925 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002926 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002927 return 0;
2928
2929 /* NOTE: The allocation never fails. The failure
2930 * throw an error, and the function never returns.
2931 * if the throw is not avalaible, the process is aborted.
2932 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002933 /* Create the object: obj[0] = userdata. */
2934 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002935 hs = lua_newuserdata(L, sizeof(struct hlua_txn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002936 lua_rawseti(L, -2, 0);
2937
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002938 hs->s = s;
2939 hs->p = p;
2940 hs->l7 = l7;
2941
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002942 /* Create the "f" field that contains a list of fetches. */
2943 lua_pushstring(L, "f");
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002944 if (!hlua_fetches_new(L, hs, 0))
2945 return 0;
2946 lua_settable(L, -3);
2947
2948 /* Create the "sf" field that contains a list of stringsafe fetches. */
2949 lua_pushstring(L, "sf");
2950 if (!hlua_fetches_new(L, hs, 1))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002951 return 0;
2952 lua_settable(L, -3);
2953
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002954 /* Create the "c" field that contains a list of converters. */
2955 lua_pushstring(L, "c");
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002956 if (!hlua_converters_new(L, hs, 0))
2957 return 0;
2958 lua_settable(L, -3);
2959
2960 /* Create the "sc" field that contains a list of stringsafe converters. */
2961 lua_pushstring(L, "sc");
2962 if (!hlua_converters_new(L, hs, 1))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002963 return 0;
2964 lua_settable(L, -3);
2965
Thierry FOURNIER397826a2015-03-11 19:39:09 +01002966 /* Create the "req" field that contains the request channel object. */
2967 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01002968 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01002969 return 0;
2970 lua_settable(L, -3);
2971
2972 /* Create the "res" field that contains the response channel object. */
2973 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01002974 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01002975 return 0;
2976 lua_settable(L, -3);
2977
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002978 /* Pop a class sesison metatable and affect it to the userdata. */
2979 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
2980 lua_setmetatable(L, -2);
2981
2982 return 1;
2983}
2984
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002985/* This function is an Lua binding that send pending data
2986 * to the client, and close the stream interface.
2987 */
2988__LJMP static int hlua_txn_close(lua_State *L)
2989{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002990 struct hlua_txn *s;
Willy Tarreau81389672015-03-10 12:03:52 +01002991 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002992
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002993 MAY_LJMP(check_args(L, 1, "close"));
2994 s = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002995
Willy Tarreau94aa6172015-03-13 14:19:06 +01002996 ic = &s->s->req;
2997 oc = &s->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01002998
2999 channel_abort(ic);
3000 channel_auto_close(ic);
3001 channel_erase(ic);
3002 channel_auto_read(oc);
3003 channel_auto_close(oc);
3004 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003005
3006 return 0;
3007}
3008
Thierry FOURNIER9a819e72015-02-16 20:22:55 +01003009/* This function is an LUA binding. It creates ans returns
3010 * an array of HTTP headers. This function does not fails.
3011 */
Willy Tarreau59551662015-03-10 14:23:13 +01003012static int hlua_session_get_headers(lua_State *L)
Thierry FOURNIER9a819e72015-02-16 20:22:55 +01003013{
3014 struct hlua_txn *s = MAY_LJMP(hlua_checktxn(L, 1));
3015 struct session *sess = s->s;
3016 const char *cur_ptr, *cur_next, *p;
3017 int old_idx, cur_idx;
3018 struct hdr_idx_elem *cur_hdr;
3019 const char *hn, *hv;
3020 int hnl, hvl;
3021
3022 /* Create the table. */
3023 lua_newtable(L);
3024
3025 /* Build array of headers. */
3026 old_idx = 0;
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01003027 cur_next = sess->req.buf->p + hdr_idx_first_pos(&sess->txn.hdr_idx);
Thierry FOURNIER9a819e72015-02-16 20:22:55 +01003028
3029 while (1) {
3030 cur_idx = sess->txn.hdr_idx.v[old_idx].next;
3031 if (!cur_idx)
3032 break;
3033 old_idx = cur_idx;
3034
3035 cur_hdr = &sess->txn.hdr_idx.v[cur_idx];
3036 cur_ptr = cur_next;
3037 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
3038
3039 /* Now we have one full header at cur_ptr of len cur_hdr->len,
3040 * and the next header starts at cur_next. We'll check
3041 * this header in the list as well as against the default
3042 * rule.
3043 */
3044
3045 /* look for ': *'. */
3046 hn = cur_ptr;
3047 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
3048 if (p >= cur_ptr+cur_hdr->len)
3049 continue;
3050 hnl = p - hn;
3051 p++;
3052 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
3053 p++;
3054 if (p >= cur_ptr+cur_hdr->len)
3055 continue;
3056 hv = p;
3057 hvl = cur_ptr+cur_hdr->len-p;
3058
3059 /* Push values in the table. */
3060 lua_pushlstring(L, hn, hnl);
3061 lua_pushlstring(L, hv, hvl);
3062 lua_settable(L, -3);
3063 }
3064
3065 return 1;
3066}
3067
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003068__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003069{
3070 int wakeup_ms = lua_tointeger(L, -1);
3071 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003072 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003073 return 0;
3074}
3075
3076__LJMP static int hlua_sleep(lua_State *L)
3077{
3078 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003079 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003080
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003081 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003082
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003083 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003084 wakeup_ms = tick_add(now_ms, delay);
3085 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003086
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003087 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3088 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003089}
3090
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003091__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003092{
3093 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003094 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003095
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003096 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003097
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003098 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003099 wakeup_ms = tick_add(now_ms, delay);
3100 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003101
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003102 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3103 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003104}
3105
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003106/* This functionis an LUA binding. it permits to give back
3107 * the hand at the HAProxy scheduler. It is used when the
3108 * LUA processing consumes a lot of time.
3109 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003110__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003111{
3112 return 0;
3113}
3114
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003115__LJMP static int hlua_yield(lua_State *L)
3116{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003117 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
3118 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003119}
3120
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003121/* This function change the nice of the currently executed
3122 * task. It is used set low or high priority at the current
3123 * task.
3124 */
Willy Tarreau59551662015-03-10 14:23:13 +01003125__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003126{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003127 struct hlua *hlua;
3128 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003129
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003130 MAY_LJMP(check_args(L, 1, "set_nice"));
3131 hlua = hlua_gethlua(L);
3132 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003133
3134 /* If he task is not set, I'm in a start mode. */
3135 if (!hlua || !hlua->task)
3136 return 0;
3137
3138 if (nice < -1024)
3139 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003140 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003141 nice = 1024;
3142
3143 hlua->task->nice = nice;
3144 return 0;
3145}
3146
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003147/* This function is used as a calback of a task. It is called by the
3148 * HAProxy task subsystem when the task is awaked. The LUA runtime can
3149 * return an E_AGAIN signal, the emmiter of this signal must set a
3150 * signal to wake the task.
3151 */
3152static struct task *hlua_process_task(struct task *task)
3153{
3154 struct hlua *hlua = task->context;
3155 enum hlua_exec status;
3156
3157 /* We need to remove the task from the wait queue before executing
3158 * the Lua code because we don't know if it needs to wait for
3159 * another timer or not in the case of E_AGAIN.
3160 */
3161 task_delete(task);
3162
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003163 /* If it is the first call to the task, we must initialize the
3164 * execution timeouts.
3165 */
3166 if (!HLUA_IS_RUNNING(hlua))
3167 hlua->expire = tick_add(now_ms, hlua_timeout_task);
3168
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003169 /* Execute the Lua code. */
3170 status = hlua_ctx_resume(hlua, 1);
3171
3172 switch (status) {
3173 /* finished or yield */
3174 case HLUA_E_OK:
3175 hlua_ctx_destroy(hlua);
3176 task_delete(task);
3177 task_free(task);
3178 break;
3179
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003180 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
3181 if (hlua->wake_time != TICK_ETERNITY)
3182 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003183 break;
3184
3185 /* finished with error. */
3186 case HLUA_E_ERRMSG:
3187 send_log(NULL, LOG_ERR, "Lua task: %s.", lua_tostring(hlua->T, -1));
3188 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3189 Alert("Lua task: %s.\n", lua_tostring(hlua->T, -1));
3190 hlua_ctx_destroy(hlua);
3191 task_delete(task);
3192 task_free(task);
3193 break;
3194
3195 case HLUA_E_ERR:
3196 default:
3197 send_log(NULL, LOG_ERR, "Lua task: unknown error.");
3198 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3199 Alert("Lua task: unknown error.\n");
3200 hlua_ctx_destroy(hlua);
3201 task_delete(task);
3202 task_free(task);
3203 break;
3204 }
3205 return NULL;
3206}
3207
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003208/* This function is an LUA binding that register LUA function to be
3209 * executed after the HAProxy configuration parsing and before the
3210 * HAProxy scheduler starts. This function expect only one LUA
3211 * argument that is a function. This function returns nothing, but
3212 * throws if an error is encountered.
3213 */
3214__LJMP static int hlua_register_init(lua_State *L)
3215{
3216 struct hlua_init_function *init;
3217 int ref;
3218
3219 MAY_LJMP(check_args(L, 1, "register_init"));
3220
3221 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3222
3223 init = malloc(sizeof(*init));
3224 if (!init)
3225 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3226
3227 init->function_ref = ref;
3228 LIST_ADDQ(&hlua_init_functions, &init->l);
3229 return 0;
3230}
3231
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003232/* This functio is an LUA binding. It permits to register a task
3233 * executed in parallel of the main HAroxy activity. The task is
3234 * created and it is set in the HAProxy scheduler. It can be called
3235 * from the "init" section, "post init" or during the runtime.
3236 *
3237 * Lua prototype:
3238 *
3239 * <none> core.register_task(<function>)
3240 */
3241static int hlua_register_task(lua_State *L)
3242{
3243 struct hlua *hlua;
3244 struct task *task;
3245 int ref;
3246
3247 MAY_LJMP(check_args(L, 1, "register_task"));
3248
3249 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3250
3251 hlua = malloc(sizeof(*hlua));
3252 if (!hlua)
3253 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3254
3255 task = task_new();
3256 task->context = hlua;
3257 task->process = hlua_process_task;
3258
3259 if (!hlua_ctx_init(hlua, task))
3260 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3261
3262 /* Restore the function in the stack. */
3263 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
3264 hlua->nargs = 0;
3265
3266 /* Schedule task. */
3267 task_schedule(task, now_ms);
3268
3269 return 0;
3270}
3271
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003272/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
3273 * doesn't allow "yield" functions because the HAProxy engine cannot
3274 * resume converters.
3275 */
3276static int hlua_sample_conv_wrapper(struct session *session, const struct arg *arg_p,
3277 struct sample *smp, void *private)
3278{
3279 struct hlua_function *fcn = (struct hlua_function *)private;
3280
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003281 /* In the execution wrappers linked with a session, the
3282 * Lua context can be not initialized. This behavior
3283 * permits to save performances because a systematic
3284 * Lua initialization cause 5% performances loss.
3285 */
3286 if (!session->hlua.T && !hlua_ctx_init(&session->hlua, session->task)) {
3287 send_log(session->be, LOG_ERR, "Lua converter '%s': can't initialize Lua context.", fcn->name);
3288 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3289 Alert("Lua converter '%s': can't initialize Lua context.\n", fcn->name);
3290 return 0;
3291 }
3292
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003293 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003294 if (!HLUA_IS_RUNNING(&session->hlua)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003295 /* Check stack available size. */
3296 if (!lua_checkstack(session->hlua.T, 1)) {
3297 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
3298 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3299 Alert("Lua converter '%s': full stack.\n", fcn->name);
3300 return 0;
3301 }
3302
3303 /* Restore the function in the stack. */
3304 lua_rawgeti(session->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
3305
3306 /* convert input sample and pust-it in the stack. */
3307 if (!lua_checkstack(session->hlua.T, 1)) {
3308 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
3309 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3310 Alert("Lua converter '%s': full stack.\n", fcn->name);
3311 return 0;
3312 }
3313 hlua_smp2lua(session->hlua.T, smp);
3314 session->hlua.nargs = 2;
3315
3316 /* push keywords in the stack. */
3317 if (arg_p) {
3318 for (; arg_p->type != ARGT_STOP; arg_p++) {
3319 if (!lua_checkstack(session->hlua.T, 1)) {
3320 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
3321 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3322 Alert("Lua converter '%s': full stack.\n", fcn->name);
3323 return 0;
3324 }
3325 hlua_arg2lua(session->hlua.T, arg_p);
3326 session->hlua.nargs++;
3327 }
3328 }
3329
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003330 /* We must initialize the execution timeouts. */
3331 session->hlua.expire = tick_add(now_ms, hlua_timeout_session);
3332
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003333 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003334 HLUA_SET_RUN(&session->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003335 }
3336
3337 /* Execute the function. */
3338 switch (hlua_ctx_resume(&session->hlua, 0)) {
3339 /* finished. */
3340 case HLUA_E_OK:
3341 /* Convert the returned value in sample. */
3342 hlua_lua2smp(session->hlua.T, -1, smp);
3343 lua_pop(session->hlua.T, 1);
3344 return 1;
3345
3346 /* yield. */
3347 case HLUA_E_AGAIN:
3348 send_log(session->be, LOG_ERR, "Lua converter '%s': cannot use yielded functions.", fcn->name);
3349 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3350 Alert("Lua converter '%s': cannot use yielded functions.\n", fcn->name);
3351 return 0;
3352
3353 /* finished with error. */
3354 case HLUA_E_ERRMSG:
3355 /* Display log. */
3356 send_log(session->be, LOG_ERR, "Lua converter '%s': %s.", fcn->name, lua_tostring(session->hlua.T, -1));
3357 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3358 Alert("Lua converter '%s': %s.\n", fcn->name, lua_tostring(session->hlua.T, -1));
3359 lua_pop(session->hlua.T, 1);
3360 return 0;
3361
3362 case HLUA_E_ERR:
3363 /* Display log. */
3364 send_log(session->be, LOG_ERR, "Lua converter '%s' returns an unknown error.", fcn->name);
3365 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3366 Alert("Lua converter '%s' returns an unknown error.\n", fcn->name);
3367
3368 default:
3369 return 0;
3370 }
3371}
3372
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003373/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
3374 * doesn't allow "yield" functions because the HAProxy engine cannot
3375 * resume sample-fetches.
3376 */
3377static int hlua_sample_fetch_wrapper(struct proxy *px, struct session *s, void *l7,
3378 unsigned int opt, const struct arg *arg_p,
3379 struct sample *smp, const char *kw, void *private)
3380{
3381 struct hlua_function *fcn = (struct hlua_function *)private;
3382
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003383 /* In the execution wrappers linked with a session, the
3384 * Lua context can be not initialized. This behavior
3385 * permits to save performances because a systematic
3386 * Lua initialization cause 5% performances loss.
3387 */
3388 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
3389 send_log(s->be, LOG_ERR, "Lua sample-fetch '%s': can't initialize Lua context.", fcn->name);
3390 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3391 Alert("Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
3392 return 0;
3393 }
3394
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003395 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003396 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003397 /* Check stack available size. */
3398 if (!lua_checkstack(s->hlua.T, 2)) {
3399 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3400 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3401 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3402 return 0;
3403 }
3404
3405 /* Restore the function in the stack. */
3406 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
3407
3408 /* push arguments in the stack. */
3409 if (!hlua_txn_new(s->hlua.T, s, px, l7)) {
3410 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3411 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3412 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3413 return 0;
3414 }
3415 s->hlua.nargs = 1;
3416
3417 /* push keywords in the stack. */
3418 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
3419 /* Check stack available size. */
3420 if (!lua_checkstack(s->hlua.T, 1)) {
3421 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3422 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3423 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3424 return 0;
3425 }
3426 if (!lua_checkstack(s->hlua.T, 1)) {
3427 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3428 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3429 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3430 return 0;
3431 }
3432 hlua_arg2lua(s->hlua.T, arg_p);
3433 s->hlua.nargs++;
3434 }
3435
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003436 /* We must initialize the execution timeouts. */
3437 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
3438
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003439 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003440 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003441 }
3442
3443 /* Execute the function. */
3444 switch (hlua_ctx_resume(&s->hlua, 0)) {
3445 /* finished. */
3446 case HLUA_E_OK:
3447 /* Convert the returned value in sample. */
3448 hlua_lua2smp(s->hlua.T, -1, smp);
3449 lua_pop(s->hlua.T, 1);
3450
3451 /* Set the end of execution flag. */
3452 smp->flags &= ~SMP_F_MAY_CHANGE;
3453 return 1;
3454
3455 /* yield. */
3456 case HLUA_E_AGAIN:
3457 send_log(px, LOG_ERR, "Lua sample-fetch '%s': cannot use yielded functions.", fcn->name);
3458 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3459 Alert("Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
3460 return 0;
3461
3462 /* finished with error. */
3463 case HLUA_E_ERRMSG:
3464 /* Display log. */
3465 send_log(px, LOG_ERR, "Lua sample-fetch '%s': %s.", fcn->name, lua_tostring(s->hlua.T, -1));
3466 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3467 Alert("Lua sample-fetch '%s': %s.\n", fcn->name, lua_tostring(s->hlua.T, -1));
3468 lua_pop(s->hlua.T, 1);
3469 return 0;
3470
3471 case HLUA_E_ERR:
3472 /* Display log. */
3473 send_log(px, LOG_ERR, "Lua sample-fetch '%s' returns an unknown error.", fcn->name);
3474 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3475 Alert("Lua sample-fetch '%s': returns an unknown error.\n", fcn->name);
3476
3477 default:
3478 return 0;
3479 }
3480}
3481
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003482/* This function is an LUA binding used for registering
3483 * "sample-conv" functions. It expects a converter name used
3484 * in the haproxy configuration file, and an LUA function.
3485 */
3486__LJMP static int hlua_register_converters(lua_State *L)
3487{
3488 struct sample_conv_kw_list *sck;
3489 const char *name;
3490 int ref;
3491 int len;
3492 struct hlua_function *fcn;
3493
3494 MAY_LJMP(check_args(L, 2, "register_converters"));
3495
3496 /* First argument : converter name. */
3497 name = MAY_LJMP(luaL_checkstring(L, 1));
3498
3499 /* Second argument : lua function. */
3500 ref = MAY_LJMP(hlua_checkfunction(L, 2));
3501
3502 /* Allocate and fill the sample fetch keyword struct. */
3503 sck = malloc(sizeof(struct sample_conv_kw_list) +
3504 sizeof(struct sample_conv) * 2);
3505 if (!sck)
3506 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3507 fcn = malloc(sizeof(*fcn));
3508 if (!fcn)
3509 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3510
3511 /* Fill fcn. */
3512 fcn->name = strdup(name);
3513 if (!fcn->name)
3514 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3515 fcn->function_ref = ref;
3516
3517 /* List head */
3518 sck->list.n = sck->list.p = NULL;
3519
3520 /* converter keyword. */
3521 len = strlen("lua.") + strlen(name) + 1;
3522 sck->kw[0].kw = malloc(len);
3523 if (!sck->kw[0].kw)
3524 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3525
3526 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
3527 sck->kw[0].process = hlua_sample_conv_wrapper;
3528 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
3529 sck->kw[0].val_args = NULL;
3530 sck->kw[0].in_type = SMP_T_STR;
3531 sck->kw[0].out_type = SMP_T_STR;
3532 sck->kw[0].private = fcn;
3533
3534 /* End of array. */
3535 memset(&sck->kw[1], 0, sizeof(struct sample_conv));
3536
3537 /* Register this new converter */
3538 sample_register_convs(sck);
3539
3540 return 0;
3541}
3542
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003543/* This fucntion is an LUA binding used for registering
3544 * "sample-fetch" functions. It expects a converter name used
3545 * in the haproxy configuration file, and an LUA function.
3546 */
3547__LJMP static int hlua_register_fetches(lua_State *L)
3548{
3549 const char *name;
3550 int ref;
3551 int len;
3552 struct sample_fetch_kw_list *sfk;
3553 struct hlua_function *fcn;
3554
3555 MAY_LJMP(check_args(L, 2, "register_fetches"));
3556
3557 /* First argument : sample-fetch name. */
3558 name = MAY_LJMP(luaL_checkstring(L, 1));
3559
3560 /* Second argument : lua function. */
3561 ref = MAY_LJMP(hlua_checkfunction(L, 2));
3562
3563 /* Allocate and fill the sample fetch keyword struct. */
3564 sfk = malloc(sizeof(struct sample_fetch_kw_list) +
3565 sizeof(struct sample_fetch) * 2);
3566 if (!sfk)
3567 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3568 fcn = malloc(sizeof(*fcn));
3569 if (!fcn)
3570 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3571
3572 /* Fill fcn. */
3573 fcn->name = strdup(name);
3574 if (!fcn->name)
3575 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3576 fcn->function_ref = ref;
3577
3578 /* List head */
3579 sfk->list.n = sfk->list.p = NULL;
3580
3581 /* sample-fetch keyword. */
3582 len = strlen("lua.") + strlen(name) + 1;
3583 sfk->kw[0].kw = malloc(len);
3584 if (!sfk->kw[0].kw)
3585 return luaL_error(L, "lua out of memory error.");
3586
3587 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
3588 sfk->kw[0].process = hlua_sample_fetch_wrapper;
3589 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
3590 sfk->kw[0].val_args = NULL;
3591 sfk->kw[0].out_type = SMP_T_STR;
3592 sfk->kw[0].use = SMP_USE_HTTP_ANY;
3593 sfk->kw[0].val = 0;
3594 sfk->kw[0].private = fcn;
3595
3596 /* End of array. */
3597 memset(&sfk->kw[1], 0, sizeof(struct sample_fetch));
3598
3599 /* Register this new fetch. */
3600 sample_register_fetches(sfk);
3601
3602 return 0;
3603}
3604
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003605/* global {tcp|http}-request parser. Return 1 in succes case, else return 0. */
3606static int hlua_parse_rule(const char **args, int *cur_arg, struct proxy *px,
3607 struct hlua_rule **rule_p, char **err)
3608{
3609 struct hlua_rule *rule;
3610
3611 /* Memory for the rule. */
3612 rule = malloc(sizeof(*rule));
3613 if (!rule) {
3614 memprintf(err, "out of memory error");
3615 return 0;
3616 }
3617 *rule_p = rule;
3618
3619 /* The requiered arg is a function name. */
3620 if (!args[*cur_arg]) {
3621 memprintf(err, "expect Lua function name");
3622 return 0;
3623 }
3624
3625 /* Lookup for the symbol, and check if it is a function. */
3626 lua_getglobal(gL.T, args[*cur_arg]);
3627 if (lua_isnil(gL.T, -1)) {
3628 lua_pop(gL.T, 1);
3629 memprintf(err, "Lua function '%s' not found", args[*cur_arg]);
3630 return 0;
3631 }
3632 if (!lua_isfunction(gL.T, -1)) {
3633 lua_pop(gL.T, 1);
3634 memprintf(err, "'%s' is not a function", args[*cur_arg]);
3635 return 0;
3636 }
3637
3638 /* Reference the Lua function and store the reference. */
3639 rule->fcn.function_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
3640 rule->fcn.name = strdup(args[*cur_arg]);
3641 if (!rule->fcn.name) {
3642 memprintf(err, "out of memory error.");
3643 return 0;
3644 }
3645 (*cur_arg)++;
3646
3647 /* TODO: later accept arguments. */
3648 rule->args = NULL;
3649
3650 return 1;
3651}
3652
3653/* This function is a wrapper to execute each LUA function declared
3654 * as an action wrapper during the initialisation period. This function
3655 * return 1 if the processing is finished (with oe without error) and
3656 * return 0 if the function must be called again because the LUA
3657 * returns a yield.
3658 */
3659static int hlua_request_act_wrapper(struct hlua_rule *rule, struct proxy *px,
3660 struct session *s, struct http_txn *http_txn,
3661 unsigned int analyzer)
3662{
3663 char **arg;
3664
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003665 /* In the execution wrappers linked with a session, the
3666 * Lua context can be not initialized. This behavior
3667 * permits to save performances because a systematic
3668 * Lua initialization cause 5% performances loss.
3669 */
3670 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
3671 send_log(px, LOG_ERR, "Lua action '%s': can't initialize Lua context.", rule->fcn.name);
3672 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3673 Alert("Lua action '%s': can't initialize Lua context.\n", rule->fcn.name);
3674 return 0;
3675 }
3676
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003677 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003678 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003679 /* Check stack available size. */
3680 if (!lua_checkstack(s->hlua.T, 1)) {
3681 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
3682 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3683 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
3684 return 0;
3685 }
3686
3687 /* Restore the function in the stack. */
3688 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->fcn.function_ref);
3689
3690 /* Create and and push object session in the stack. */
3691 if (!hlua_txn_new(s->hlua.T, s, px, http_txn)) {
3692 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
3693 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3694 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
3695 return 0;
3696 }
3697 s->hlua.nargs = 1;
3698
3699 /* push keywords in the stack. */
3700 for (arg = rule->args; arg && *arg; arg++) {
3701 if (!lua_checkstack(s->hlua.T, 1)) {
3702 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
3703 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3704 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
3705 return 0;
3706 }
3707 lua_pushstring(s->hlua.T, *arg);
3708 s->hlua.nargs++;
3709 }
3710
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003711 /* We must initialize the execution timeouts. */
3712 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
3713
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003714 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003715 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003716 }
3717
3718 /* Execute the function. */
3719 switch (hlua_ctx_resume(&s->hlua, 1)) {
3720 /* finished. */
3721 case HLUA_E_OK:
3722 return 1;
3723
3724 /* yield. */
3725 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003726 /* Set timeout in the required channel. */
3727 if (s->hlua.wake_time != TICK_ETERNITY) {
3728 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01003729 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003730 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01003731 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003732 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003733 /* Some actions can be wake up when a "write" event
3734 * is detected on a response channel. This is useful
3735 * only for actions targetted on the requests.
3736 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003737 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01003738 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01003739 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01003740 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003741 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003742 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01003743 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003744 return 0;
3745
3746 /* finished with error. */
3747 case HLUA_E_ERRMSG:
3748 /* Display log. */
3749 send_log(px, LOG_ERR, "Lua function '%s': %s.", rule->fcn.name, lua_tostring(s->hlua.T, -1));
3750 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3751 Alert("Lua function '%s': %s.\n", rule->fcn.name, lua_tostring(s->hlua.T, -1));
3752 lua_pop(s->hlua.T, 1);
3753 return 1;
3754
3755 case HLUA_E_ERR:
3756 /* Display log. */
3757 send_log(px, LOG_ERR, "Lua function '%s' return an unknown error.", rule->fcn.name);
3758 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3759 Alert("Lua function '%s' return an unknown error.\n", rule->fcn.name);
3760
3761 default:
3762 return 1;
3763 }
3764}
3765
3766/* Lua execution wrapper for "tcp-request". This function uses
3767 * "hlua_request_act_wrapper" for executing the LUA code.
3768 */
3769int hlua_tcp_req_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
3770 struct session *s)
3771{
3772 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
3773 px, s, NULL, AN_REQ_INSPECT_FE);
3774}
3775
3776/* Lua execution wrapper for "tcp-response". This function uses
3777 * "hlua_request_act_wrapper" for executing the LUA code.
3778 */
3779int hlua_tcp_res_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
3780 struct session *s)
3781{
3782 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
3783 px, s, NULL, AN_RES_INSPECT);
3784}
3785
3786/* Lua execution wrapper for http-request.
3787 * This function uses "hlua_request_act_wrapper" for executing
3788 * the LUA code.
3789 */
3790int hlua_http_req_act_wrapper(struct http_req_rule *rule, struct proxy *px,
3791 struct session *s, struct http_txn *http_txn)
3792{
3793 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
3794 s, http_txn, AN_REQ_HTTP_PROCESS_FE);
3795}
3796
3797/* Lua execution wrapper for http-response.
3798 * This function uses "hlua_request_act_wrapper" for executing
3799 * the LUA code.
3800 */
3801int hlua_http_res_act_wrapper(struct http_res_rule *rule, struct proxy *px,
3802 struct session *s, struct http_txn *http_txn)
3803{
3804 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
3805 s, http_txn, AN_RES_HTTP_PROCESS_BE);
3806}
3807
3808/* tcp-request <*> configuration wrapper. */
3809static int tcp_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3810 struct tcp_rule *rule, char **err)
3811{
3812 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003813 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003814 rule->action = TCP_ACT_CUSTOM;
3815 rule->action_ptr = hlua_tcp_req_act_wrapper;
3816 return 1;
3817}
3818
3819/* tcp-response <*> configuration wrapper. */
3820static int tcp_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3821 struct tcp_rule *rule, char **err)
3822{
3823 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003824 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003825 rule->action = TCP_ACT_CUSTOM;
3826 rule->action_ptr = hlua_tcp_res_act_wrapper;
3827 return 1;
3828}
3829
3830/* http-request <*> configuration wrapper. */
3831static int http_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3832 struct http_req_rule *rule, char **err)
3833{
3834 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
3835 return -1;
3836 rule->action = HTTP_REQ_ACT_CUSTOM_CONT;
3837 rule->action_ptr = hlua_http_req_act_wrapper;
3838 return 1;
3839}
3840
3841/* http-response <*> configuration wrapper. */
3842static int http_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3843 struct http_res_rule *rule, char **err)
3844{
3845 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
3846 return -1;
3847 rule->action = HTTP_RES_ACT_CUSTOM_CONT;
3848 rule->action_ptr = hlua_http_res_act_wrapper;
3849 return 1;
3850}
3851
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003852static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
3853 struct proxy *defpx, const char *file, int line,
3854 char **err, unsigned int *timeout)
3855{
3856 const char *error;
3857
3858 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
3859 if (error && *error != '\0') {
3860 memprintf(err, "%s: invalid timeout", args[0]);
3861 return -1;
3862 }
3863 return 0;
3864}
3865
3866static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
3867 struct proxy *defpx, const char *file, int line,
3868 char **err)
3869{
3870 return hlua_read_timeout(args, section_type, curpx, defpx,
3871 file, line, err, &hlua_timeout_session);
3872}
3873
3874static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
3875 struct proxy *defpx, const char *file, int line,
3876 char **err)
3877{
3878 return hlua_read_timeout(args, section_type, curpx, defpx,
3879 file, line, err, &hlua_timeout_task);
3880}
3881
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01003882static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
3883 struct proxy *defpx, const char *file, int line,
3884 char **err)
3885{
3886 char *error;
3887
3888 hlua_nb_instruction = strtoll(args[1], &error, 10);
3889 if (*error != '\0') {
3890 memprintf(err, "%s: invalid number", args[0]);
3891 return -1;
3892 }
3893 return 0;
3894}
3895
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01003896/* This function is called by the main configuration key "lua-load". It loads and
3897 * execute an lua file during the parsing of the HAProxy configuration file. It is
3898 * the main lua entry point.
3899 *
3900 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
3901 * occured, otherwise it returns 0.
3902 *
3903 * In some error case, LUA set an error message in top of the stack. This function
3904 * returns this error message in the HAProxy logs and pop it from the stack.
3905 */
3906static int hlua_load(char **args, int section_type, struct proxy *curpx,
3907 struct proxy *defpx, const char *file, int line,
3908 char **err)
3909{
3910 int error;
3911
3912 /* Just load and compile the file. */
3913 error = luaL_loadfile(gL.T, args[1]);
3914 if (error) {
3915 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
3916 lua_pop(gL.T, 1);
3917 return -1;
3918 }
3919
3920 /* If no syntax error where detected, execute the code. */
3921 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
3922 switch (error) {
3923 case LUA_OK:
3924 break;
3925 case LUA_ERRRUN:
3926 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
3927 lua_pop(gL.T, 1);
3928 return -1;
3929 case LUA_ERRMEM:
3930 memprintf(err, "lua out of memory error\n");
3931 return -1;
3932 case LUA_ERRERR:
3933 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
3934 lua_pop(gL.T, 1);
3935 return -1;
3936 case LUA_ERRGCMM:
3937 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
3938 lua_pop(gL.T, 1);
3939 return -1;
3940 default:
3941 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
3942 lua_pop(gL.T, 1);
3943 return -1;
3944 }
3945
3946 return 0;
3947}
3948
3949/* configuration keywords declaration */
3950static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003951 { CFG_GLOBAL, "lua-load", hlua_load },
3952 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
3953 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01003954 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01003955 { 0, NULL, NULL },
3956}};
3957
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003958static struct http_req_action_kw_list http_req_kws = {"lua", { }, {
3959 { "lua", http_req_action_register_lua },
3960 { NULL, NULL }
3961}};
3962
3963static struct http_res_action_kw_list http_res_kws = {"lua", { }, {
3964 { "lua", http_res_action_register_lua },
3965 { NULL, NULL }
3966}};
3967
3968static struct tcp_action_kw_list tcp_req_cont_kws = {"lua", { }, {
3969 { "lua", tcp_req_action_register_lua },
3970 { NULL, NULL }
3971}};
3972
3973static struct tcp_action_kw_list tcp_res_cont_kws = {"lua", { }, {
3974 { "lua", tcp_res_action_register_lua },
3975 { NULL, NULL }
3976}};
3977
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003978int hlua_post_init()
3979{
3980 struct hlua_init_function *init;
3981 const char *msg;
3982 enum hlua_exec ret;
3983
3984 list_for_each_entry(init, &hlua_init_functions, l) {
3985 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
3986 ret = hlua_ctx_resume(&gL, 0);
3987 switch (ret) {
3988 case HLUA_E_OK:
3989 lua_pop(gL.T, -1);
3990 return 1;
3991 case HLUA_E_AGAIN:
3992 Alert("lua init: yield not allowed.\n");
3993 return 0;
3994 case HLUA_E_ERRMSG:
3995 msg = lua_tostring(gL.T, -1);
3996 Alert("lua init: %s.\n", msg);
3997 return 0;
3998 case HLUA_E_ERR:
3999 default:
4000 Alert("lua init: unknown runtime error.\n");
4001 return 0;
4002 }
4003 }
4004 return 1;
4005}
4006
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01004007void hlua_init(void)
4008{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004009 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004010 int idx;
4011 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004012 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004013 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004014#ifdef USE_OPENSSL
4015 char *args[4];
4016 struct srv_kw *kw;
4017 int tmp_error;
4018 char *error;
4019#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004020
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004021 /* Initialise com signals pool session. */
4022 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
4023
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004024 /* Initialise sleep pool. */
4025 pool2_hlua_sleep = create_pool("hlua_sleep", sizeof(struct hlua_sleep), MEM_F_SHARED);
4026
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004027 /* Register configuration keywords. */
4028 cfg_register_keywords(&cfg_kws);
4029
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004030 /* Register custom HTTP rules. */
4031 http_req_keywords_register(&http_req_kws);
4032 http_res_keywords_register(&http_res_kws);
4033 tcp_req_cont_keywords_register(&tcp_req_cont_kws);
4034 tcp_res_cont_keywords_register(&tcp_res_cont_kws);
4035
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004036 /* Init main lua stack. */
4037 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004038 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004039 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004040 gL.T = luaL_newstate();
4041 hlua_sethlua(&gL);
4042 gL.Tref = LUA_REFNIL;
4043 gL.task = NULL;
4044
4045 /* Initialise lua. */
4046 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004047
4048 /*
4049 *
4050 * Create "core" object.
4051 *
4052 */
4053
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01004054 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004055 lua_newtable(gL.T);
4056
4057 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004058 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004059 hlua_class_const_int(gL.T, log_levels[i], i);
4060
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004061 /* Register special functions. */
4062 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004063 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004064 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004065 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004066 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01004067 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004068 hlua_class_function(gL.T, "sleep", hlua_sleep);
4069 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01004070 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
4071 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
4072 hlua_class_function(gL.T, "set_map", hlua_set_map);
4073 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004074 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004075
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004076 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004077
4078 /*
4079 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004080 * Register class Channel
4081 *
4082 */
4083
4084 /* Create and fill the metatable. */
4085 lua_newtable(gL.T);
4086
4087 /* Create and fille the __index entry. */
4088 lua_pushstring(gL.T, "__index");
4089 lua_newtable(gL.T);
4090
4091 /* Register . */
4092 hlua_class_function(gL.T, "get", hlua_channel_get);
4093 hlua_class_function(gL.T, "dup", hlua_channel_dup);
4094 hlua_class_function(gL.T, "getline", hlua_channel_getline);
4095 hlua_class_function(gL.T, "set", hlua_channel_set);
4096 hlua_class_function(gL.T, "append", hlua_channel_append);
4097 hlua_class_function(gL.T, "send", hlua_channel_send);
4098 hlua_class_function(gL.T, "forward", hlua_channel_forward);
4099 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
4100 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
4101
4102 lua_settable(gL.T, -3);
4103
4104 /* Register previous table in the registry with reference and named entry. */
4105 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4106 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
4107 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4108
4109 /*
4110 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004111 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004112 *
4113 */
4114
4115 /* Create and fill the metatable. */
4116 lua_newtable(gL.T);
4117
4118 /* Create and fille the __index entry. */
4119 lua_pushstring(gL.T, "__index");
4120 lua_newtable(gL.T);
4121
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004122 /* Browse existing fetches and create the associated
4123 * object method.
4124 */
4125 sf = NULL;
4126 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
4127
4128 /* Dont register the keywork if the arguments check function are
4129 * not safe during the runtime.
4130 */
4131 if ((sf->val_args != NULL) &&
4132 (sf->val_args != val_payload_lv) &&
4133 (sf->val_args != val_hdr))
4134 continue;
4135
4136 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4137 * by an underscore.
4138 */
4139 strncpy(trash.str, sf->kw, trash.size);
4140 trash.str[trash.size - 1] = '\0';
4141 for (p = trash.str; *p; p++)
4142 if (*p == '.' || *p == '-' || *p == '+')
4143 *p = '_';
4144
4145 /* Register the function. */
4146 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01004147 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004148 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
4149 lua_settable(gL.T, -3);
4150 }
4151
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004152 lua_settable(gL.T, -3);
4153
4154 /* Register previous table in the registry with reference and named entry. */
4155 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4156 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
4157 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4158
4159 /*
4160 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004161 * Register class Converters
4162 *
4163 */
4164
4165 /* Create and fill the metatable. */
4166 lua_newtable(gL.T);
4167
4168 /* Create and fill the __index entry. */
4169 lua_pushstring(gL.T, "__index");
4170 lua_newtable(gL.T);
4171
4172 /* Browse existing converters and create the associated
4173 * object method.
4174 */
4175 sc = NULL;
4176 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
4177 /* Dont register the keywork if the arguments check function are
4178 * not safe during the runtime.
4179 */
4180 if (sc->val_args != NULL)
4181 continue;
4182
4183 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4184 * by an underscore.
4185 */
4186 strncpy(trash.str, sc->kw, trash.size);
4187 trash.str[trash.size - 1] = '\0';
4188 for (p = trash.str; *p; p++)
4189 if (*p == '.' || *p == '-' || *p == '+')
4190 *p = '_';
4191
4192 /* Register the function. */
4193 lua_pushstring(gL.T, trash.str);
4194 lua_pushlightuserdata(gL.T, sc);
4195 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
4196 lua_settable(gL.T, -3);
4197 }
4198
4199 lua_settable(gL.T, -3);
4200
4201 /* Register previous table in the registry with reference and named entry. */
4202 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4203 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
4204 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4205
4206 /*
4207 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004208 * Register class TXN
4209 *
4210 */
4211
4212 /* Create and fill the metatable. */
4213 lua_newtable(gL.T);
4214
4215 /* Create and fille the __index entry. */
4216 lua_pushstring(gL.T, "__index");
4217 lua_newtable(gL.T);
4218
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004219 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01004220 hlua_class_function(gL.T, "get_headers", hlua_session_get_headers);
4221 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
4222 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004223 hlua_class_function(gL.T, "close", hlua_txn_close);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004224
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004225 lua_settable(gL.T, -3);
4226
4227 /* Register previous table in the registry with reference and named entry. */
4228 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4229 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
4230 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004231
4232 /*
4233 *
4234 * Register class Socket
4235 *
4236 */
4237
4238 /* Create and fill the metatable. */
4239 lua_newtable(gL.T);
4240
4241 /* Create and fille the __index entry. */
4242 lua_pushstring(gL.T, "__index");
4243 lua_newtable(gL.T);
4244
Baptiste Assmann84bb4932015-03-02 21:40:06 +01004245#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004246 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01004247#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004248 hlua_class_function(gL.T, "connect", hlua_socket_connect);
4249 hlua_class_function(gL.T, "send", hlua_socket_send);
4250 hlua_class_function(gL.T, "receive", hlua_socket_receive);
4251 hlua_class_function(gL.T, "close", hlua_socket_close);
4252 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
4253 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
4254 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
4255 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
4256
4257 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
4258
4259 /* Register the garbage collector entry. */
4260 lua_pushstring(gL.T, "__gc");
4261 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
4262 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
4263
4264 /* Register previous table in the registry with reference and named entry. */
4265 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4266 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4267 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
4268 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
4269
4270 /* Proxy and server configuration initialisation. */
4271 memset(&socket_proxy, 0, sizeof(socket_proxy));
4272 init_new_proxy(&socket_proxy);
4273 socket_proxy.parent = NULL;
4274 socket_proxy.last_change = now.tv_sec;
4275 socket_proxy.id = "LUA-SOCKET";
4276 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
4277 socket_proxy.maxconn = 0;
4278 socket_proxy.accept = NULL;
4279 socket_proxy.options2 |= PR_O2_INDEPSTR;
4280 socket_proxy.srv = NULL;
4281 socket_proxy.conn_retries = 0;
4282 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
4283
4284 /* Init TCP server: unchanged parameters */
4285 memset(&socket_tcp, 0, sizeof(socket_tcp));
4286 socket_tcp.next = NULL;
4287 socket_tcp.proxy = &socket_proxy;
4288 socket_tcp.obj_type = OBJ_TYPE_SERVER;
4289 LIST_INIT(&socket_tcp.actconns);
4290 LIST_INIT(&socket_tcp.pendconns);
4291 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
4292 socket_tcp.last_change = 0;
4293 socket_tcp.id = "LUA-TCP-CONN";
4294 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
4295 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
4296 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
4297
4298 /* XXX: Copy default parameter from default server,
4299 * but the default server is not initialized.
4300 */
4301 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
4302 socket_tcp.minconn = socket_proxy.defsrv.minconn;
4303 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
4304 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
4305 socket_tcp.onerror = socket_proxy.defsrv.onerror;
4306 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
4307 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
4308 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
4309 socket_tcp.uweight = socket_proxy.defsrv.iweight;
4310 socket_tcp.iweight = socket_proxy.defsrv.iweight;
4311
4312 socket_tcp.check.status = HCHK_STATUS_INI;
4313 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
4314 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
4315 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
4316 socket_tcp.check.server = &socket_tcp;
4317
4318 socket_tcp.agent.status = HCHK_STATUS_INI;
4319 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
4320 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
4321 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
4322 socket_tcp.agent.server = &socket_tcp;
4323
4324 socket_tcp.xprt = &raw_sock;
4325
4326#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004327 /* Init TCP server: unchanged parameters */
4328 memset(&socket_ssl, 0, sizeof(socket_ssl));
4329 socket_ssl.next = NULL;
4330 socket_ssl.proxy = &socket_proxy;
4331 socket_ssl.obj_type = OBJ_TYPE_SERVER;
4332 LIST_INIT(&socket_ssl.actconns);
4333 LIST_INIT(&socket_ssl.pendconns);
4334 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
4335 socket_ssl.last_change = 0;
4336 socket_ssl.id = "LUA-SSL-CONN";
4337 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
4338 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
4339 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
4340
4341 /* XXX: Copy default parameter from default server,
4342 * but the default server is not initialized.
4343 */
4344 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
4345 socket_ssl.minconn = socket_proxy.defsrv.minconn;
4346 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
4347 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
4348 socket_ssl.onerror = socket_proxy.defsrv.onerror;
4349 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
4350 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
4351 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
4352 socket_ssl.uweight = socket_proxy.defsrv.iweight;
4353 socket_ssl.iweight = socket_proxy.defsrv.iweight;
4354
4355 socket_ssl.check.status = HCHK_STATUS_INI;
4356 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
4357 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
4358 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
4359 socket_ssl.check.server = &socket_ssl;
4360
4361 socket_ssl.agent.status = HCHK_STATUS_INI;
4362 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
4363 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
4364 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
4365 socket_ssl.agent.server = &socket_ssl;
4366
4367 socket_ssl.xprt = &raw_sock;
4368
4369 args[0] = "ssl";
4370 args[1] = "verify";
4371 args[2] = "none";
4372 args[3] = NULL;
4373
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004374 for (idx = 0; idx < 3; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004375 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
4376 /*
4377 *
4378 * If the keyword is not known, we can search in the registered
4379 * server keywords. This is usefull to configure special SSL
4380 * features like client certificates and ssl_verify.
4381 *
4382 */
4383 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
4384 if (tmp_error != 0) {
4385 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
4386 abort(); /* This must be never arrives because the command line
4387 not editable by the user. */
4388 }
4389 idx += kw->skip;
4390 }
4391 }
4392
4393 /* Initialize SSL server. */
4394 if (socket_ssl.xprt == &ssl_sock) {
4395 socket_ssl.use_ssl = 1;
4396 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
4397 }
4398#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01004399}