blob: 5eaf2258d0f93a5a49555d2656adc007b94007c8 [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 FOURNIER2ba18a22015-01-23 14:07:08 +010075
Thierry FOURNIERbd413492015-03-03 16:52:26 +010076/* Global Lua execution timeout. By default Lua, execution linked
77 * with session (actions, sample-fetches and converters) have a
78 * short timeout. Lua linked with tasks doesn't have a timeout
79 * because a task may remain alive during all the haproxy execution.
80 */
81static unsigned int hlua_timeout_session = 4000; /* session timeout. */
82static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
83
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010084/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
85 * it is used for preventing infinite loops.
86 *
87 * I test the scheer with an infinite loop containing one incrementation
88 * and one test. I run this loop between 10 seconds, I raise a ceil of
89 * 710M loops from one interrupt each 9000 instructions, so I fix the value
90 * to one interrupt each 10 000 instructions.
91 *
92 * configured | Number of
93 * instructions | loops executed
94 * between two | in milions
95 * forced yields |
96 * ---------------+---------------
97 * 10 | 160
98 * 500 | 670
99 * 1000 | 680
100 * 5000 | 700
101 * 7000 | 700
102 * 8000 | 700
103 * 9000 | 710 <- ceil
104 * 10000 | 710
105 * 100000 | 710
106 * 1000000 | 710
107 *
108 */
109static unsigned int hlua_nb_instruction = 10000;
110
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100111/* These functions converts types between HAProxy internal args or
112 * sample and LUA types. Another function permits to check if the
113 * LUA stack contains arguments according with an required ARG_T
114 * format.
115 */
116static int hlua_arg2lua(lua_State *L, const struct arg *arg);
117static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
118__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp, unsigned int mask);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100119static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100120static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
121
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100122/* Used to check an Lua function type in the stack. It creates and
123 * returns a reference of the function. This function throws an
124 * error if the rgument is not a "function".
125 */
126__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
127{
128 if (!lua_isfunction(L, argno)) {
129 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
130 WILL_LJMP(luaL_argerror(L, argno, msg));
131 }
132 lua_pushvalue(L, argno);
133 return luaL_ref(L, LUA_REGISTRYINDEX);
134}
135
136/* The three following functions are useful for adding entries
137 * in a table. These functions takes a string and respectively an
138 * integer, a string or a function and add it to the table in the
139 * top of the stack.
140 *
141 * These functions throws an error if no more stack size is
142 * available.
143 */
144__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100145 int value)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100146{
147 if (!lua_checkstack(L, 2))
148 WILL_LJMP(luaL_error(L, "full stack"));
149 lua_pushstring(L, name);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100150 lua_pushinteger(L, value);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100151 lua_settable(L, -3);
152}
153__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
154 const char *value)
155{
156 if (!lua_checkstack(L, 2))
157 WILL_LJMP(luaL_error(L, "full stack"));
158 lua_pushstring(L, name);
159 lua_pushstring(L, value);
160 lua_settable(L, -3);
161}
162__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
163 int (*function)(lua_State *L))
164{
165 if (!lua_checkstack(L, 2))
166 WILL_LJMP(luaL_error(L, "full stack"));
167 lua_pushstring(L, name);
168 lua_pushcclosure(L, function, 0);
169 lua_settable(L, -3);
170}
171
172/* This function check the number of arguments available in the
173 * stack. If the number of arguments available is not the same
174 * then <nb> an error is throwed.
175 */
176__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
177{
178 if (lua_gettop(L) == nb)
179 return;
180 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
181}
182
183/* Return true if the data in stack[<ud>] is an object of
184 * type <class_ref>.
185 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100186static int hlua_metaistype(lua_State *L, int ud, int class_ref)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100187{
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100188 if (!lua_getmetatable(L, ud))
189 return 0;
190
191 lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
192 if (!lua_rawequal(L, -1, -2)) {
193 lua_pop(L, 2);
194 return 0;
195 }
196
197 lua_pop(L, 2);
198 return 1;
199}
200
201/* Return an object of the expected type, or throws an error. */
202__LJMP static void *hlua_checkudata(lua_State *L, int ud, int class_ref)
203{
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100204 void *p;
205
206 /* Check if the stack entry is an array. */
207 if (!lua_istable(L, ud))
208 WILL_LJMP(luaL_argerror(L, ud, NULL));
209 /* Check if the metadata have the expected type. */
210 if (!hlua_metaistype(L, ud, class_ref))
211 WILL_LJMP(luaL_argerror(L, ud, NULL));
212 /* Push on the stack at the entry [0] of the table. */
213 lua_rawgeti(L, ud, 0);
214 /* Check if this entry is userdata. */
215 p = lua_touserdata(L, -1);
216 if (!p)
217 WILL_LJMP(luaL_argerror(L, ud, NULL));
218 /* Remove the entry returned by lua_rawgeti(). */
219 lua_pop(L, 1);
220 /* Return the associated struct. */
221 return p;
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100222}
223
224/* This fucntion push an error string prefixed by the file name
225 * and the line number where the error is encountered.
226 */
227static int hlua_pusherror(lua_State *L, const char *fmt, ...)
228{
229 va_list argp;
230 va_start(argp, fmt);
231 luaL_where(L, 1);
232 lua_pushvfstring(L, fmt, argp);
233 va_end(argp);
234 lua_concat(L, 2);
235 return 1;
236}
237
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100238/* This function register a new signal. "lua" is the current lua
239 * execution context. It contains a pointer to the associated task.
240 * "link" is a list head attached to an other task that must be wake
241 * the lua task if an event occurs. This is useful with external
242 * events like TCP I/O or sleep functions. This funcion allocate
243 * memory for the signal.
244 */
245static int hlua_com_new(struct hlua *lua, struct list *link)
246{
247 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
248 if (!com)
249 return 0;
250 LIST_ADDQ(&lua->com, &com->purge_me);
251 LIST_ADDQ(link, &com->wake_me);
252 com->task = lua->task;
253 return 1;
254}
255
256/* This function purge all the pending signals when the LUA execution
257 * is finished. This prevent than a coprocess try to wake a deleted
258 * task. This function remove the memory associated to the signal.
259 */
260static void hlua_com_purge(struct hlua *lua)
261{
262 struct hlua_com *com, *back;
263
264 /* Delete all pending communication signals. */
265 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
266 LIST_DEL(&com->purge_me);
267 LIST_DEL(&com->wake_me);
268 pool_free2(pool2_hlua_com, com);
269 }
270}
271
272/* This function sends signals. It wakes all the tasks attached
273 * to a list head, and remove the signal, and free the used
274 * memory.
275 */
276static void hlua_com_wake(struct list *wake)
277{
278 struct hlua_com *com, *back;
279
280 /* Wake task and delete all pending communication signals. */
281 list_for_each_entry_safe(com, back, wake, wake_me) {
282 LIST_DEL(&com->purge_me);
283 LIST_DEL(&com->wake_me);
284 task_wakeup(com->task, TASK_WOKEN_MSG);
285 pool_free2(pool2_hlua_com, com);
286 }
287}
288
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100289/* This functions is used with sample fetch and converters. It
290 * converts the HAProxy configuration argument in a lua stack
291 * values.
292 *
293 * It takes an array of "arg", and each entry of the array is
294 * converted and pushed in the LUA stack.
295 */
296static int hlua_arg2lua(lua_State *L, const struct arg *arg)
297{
298 switch (arg->type) {
299 case ARGT_SINT:
300 lua_pushinteger(L, arg->data.sint);
301 break;
302
303 case ARGT_UINT:
304 case ARGT_TIME:
305 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100306 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100307 break;
308
309 case ARGT_STR:
310 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
311 break;
312
313 case ARGT_IPV4:
314 case ARGT_IPV6:
315 case ARGT_MSK4:
316 case ARGT_MSK6:
317 case ARGT_FE:
318 case ARGT_BE:
319 case ARGT_TAB:
320 case ARGT_SRV:
321 case ARGT_USR:
322 case ARGT_MAP:
323 default:
324 lua_pushnil(L);
325 break;
326 }
327 return 1;
328}
329
330/* This function take one entrie in an LUA stack at the index "ud",
331 * and try to convert it in an HAProxy argument entry. This is useful
332 * with sample fetch wrappers. The input arguments are gived to the
333 * lua wrapper and converted as arg list by thi function.
334 */
335static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
336{
337 switch (lua_type(L, ud)) {
338
339 case LUA_TNUMBER:
340 case LUA_TBOOLEAN:
341 arg->type = ARGT_SINT;
342 arg->data.sint = lua_tointeger(L, ud);
343 break;
344
345 case LUA_TSTRING:
346 arg->type = ARGT_STR;
347 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
348 break;
349
350 case LUA_TUSERDATA:
351 case LUA_TNIL:
352 case LUA_TTABLE:
353 case LUA_TFUNCTION:
354 case LUA_TTHREAD:
355 case LUA_TLIGHTUSERDATA:
356 arg->type = ARGT_SINT;
357 arg->data.uint = 0;
358 break;
359 }
360 return 1;
361}
362
363/* the following functions are used to convert a struct sample
364 * in Lua type. This useful to convert the return of the
365 * fetchs or converters.
366 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100367static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100368{
369 switch (smp->type) {
370 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100371 case SMP_T_BOOL:
372 case SMP_T_UINT:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100373 lua_pushinteger(L, smp->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100374 break;
375
376 case SMP_T_BIN:
377 case SMP_T_STR:
378 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
379 break;
380
381 case SMP_T_METH:
382 switch (smp->data.meth.meth) {
383 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
384 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
385 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
386 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
387 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
388 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
389 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
390 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
391 case HTTP_METH_OTHER:
392 lua_pushlstring(L, smp->data.meth.str.str, smp->data.meth.str.len);
393 break;
394 default:
395 lua_pushnil(L);
396 break;
397 }
398 break;
399
400 case SMP_T_IPV4:
401 case SMP_T_IPV6:
402 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100403 if (sample_casts[smp->type][SMP_T_STR] &&
404 sample_casts[smp->type][SMP_T_STR](smp))
405 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
406 else
407 lua_pushnil(L);
408 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100409 default:
410 lua_pushnil(L);
411 break;
412 }
413 return 1;
414}
415
416/* the following functions are used to convert an Lua type in a
417 * struct sample. This is useful to provide data from a converter
418 * to the LUA code.
419 */
420static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
421{
422 switch (lua_type(L, ud)) {
423
424 case LUA_TNUMBER:
425 smp->type = SMP_T_SINT;
426 smp->data.sint = lua_tointeger(L, ud);
427 break;
428
429
430 case LUA_TBOOLEAN:
431 smp->type = SMP_T_BOOL;
432 smp->data.uint = lua_toboolean(L, ud);
433 break;
434
435 case LUA_TSTRING:
436 smp->type = SMP_T_STR;
437 smp->flags |= SMP_F_CONST;
438 smp->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.str.len);
439 break;
440
441 case LUA_TUSERDATA:
442 case LUA_TNIL:
443 case LUA_TTABLE:
444 case LUA_TFUNCTION:
445 case LUA_TTHREAD:
446 case LUA_TLIGHTUSERDATA:
447 smp->type = SMP_T_BOOL;
448 smp->data.uint = 0;
449 break;
450 }
451 return 1;
452}
453
454/* This function check the "argp" builded by another conversion function
455 * is in accord with the expected argp defined by the "mask". The fucntion
456 * returns true or false. It can be adjust the types if there compatibles.
457 */
458__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp, unsigned int mask)
459{
460 int min_arg;
461 int idx;
462
463 idx = 0;
464 min_arg = ARGM(mask);
465 mask >>= ARGM_BITS;
466
467 while (1) {
468
469 /* Check oversize. */
470 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100471 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100472 }
473
474 /* Check for mandatory arguments. */
475 if (argp[idx].type == ARGT_STOP) {
476 if (idx + 1 < min_arg)
477 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
478 return 0;
479 }
480
481 /* Check for exceed the number of requiered argument. */
482 if ((mask & ARGT_MASK) == ARGT_STOP &&
483 argp[idx].type != ARGT_STOP) {
484 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
485 }
486
487 if ((mask & ARGT_MASK) == ARGT_STOP &&
488 argp[idx].type == ARGT_STOP) {
489 return 0;
490 }
491
492 /* Compatibility mask. */
493 switch (argp[idx].type) {
494 case ARGT_SINT:
495 switch (mask & ARGT_MASK) {
496 case ARGT_UINT: argp[idx].type = mask & ARGT_MASK; break;
497 case ARGT_TIME: argp[idx].type = mask & ARGT_MASK; break;
498 case ARGT_SIZE: argp[idx].type = mask & ARGT_MASK; break;
499 }
500 break;
501 }
502
503 /* Check for type of argument. */
504 if ((mask & ARGT_MASK) != argp[idx].type) {
505 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
506 arg_type_names[(mask & ARGT_MASK)],
507 arg_type_names[argp[idx].type & ARGT_MASK]);
508 WILL_LJMP(luaL_argerror(L, first + idx, msg));
509 }
510
511 /* Next argument. */
512 mask >>= ARGT_BITS;
513 idx++;
514 }
515}
516
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100517/*
518 * The following functions are used to make correspondance between the the
519 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100520 *
521 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100522 * - hlua_sethlua : create the association between hlua context and lua_state.
523 */
524static inline struct hlua *hlua_gethlua(lua_State *L)
525{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100526 struct hlua **hlua = lua_getextraspace(L);
527 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100528}
529static inline void hlua_sethlua(struct hlua *hlua)
530{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100531 struct hlua **hlua_store = lua_getextraspace(hlua->T);
532 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100533}
534
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100535/* This function just ensure that the yield will be always
536 * returned with a timeout and permit to set some flags
537 */
538__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100539 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100540{
541 struct hlua *hlua = hlua_gethlua(L);
542
543 /* Set the wake timeout. If timeout is required, we set
544 * the expiration time.
545 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100546 hlua->wake_time = tick_first(timeout, hlua->expire);
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100547
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100548 hlua->flags |= flags;
549
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100550 /* Process the yield. */
551 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
552}
553
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100554/* This function initialises the Lua environment stored in the session.
555 * It must be called at the start of the session. This function creates
556 * an LUA coroutine. It can not be use to crete the main LUA context.
557 */
558int hlua_ctx_init(struct hlua *lua, struct task *task)
559{
560 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100561 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100562 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100563 lua->T = lua_newthread(gL.T);
564 if (!lua->T) {
565 lua->Tref = LUA_REFNIL;
566 return 0;
567 }
568 hlua_sethlua(lua);
569 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
570 lua->task = task;
571 return 1;
572}
573
574/* Used to destroy the Lua coroutine when the attached session or task
575 * is destroyed. The destroy also the memory context. The struct "lua"
576 * is not freed.
577 */
578void hlua_ctx_destroy(struct hlua *lua)
579{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100580 if (!lua->T)
581 return;
582
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100583 /* Purge all the pending signals. */
584 hlua_com_purge(lua);
585
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100586 /* The thread is garbage collected by Lua. */
587 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
588 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
589}
590
591/* This function is used to restore the Lua context when a coroutine
592 * fails. This function copy the common memory between old coroutine
593 * and the new coroutine. The old coroutine is destroyed, and its
594 * replaced by the new coroutine.
595 * If the flag "keep_msg" is set, the last entry of the old is assumed
596 * as string error message and it is copied in the new stack.
597 */
598static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
599{
600 lua_State *T;
601 int new_ref;
602
603 /* Renew the main LUA stack doesn't have sense. */
604 if (lua == &gL)
605 return 0;
606
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100607 /* New Lua coroutine. */
608 T = lua_newthread(gL.T);
609 if (!T)
610 return 0;
611
612 /* Copy last error message. */
613 if (keep_msg)
614 lua_xmove(lua->T, T, 1);
615
616 /* Copy data between the coroutines. */
617 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
618 lua_xmove(lua->T, T, 1);
619 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
620
621 /* Destroy old data. */
622 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
623
624 /* The thread is garbage collected by Lua. */
625 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
626
627 /* Fill the struct with the new coroutine values. */
628 lua->Mref = new_ref;
629 lua->T = T;
630 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
631
632 /* Set context. */
633 hlua_sethlua(lua);
634
635 return 1;
636}
637
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100638void hlua_hook(lua_State *L, lua_Debug *ar)
639{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100640 struct hlua *hlua = hlua_gethlua(L);
641
642 /* Lua cannot yield when its returning from a function,
643 * so, we can fix the interrupt hook to 1 instruction,
644 * expecting that the function is finnished.
645 */
646 if (lua_gethookmask(L) & LUA_MASKRET) {
647 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
648 return;
649 }
650
651 /* restore the interrupt condition. */
652 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
653
654 /* If we interrupt the Lua processing in yieldable state, we yield.
655 * If the state is not yieldable, trying yield causes an error.
656 */
657 if (lua_isyieldable(L))
658 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
659
660 /* If we cannot yield, check the timeout. */
661 if (tick_is_expired(hlua->expire, now_ms)) {
662 lua_pushfstring(L, "execution timeout");
663 WILL_LJMP(lua_error(L));
664 }
665
666 /* Try to interrupt the process at the end of the current
667 * unyieldable function.
668 */
669 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100670}
671
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100672/* This function start or resumes the Lua stack execution. If the flag
673 * "yield_allowed" if no set and the LUA stack execution returns a yield
674 * The function return an error.
675 *
676 * The function can returns 4 values:
677 * - HLUA_E_OK : The execution is terminated without any errors.
678 * - HLUA_E_AGAIN : The execution must continue at the next associated
679 * task wakeup.
680 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
681 * the top of the stack.
682 * - HLUA_E_ERR : An error has occured without error message.
683 *
684 * If an error occured, the stack is renewed and it is ready to run new
685 * LUA code.
686 */
687static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
688{
689 int ret;
690 const char *msg;
691
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100692 HLUA_SET_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100693
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100694 /* If we want to resume the task, then check first the execution timeout.
695 * if it is reached, we can interrupt the Lua processing.
696 */
697 if (tick_is_expired(lua->expire, now_ms))
698 goto timeout_reached;
699
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100700resume_execution:
701
702 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
703 * instructions. it is used for preventing infinite loops.
704 */
705 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
706
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +0100707 /* Remove all flags except the running flags. */
708 lua->flags = HLUA_RUN;
709
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100710 /* Call the function. */
711 ret = lua_resume(lua->T, gL.T, lua->nargs);
712 switch (ret) {
713
714 case LUA_OK:
715 ret = HLUA_E_OK;
716 break;
717
718 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100719 /* Check if the execution timeout is expired. It it is the case, we
720 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100721 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100722 if (tick_is_expired(lua->expire, now_ms)) {
723
724timeout_reached:
725
726 lua_settop(lua->T, 0); /* Empty the stack. */
727 if (!lua_checkstack(lua->T, 1)) {
728 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100729 break;
730 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100731 lua_pushfstring(lua->T, "execution timeout");
732 ret = HLUA_E_ERRMSG;
733 break;
734 }
735 /* Process the forced yield. if the general yield is not allowed or
736 * if no task were associated this the current Lua execution
737 * coroutine, we resume the execution. Else we want to return in the
738 * scheduler and we want to be waked up again, to continue the
739 * current Lua execution. So we schedule our own task.
740 */
741 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100742 if (!yield_allowed || !lua->task)
743 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100744 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100745 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100746 if (!yield_allowed) {
747 lua_settop(lua->T, 0); /* Empty the stack. */
748 if (!lua_checkstack(lua->T, 1)) {
749 ret = HLUA_E_ERR;
750 break;
751 }
752 lua_pushfstring(lua->T, "yield not allowed");
753 ret = HLUA_E_ERRMSG;
754 break;
755 }
756 ret = HLUA_E_AGAIN;
757 break;
758
759 case LUA_ERRRUN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100760 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100761 if (!lua_checkstack(lua->T, 1)) {
762 ret = HLUA_E_ERR;
763 break;
764 }
765 msg = lua_tostring(lua->T, -1);
766 lua_settop(lua->T, 0); /* Empty the stack. */
767 lua_pop(lua->T, 1);
768 if (msg)
769 lua_pushfstring(lua->T, "runtime error: %s", msg);
770 else
771 lua_pushfstring(lua->T, "unknown runtime error");
772 ret = HLUA_E_ERRMSG;
773 break;
774
775 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100776 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100777 lua_settop(lua->T, 0); /* Empty the stack. */
778 if (!lua_checkstack(lua->T, 1)) {
779 ret = HLUA_E_ERR;
780 break;
781 }
782 lua_pushfstring(lua->T, "out of memory error");
783 ret = HLUA_E_ERRMSG;
784 break;
785
786 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100787 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100788 if (!lua_checkstack(lua->T, 1)) {
789 ret = HLUA_E_ERR;
790 break;
791 }
792 msg = lua_tostring(lua->T, -1);
793 lua_settop(lua->T, 0); /* Empty the stack. */
794 lua_pop(lua->T, 1);
795 if (msg)
796 lua_pushfstring(lua->T, "message handler error: %s", msg);
797 else
798 lua_pushfstring(lua->T, "message handler error");
799 ret = HLUA_E_ERRMSG;
800 break;
801
802 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100803 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100804 lua_settop(lua->T, 0); /* Empty the stack. */
805 if (!lua_checkstack(lua->T, 1)) {
806 ret = HLUA_E_ERR;
807 break;
808 }
809 lua_pushfstring(lua->T, "unknonwn error");
810 ret = HLUA_E_ERRMSG;
811 break;
812 }
813
814 switch (ret) {
815 case HLUA_E_AGAIN:
816 break;
817
818 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100819 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100820 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100821 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100822 break;
823
824 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100825 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100826 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100827 hlua_ctx_renew(lua, 0);
828 break;
829
830 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100831 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100832 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100833 break;
834 }
835
836 return ret;
837}
838
Thierry FOURNIER83758bb2015-02-04 13:21:04 +0100839/* This function is an LUA binding. It provides a function
840 * for deleting ACL from a referenced ACL file.
841 */
842__LJMP static int hlua_del_acl(lua_State *L)
843{
844 const char *name;
845 const char *key;
846 struct pat_ref *ref;
847
848 MAY_LJMP(check_args(L, 2, "del_acl"));
849
850 name = MAY_LJMP(luaL_checkstring(L, 1));
851 key = MAY_LJMP(luaL_checkstring(L, 2));
852
853 ref = pat_ref_lookup(name);
854 if (!ref)
855 WILL_LJMP(luaL_error(L, "'del_acl': unkown acl file '%s'", name));
856
857 pat_ref_delete(ref, key);
858 return 0;
859}
860
861/* This function is an LUA binding. It provides a function
862 * for deleting map entry from a referenced map file.
863 */
864static int hlua_del_map(lua_State *L)
865{
866 const char *name;
867 const char *key;
868 struct pat_ref *ref;
869
870 MAY_LJMP(check_args(L, 2, "del_map"));
871
872 name = MAY_LJMP(luaL_checkstring(L, 1));
873 key = MAY_LJMP(luaL_checkstring(L, 2));
874
875 ref = pat_ref_lookup(name);
876 if (!ref)
877 WILL_LJMP(luaL_error(L, "'del_map': unkown acl file '%s'", name));
878
879 pat_ref_delete(ref, key);
880 return 0;
881}
882
883/* This function is an LUA binding. It provides a function
884 * for adding ACL pattern from a referenced ACL file.
885 */
886static int hlua_add_acl(lua_State *L)
887{
888 const char *name;
889 const char *key;
890 struct pat_ref *ref;
891
892 MAY_LJMP(check_args(L, 2, "add_acl"));
893
894 name = MAY_LJMP(luaL_checkstring(L, 1));
895 key = MAY_LJMP(luaL_checkstring(L, 2));
896
897 ref = pat_ref_lookup(name);
898 if (!ref)
899 WILL_LJMP(luaL_error(L, "'add_acl': unkown acl file '%s'", name));
900
901 if (pat_ref_find_elt(ref, key) == NULL)
902 pat_ref_add(ref, key, NULL, NULL);
903 return 0;
904}
905
906/* This function is an LUA binding. It provides a function
907 * for setting map pattern and sample from a referenced map
908 * file.
909 */
910static int hlua_set_map(lua_State *L)
911{
912 const char *name;
913 const char *key;
914 const char *value;
915 struct pat_ref *ref;
916
917 MAY_LJMP(check_args(L, 3, "set_map"));
918
919 name = MAY_LJMP(luaL_checkstring(L, 1));
920 key = MAY_LJMP(luaL_checkstring(L, 2));
921 value = MAY_LJMP(luaL_checkstring(L, 3));
922
923 ref = pat_ref_lookup(name);
924 if (!ref)
925 WILL_LJMP(luaL_error(L, "'set_map': unkown map file '%s'", name));
926
927 if (pat_ref_find_elt(ref, key) != NULL)
928 pat_ref_set(ref, key, value, NULL);
929 else
930 pat_ref_add(ref, key, value, NULL);
931 return 0;
932}
933
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100934/* A class is a lot of memory that contain data. This data can be a table,
935 * an integer or user data. This data is associated with a metatable. This
936 * metatable have an original version registred in the global context with
937 * the name of the object (_G[<name>] = <metable> ).
938 *
939 * A metable is a table that modify the standard behavior of a standard
940 * access to the associated data. The entries of this new metatable are
941 * defined as is:
942 *
943 * http://lua-users.org/wiki/MetatableEvents
944 *
945 * __index
946 *
947 * we access an absent field in a table, the result is nil. This is
948 * true, but it is not the whole truth. Actually, such access triggers
949 * the interpreter to look for an __index metamethod: If there is no
950 * such method, as usually happens, then the access results in nil;
951 * otherwise, the metamethod will provide the result.
952 *
953 * Control 'prototype' inheritance. When accessing "myTable[key]" and
954 * the key does not appear in the table, but the metatable has an __index
955 * property:
956 *
957 * - if the value is a function, the function is called, passing in the
958 * table and the key; the return value of that function is returned as
959 * the result.
960 *
961 * - if the value is another table, the value of the key in that table is
962 * asked for and returned (and if it doesn't exist in that table, but that
963 * table's metatable has an __index property, then it continues on up)
964 *
965 * - Use "rawget(myTable,key)" to skip this metamethod.
966 *
967 * http://www.lua.org/pil/13.4.1.html
968 *
969 * __newindex
970 *
971 * Like __index, but control property assignment.
972 *
973 * __mode - Control weak references. A string value with one or both
974 * of the characters 'k' and 'v' which specifies that the the
975 * keys and/or values in the table are weak references.
976 *
977 * __call - Treat a table like a function. When a table is followed by
978 * parenthesis such as "myTable( 'foo' )" and the metatable has
979 * a __call key pointing to a function, that function is invoked
980 * (passing any specified arguments) and the return value is
981 * returned.
982 *
983 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
984 * called, if the metatable for myTable has a __metatable
985 * key, the value of that key is returned instead of the
986 * actual metatable.
987 *
988 * __tostring - Control string representation. When the builtin
989 * "tostring( myTable )" function is called, if the metatable
990 * for myTable has a __tostring property set to a function,
991 * that function is invoked (passing myTable to it) and the
992 * return value is used as the string representation.
993 *
994 * __len - Control table length. When the table length is requested using
995 * the length operator ( '#' ), if the metatable for myTable has
996 * a __len key pointing to a function, that function is invoked
997 * (passing myTable to it) and the return value used as the value
998 * of "#myTable".
999 *
1000 * __gc - Userdata finalizer code. When userdata is set to be garbage
1001 * collected, if the metatable has a __gc field pointing to a
1002 * function, that function is first invoked, passing the userdata
1003 * to it. The __gc metamethod is not called for tables.
1004 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1005 *
1006 * Special metamethods for redefining standard operators:
1007 * http://www.lua.org/pil/13.1.html
1008 *
1009 * __add "+"
1010 * __sub "-"
1011 * __mul "*"
1012 * __div "/"
1013 * __unm "!"
1014 * __pow "^"
1015 * __concat ".."
1016 *
1017 * Special methods for redfining standar relations
1018 * http://www.lua.org/pil/13.2.html
1019 *
1020 * __eq "=="
1021 * __lt "<"
1022 * __le "<="
1023 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001024
1025/*
1026 *
1027 *
1028 * Class Socket
1029 *
1030 *
1031 */
1032
1033__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1034{
1035 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1036}
1037
1038/* This function is the handler called for each I/O on the established
1039 * connection. It is used for notify space avalaible to send or data
1040 * received.
1041 */
1042static void hlua_socket_handler(struct stream_interface *si)
1043{
1044 struct appctx *appctx = objt_appctx(si->end);
1045 struct connection *c = objt_conn(si->ib->cons->end);
1046
1047 /* Wakeup the main session if the client connection is closed. */
1048 if (!c || channel_output_closed(si->ib) || channel_input_closed(si->ob)) {
1049 if (appctx->ctx.hlua.socket) {
1050 appctx->ctx.hlua.socket->s = NULL;
1051 appctx->ctx.hlua.socket = NULL;
1052 }
1053 si_shutw(si);
1054 si_shutr(si);
1055 si->ib->flags |= CF_READ_NULL;
1056 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1057 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1058 return;
1059 }
1060
1061 if (!(c->flags & CO_FL_CONNECTED))
1062 return;
1063
1064 /* This function is called after the connect. */
1065 appctx->ctx.hlua.connected = 1;
1066
1067 /* Wake the tasks which wants to write if the buffer have avalaible space. */
1068 if (channel_may_recv(si->ob))
1069 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1070
1071 /* Wake the tasks which wants to read if the buffer contains data. */
1072 if (channel_is_empty(si->ib))
1073 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1074}
1075
1076/* This function is called when the "struct session" is destroyed.
1077 * Remove the link from the object to this session.
1078 * Wake all the pending signals.
1079 */
1080static void hlua_socket_release(struct stream_interface *si)
1081{
1082 struct appctx *appctx = objt_appctx(si->end);
1083
1084 /* Remove my link in the original object. */
1085 if (appctx->ctx.hlua.socket)
1086 appctx->ctx.hlua.socket->s = NULL;
1087
1088 /* Wake all the task waiting for me. */
1089 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1090 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1091}
1092
1093/* If the garbage collectio of the object is launch, nobody
1094 * uses this object. If the session does not exists, just quit.
1095 * Send the shutdown signal to the session. In some cases,
1096 * pending signal can rest in the read and write lists. destroy
1097 * it.
1098 */
1099__LJMP static int hlua_socket_gc(lua_State *L)
1100{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001101 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001102 struct appctx *appctx;
1103
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001104 MAY_LJMP(check_args(L, 1, "__gc"));
1105
1106 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001107 if (!socket->s)
1108 return 0;
1109
1110 /* Remove all reference between the Lua stack and the coroutine session. */
1111 appctx = objt_appctx(socket->s->si[0].end);
1112 session_shutdown(socket->s, SN_ERR_KILLED);
1113 socket->s = NULL;
1114 appctx->ctx.hlua.socket = NULL;
1115
1116 return 0;
1117}
1118
1119/* The close function send shutdown signal and break the
1120 * links between the session and the object.
1121 */
1122__LJMP static int hlua_socket_close(lua_State *L)
1123{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001124 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001125 struct appctx *appctx;
1126
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001127 MAY_LJMP(check_args(L, 1, "close"));
1128
1129 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001130 if (!socket->s)
1131 return 0;
1132
1133 /* Close the session and remove the associated stop task. */
1134 session_shutdown(socket->s, SN_ERR_KILLED);
1135 appctx = objt_appctx(socket->s->si[0].end);
1136 appctx->ctx.hlua.socket = NULL;
1137 socket->s = NULL;
1138
1139 return 0;
1140}
1141
1142/* This Lua function assumes that the stack contain three parameters.
1143 * 1 - USERDATA containing a struct socket
1144 * 2 - INTEGER with values of the macro defined below
1145 * If the integer is -1, we must read at most one line.
1146 * If the integer is -2, we ust read all the data until the
1147 * end of the stream.
1148 * If the integer is positive value, we must read a number of
1149 * bytes corresponding to this value.
1150 */
1151#define HLSR_READ_LINE (-1)
1152#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001153__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001154{
1155 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1156 int wanted = lua_tointeger(L, 2);
1157 struct hlua *hlua = hlua_gethlua(L);
1158 struct appctx *appctx;
1159 int len;
1160 int nblk;
1161 char *blk1;
1162 int len1;
1163 char *blk2;
1164 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001165 int skip_at_end = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001166
1167 /* Check if this lua stack is schedulable. */
1168 if (!hlua || !hlua->task)
1169 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1170 "'frontend', 'backend' or 'task'"));
1171
1172 /* check for connection closed. If some data where read, return it. */
1173 if (!socket->s)
1174 goto connection_closed;
1175
1176 if (wanted == HLSR_READ_LINE) {
1177
1178 /* Read line. */
1179 nblk = bo_getline_nc(socket->s->si[0].ob, &blk1, &len1, &blk2, &len2);
1180 if (nblk < 0) /* Connection close. */
1181 goto connection_closed;
1182 if (nblk == 0) /* No data avalaible. */
1183 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001184
1185 /* remove final \r\n. */
1186 if (nblk == 1) {
1187 if (blk1[len1-1] == '\n') {
1188 len1--;
1189 skip_at_end++;
1190 if (blk1[len1-1] == '\r') {
1191 len1--;
1192 skip_at_end++;
1193 }
1194 }
1195 }
1196 else {
1197 if (blk2[len2-1] == '\n') {
1198 len2--;
1199 skip_at_end++;
1200 if (blk2[len2-1] == '\r') {
1201 len2--;
1202 skip_at_end++;
1203 }
1204 }
1205 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001206 }
1207
1208 else if (wanted == HLSR_READ_ALL) {
1209
1210 /* Read all the available data. */
1211 nblk = bo_getblk_nc(socket->s->si[0].ob, &blk1, &len1, &blk2, &len2);
1212 if (nblk < 0) /* Connection close. */
1213 goto connection_closed;
1214 if (nblk == 0) /* No data avalaible. */
1215 goto connection_empty;
1216 }
1217
1218 else {
1219
1220 /* Read a block of data. */
1221 nblk = bo_getblk_nc(socket->s->si[0].ob, &blk1, &len1, &blk2, &len2);
1222 if (nblk < 0) /* Connection close. */
1223 goto connection_closed;
1224 if (nblk == 0) /* No data avalaible. */
1225 goto connection_empty;
1226
1227 if (len1 > wanted) {
1228 nblk = 1;
1229 len1 = wanted;
1230 } if (nblk == 2 && len1 + len2 > wanted)
1231 len2 = wanted - len1;
1232 }
1233
1234 len = len1;
1235
1236 luaL_addlstring(&socket->b, blk1, len1);
1237 if (nblk == 2) {
1238 len += len2;
1239 luaL_addlstring(&socket->b, blk2, len2);
1240 }
1241
1242 /* Consume data. */
Thierry FOURNIER00543922015-03-09 18:35:06 +01001243 bo_skip(socket->s->si[0].ob, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001244
1245 /* Don't wait anything. */
1246 si_update(&socket->s->si[0]);
1247
1248 /* If the pattern reclaim to read all the data
1249 * in the connection, got out.
1250 */
1251 if (wanted == HLSR_READ_ALL)
1252 goto connection_empty;
1253 else if (wanted >= 0 && len < wanted)
1254 goto connection_empty;
1255
1256 /* Return result. */
1257 luaL_pushresult(&socket->b);
1258 return 1;
1259
1260connection_closed:
1261
1262 /* If the buffer containds data. */
1263 if (socket->b.n > 0) {
1264 luaL_pushresult(&socket->b);
1265 return 1;
1266 }
1267 lua_pushnil(L);
1268 lua_pushstring(L, "connection closed.");
1269 return 2;
1270
1271connection_empty:
1272
1273 appctx = objt_appctx(socket->s->si[0].end);
1274 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1275 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001276 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001277 return 0;
1278}
1279
1280/* This Lus function gets two parameters. The first one can be string
1281 * or a number. If the string is "*l", the user require one line. If
1282 * the string is "*a", the user require all the content of the stream.
1283 * If the value is a number, the user require a number of bytes equal
1284 * to the value. The default value is "*l" (a line).
1285 *
1286 * This paraeter with a variable type is converted in integer. This
1287 * integer takes this values:
1288 * -1 : read a line
1289 * -2 : read all the stream
1290 * >0 : amount if bytes.
1291 *
1292 * The second parameter is optinal. It contains a string that must be
1293 * concatenated with the read data.
1294 */
1295__LJMP static int hlua_socket_receive(struct lua_State *L)
1296{
1297 int wanted = HLSR_READ_LINE;
1298 const char *pattern;
1299 int type;
1300 char *error;
1301 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001302 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001303
1304 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1305 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1306
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001307 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001308
1309 /* check for pattern. */
1310 if (lua_gettop(L) >= 2) {
1311 type = lua_type(L, 2);
1312 if (type == LUA_TSTRING) {
1313 pattern = lua_tostring(L, 2);
1314 if (strcmp(pattern, "*a") == 0)
1315 wanted = HLSR_READ_ALL;
1316 else if (strcmp(pattern, "*l") == 0)
1317 wanted = HLSR_READ_LINE;
1318 else {
1319 wanted = strtoll(pattern, &error, 10);
1320 if (*error != '\0')
1321 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1322 }
1323 }
1324 else if (type == LUA_TNUMBER) {
1325 wanted = lua_tointeger(L, 2);
1326 if (wanted < 0)
1327 WILL_LJMP(luaL_error(L, "Unsupported size."));
1328 }
1329 }
1330
1331 /* Set pattern. */
1332 lua_pushinteger(L, wanted);
1333 lua_replace(L, 2);
1334
1335 /* init bufffer, and fiil it wih prefix. */
1336 luaL_buffinit(L, &socket->b);
1337
1338 /* Check prefix. */
1339 if (lua_gettop(L) >= 3) {
1340 if (lua_type(L, 3) != LUA_TSTRING)
1341 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1342 pattern = lua_tolstring(L, 3, &len);
1343 luaL_addlstring(&socket->b, pattern, len);
1344 }
1345
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001346 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001347}
1348
1349/* Write the Lua input string in the output buffer.
1350 * This fucntion returns a yield if no space are available.
1351 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001352static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001353{
1354 struct hlua_socket *socket;
1355 struct hlua *hlua = hlua_gethlua(L);
1356 struct appctx *appctx;
1357 size_t buf_len;
1358 const char *buf;
1359 int len;
1360 int send_len;
1361 int sent;
1362
1363 /* Check if this lua stack is schedulable. */
1364 if (!hlua || !hlua->task)
1365 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1366 "'frontend', 'backend' or 'task'"));
1367
1368 /* Get object */
1369 socket = MAY_LJMP(hlua_checksocket(L, 1));
1370 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001371 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001372
1373 /* Check for connection close. */
1374 if (!socket->s || channel_output_closed(socket->s->req)) {
1375 lua_pushinteger(L, -1);
1376 return 1;
1377 }
1378
1379 /* Update the input buffer data. */
1380 buf += sent;
1381 send_len = buf_len - sent;
1382
1383 /* All the data are sent. */
1384 if (sent >= buf_len)
1385 return 1; /* Implicitly return the length sent. */
1386
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001387 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1388 * the request buffer if its not required.
1389 */
1390 if (socket->s->req->buf->size == 0) {
1391 if (!session_alloc_recv_buffer(socket->s, &socket->s->req->buf)) {
1392 socket->s->req->prod->flags |= SI_FL_WAIT_ROOM;
1393 goto hlua_socket_write_yield_return;
1394 }
1395 }
1396
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001397 /* Check for avalaible space. */
1398 len = buffer_total_space(socket->s->si[0].ib->buf);
1399 if (len <= 0)
1400 goto hlua_socket_write_yield_return;
1401
1402 /* send data */
1403 if (len < send_len)
1404 send_len = len;
1405 len = bi_putblk(socket->s->si[0].ib, buf+sent, send_len);
1406
1407 /* "Not enough space" (-1), "Buffer too little to contain
1408 * the data" (-2) are not expected because the available length
1409 * is tested.
1410 * Other unknown error are also not expected.
1411 */
1412 if (len <= 0) {
1413 MAY_LJMP(hlua_socket_close(L));
1414 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001415 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001416 return 1;
1417 }
1418
1419 /* update buffers. */
1420 si_update(&socket->s->si[0]);
1421 socket->s->si[0].ib->rex = TICK_ETERNITY;
1422 socket->s->si[0].ob->wex = TICK_ETERNITY;
1423
1424 /* Update length sent. */
1425 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001426 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001427
1428 /* All the data buffer is sent ? */
1429 if (sent + len >= buf_len)
1430 return 1;
1431
1432hlua_socket_write_yield_return:
1433 appctx = objt_appctx(socket->s->si[0].end);
1434 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1435 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001436 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001437 return 0;
1438}
1439
1440/* This function initiate the send of data. It just check the input
1441 * parameters and push an integer in the Lua stack that contain the
1442 * amount of data writed in the buffer. This is used by the function
1443 * "hlua_socket_write_yield" that can yield.
1444 *
1445 * The Lua function gets between 3 and 4 parameters. The first one is
1446 * the associated object. The second is a string buffer. The third is
1447 * a facultative integer that represents where is the buffer position
1448 * of the start of the data that can send. The first byte is the
1449 * position "1". The default value is "1". The fourth argument is a
1450 * facultative integer that represents where is the buffer position
1451 * of the end of the data that can send. The default is the last byte.
1452 */
1453static int hlua_socket_send(struct lua_State *L)
1454{
1455 int i;
1456 int j;
1457 const char *buf;
1458 size_t buf_len;
1459
1460 /* Check number of arguments. */
1461 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1462 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1463
1464 /* Get the string. */
1465 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1466
1467 /* Get and check j. */
1468 if (lua_gettop(L) == 4) {
1469 j = MAY_LJMP(luaL_checkinteger(L, 4));
1470 if (j < 0)
1471 j = buf_len + j + 1;
1472 if (j > buf_len)
1473 j = buf_len + 1;
1474 lua_pop(L, 1);
1475 }
1476 else
1477 j = buf_len;
1478
1479 /* Get and check i. */
1480 if (lua_gettop(L) == 3) {
1481 i = MAY_LJMP(luaL_checkinteger(L, 3));
1482 if (i < 0)
1483 i = buf_len + i + 1;
1484 if (i > buf_len)
1485 i = buf_len + 1;
1486 lua_pop(L, 1);
1487 } else
1488 i = 1;
1489
1490 /* Check bth i and j. */
1491 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001492 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001493 return 1;
1494 }
1495 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001496 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001497 return 1;
1498 }
1499 if (i == 0)
1500 i = 1;
1501 if (j == 0)
1502 j = 1;
1503
1504 /* Pop the string. */
1505 lua_pop(L, 1);
1506
1507 /* Update the buffer length. */
1508 buf += i - 1;
1509 buf_len = j - i + 1;
1510 lua_pushlstring(L, buf, buf_len);
1511
1512 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001513 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001514
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001515 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001516}
1517
1518#define SOCKET_INFO_EXPANDED_FORM "[0000:0000:0000:0000:0000:0000:0000:0000]:12345"
1519static char _socket_info_expanded_form[] = SOCKET_INFO_EXPANDED_FORM;
1520#define SOCKET_INFO_MAX_LEN (sizeof(_socket_info_expanded_form))
1521__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
1522{
1523 static char buffer[SOCKET_INFO_MAX_LEN];
1524 int ret;
1525 int len;
1526 char *p;
1527
1528 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
1529 if (ret <= 0) {
1530 lua_pushnil(L);
1531 return 1;
1532 }
1533
1534 if (ret == AF_UNIX) {
1535 lua_pushstring(L, buffer+1);
1536 return 1;
1537 }
1538 else if (ret == AF_INET6) {
1539 buffer[0] = '[';
1540 len = strlen(buffer);
1541 buffer[len] = ']';
1542 len++;
1543 buffer[len] = ':';
1544 len++;
1545 p = buffer;
1546 }
1547 else if (ret == AF_INET) {
1548 p = buffer + 1;
1549 len = strlen(p);
1550 p[len] = ':';
1551 len++;
1552 }
1553 else {
1554 lua_pushnil(L);
1555 return 1;
1556 }
1557
1558 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
1559 lua_pushnil(L);
1560 return 1;
1561 }
1562
1563 lua_pushstring(L, p);
1564 return 1;
1565}
1566
1567/* Returns information about the peer of the connection. */
1568__LJMP static int hlua_socket_getpeername(struct lua_State *L)
1569{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001570 struct hlua_socket *socket;
1571 struct connection *conn;
1572
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001573 MAY_LJMP(check_args(L, 1, "getpeername"));
1574
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001575 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001576
1577 /* Check if the tcp object is avalaible. */
1578 if (!socket->s) {
1579 lua_pushnil(L);
1580 return 1;
1581 }
1582
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001583 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001584 if (!conn) {
1585 lua_pushnil(L);
1586 return 1;
1587 }
1588
1589 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
1590 unsigned int salen = sizeof(conn->addr.to);
1591 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
1592 lua_pushnil(L);
1593 return 1;
1594 }
1595 conn->flags |= CO_FL_ADDR_TO_SET;
1596 }
1597
1598 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
1599}
1600
1601/* Returns information about my connection side. */
1602static int hlua_socket_getsockname(struct lua_State *L)
1603{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001604 struct hlua_socket *socket;
1605 struct connection *conn;
1606
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001607 MAY_LJMP(check_args(L, 1, "getsockname"));
1608
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001609 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001610
1611 /* Check if the tcp object is avalaible. */
1612 if (!socket->s) {
1613 lua_pushnil(L);
1614 return 1;
1615 }
1616
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001617 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001618 if (!conn) {
1619 lua_pushnil(L);
1620 return 1;
1621 }
1622
1623 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
1624 unsigned int salen = sizeof(conn->addr.from);
1625 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
1626 lua_pushnil(L);
1627 return 1;
1628 }
1629 conn->flags |= CO_FL_ADDR_FROM_SET;
1630 }
1631
1632 return hlua_socket_info(L, &conn->addr.from);
1633}
1634
1635/* This struct define the applet. */
1636static struct si_applet update_applet = {
1637 .obj_type = OBJ_TYPE_APPLET,
1638 .name = "<LUA_TCP>",
1639 .fct = hlua_socket_handler,
1640 .release = hlua_socket_release,
1641};
1642
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001643__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001644{
1645 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1646 struct hlua *hlua = hlua_gethlua(L);
1647 struct appctx *appctx;
1648
1649 /* Check for connection close. */
1650 if (!hlua || !socket->s || channel_output_closed(socket->s->req)) {
1651 lua_pushnil(L);
1652 lua_pushstring(L, "Can't connect");
1653 return 2;
1654 }
1655
1656 appctx = objt_appctx(socket->s->si[0].end);
1657
1658 /* Check for connection established. */
1659 if (appctx->ctx.hlua.connected) {
1660 lua_pushinteger(L, 1);
1661 return 1;
1662 }
1663
1664 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1665 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001666 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001667 return 0;
1668}
1669
1670/* This function fail or initite the connection. */
1671__LJMP static int hlua_socket_connect(struct lua_State *L)
1672{
1673 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001674 int port;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001675 const char *ip;
1676 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01001677 struct hlua *hlua;
1678 struct appctx *appctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001679
1680 MAY_LJMP(check_args(L, 3, "connect"));
1681
1682 /* Get args. */
1683 socket = MAY_LJMP(hlua_checksocket(L, 1));
1684 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001685 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001686
1687 conn = si_alloc_conn(socket->s->req->cons, 0);
1688 if (!conn)
1689 WILL_LJMP(luaL_error(L, "connect: internal error"));
1690
1691 /* Parse ip address. */
1692 conn->addr.to.ss_family = AF_UNSPEC;
1693 if (!str2ip2(ip, &conn->addr.to, 0))
1694 WILL_LJMP(luaL_error(L, "connect: cannot parse ip address '%s'", ip));
1695
1696 /* Set port. */
1697 if (conn->addr.to.ss_family == AF_INET)
1698 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
1699 else if (conn->addr.to.ss_family == AF_INET6)
1700 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
1701
1702 /* it is important not to call the wakeup function directly but to
1703 * pass through task_wakeup(), because this one knows how to apply
1704 * priorities to tasks.
1705 */
1706 task_wakeup(socket->s->task, TASK_WOKEN_INIT);
1707
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01001708 hlua = hlua_gethlua(L);
1709 appctx = objt_appctx(socket->s->si[0].end);
1710 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1711 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001712 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001713
1714 return 0;
1715}
1716
Baptiste Assmann84bb4932015-03-02 21:40:06 +01001717#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001718__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
1719{
1720 struct hlua_socket *socket;
1721
1722 MAY_LJMP(check_args(L, 3, "connect_ssl"));
1723 socket = MAY_LJMP(hlua_checksocket(L, 1));
1724 socket->s->target = &socket_ssl.obj_type;
1725 return MAY_LJMP(hlua_socket_connect(L));
1726}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01001727#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001728
1729__LJMP static int hlua_socket_setoption(struct lua_State *L)
1730{
1731 return 0;
1732}
1733
1734__LJMP static int hlua_socket_settimeout(struct lua_State *L)
1735{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001736 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001737 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001738
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001739 MAY_LJMP(check_args(L, 2, "settimeout"));
1740
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001741 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001742 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001743
1744 socket->s->req->rto = tmout;
1745 socket->s->req->wto = tmout;
1746 socket->s->rep->rto = tmout;
1747 socket->s->rep->wto = tmout;
1748
1749 return 0;
1750}
1751
1752__LJMP static int hlua_socket_new(lua_State *L)
1753{
1754 struct hlua_socket *socket;
1755 struct appctx *appctx;
1756
1757 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01001758 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001759 hlua_pusherror(L, "socket: full stack");
1760 goto out_fail_conf;
1761 }
1762
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01001763 /* Create the object: obj[0] = userdata. */
1764 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001765 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01001766 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001767 memset(socket, 0, sizeof(*socket));
1768
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01001769 /* Check if the various memory pools are intialized. */
1770 if (!pool2_session || !pool2_channel || !pool2_buffer) {
1771 hlua_pusherror(L, "socket: uninitialized pools.");
1772 goto out_fail_conf;
1773 }
1774
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001775 /* Pop a class session metatable and affect it to the userdata. */
1776 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
1777 lua_setmetatable(L, -2);
1778
1779 /*
1780 *
1781 * Get memory for the request.
1782 *
1783 */
1784
1785 socket->s = pool_alloc2(pool2_session);
1786 if (!socket->s) {
1787 hlua_pusherror(L, "socket: out of memory");
1788 goto out_fail_conf;
1789 }
1790
1791 socket->s->task = task_new();
1792 if (!socket->s->task) {
1793 hlua_pusherror(L, "socket: out of memory");
1794 goto out_free_session;
1795 }
1796
1797 socket->s->req = pool_alloc2(pool2_channel);
1798 if (!socket->s->req) {
1799 hlua_pusherror(L, "socket: out of memory");
1800 goto out_fail_req;
1801 }
1802
1803 socket->s->req->buf = pool_alloc2(pool2_buffer);
1804 if (!socket->s->req->buf) {
1805 hlua_pusherror(L, "socket: out of memory");
1806 goto out_fail_req_buf;
1807 }
1808
1809 socket->s->rep = pool_alloc2(pool2_channel);
1810 if (!socket->s->rep) {
1811 hlua_pusherror(L, "socket: out of memory");
1812 goto out_fail_rep;
1813 }
1814
1815 socket->s->rep->buf = pool_alloc2(pool2_buffer);
1816 if (!socket->s->rep->buf) {
1817 hlua_pusherror(L, "socket: out of memory");
1818 goto out_fail_rep_buf;
1819 }
1820
1821 /* Configura empty Lua for the session. */
1822 socket->s->hlua.T = NULL;
1823 socket->s->hlua.Tref = LUA_REFNIL;
1824 socket->s->hlua.Mref = LUA_REFNIL;
1825 socket->s->hlua.nargs = 0;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001826 socket->s->hlua.flags = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001827 LIST_INIT(&socket->s->hlua.com);
1828
1829 /* session initialisation. */
1830 session_init_srv_conn(socket->s);
1831
1832 /*
1833 *
1834 * Configure the associated task.
1835 *
1836 */
1837
1838 /* This is the dedicated function to process the session. This function
1839 * is able to establish the conection, process the timeouts, etc ...
1840 */
1841 socket->s->task->process = process_session;
1842
1843 /* Back reference to session. This is used by process_session(). */
1844 socket->s->task->context = socket->s;
1845
1846 /* The priority of the task is normal. */
1847 socket->s->task->nice = 0;
1848
1849 /* Init the next run to eternity. Later in this function, this task is
1850 * waked.
1851 */
1852 socket->s->task->expire = TICK_ETERNITY;
1853
1854 /*
1855 *
1856 * Initialize the attached buffers
1857 *
1858 */
1859 socket->s->req->buf->size = global.tune.bufsize;
1860 socket->s->rep->buf->size = global.tune.bufsize;
1861
1862 /*
1863 *
1864 * Initialize channels.
1865 *
1866 */
1867
1868 /* This function reset the struct. It must be called
1869 * before the configuration.
1870 */
1871 channel_init(socket->s->req);
1872 channel_init(socket->s->rep);
1873
1874 socket->s->req->prod = &socket->s->si[0];
1875 socket->s->req->cons = &socket->s->si[1];
1876
1877 socket->s->rep->prod = &socket->s->si[1];
1878 socket->s->rep->cons = &socket->s->si[0];
1879
1880 socket->s->si[0].ib = socket->s->req;
1881 socket->s->si[0].ob = socket->s->rep;
1882
1883 socket->s->si[1].ib = socket->s->rep;
1884 socket->s->si[1].ob = socket->s->req;
1885
1886 socket->s->req->analysers = 0;
1887 socket->s->req->rto = socket_proxy.timeout.client;
1888 socket->s->req->wto = socket_proxy.timeout.server;
1889 socket->s->req->rex = TICK_ETERNITY;
1890 socket->s->req->wex = TICK_ETERNITY;
1891 socket->s->req->analyse_exp = TICK_ETERNITY;
1892
1893 socket->s->rep->analysers = 0;
1894 socket->s->rep->rto = socket_proxy.timeout.server;
1895 socket->s->rep->wto = socket_proxy.timeout.client;
1896 socket->s->rep->rex = TICK_ETERNITY;
1897 socket->s->rep->wex = TICK_ETERNITY;
1898 socket->s->rep->analyse_exp = TICK_ETERNITY;
1899
1900 /*
1901 *
1902 * Configure the session.
1903 *
1904 */
1905
1906 /* The session dont have listener. The listener is used with real
1907 * proxies.
1908 */
1909 socket->s->listener = NULL;
1910
1911 /* The flags are initialized to 0. Values are setted later. */
1912 socket->s->flags = 0;
1913
1914 /* Assign the configured proxy to the new session. */
1915 socket->s->be = &socket_proxy;
1916 socket->s->fe = &socket_proxy;
1917
1918 /* XXX: Set namy variables */
1919 socket->s->store_count = 0;
1920 memset(socket->s->stkctr, 0, sizeof(socket->s->stkctr));
1921
1922 /* Configure logs. */
1923 socket->s->logs.logwait = 0;
1924 socket->s->logs.level = 0;
1925 socket->s->logs.accept_date = date; /* user-visible date for logging */
1926 socket->s->logs.tv_accept = now; /* corrected date for internal use */
1927 socket->s->do_log = NULL;
1928
1929 /* Function used if an error is occured. */
1930 socket->s->srv_error = default_srv_error;
1931
1932 /* Init the list of buffers. */
1933 LIST_INIT(&socket->s->buffer_wait);
1934
1935 /* Dont configure the unique ID. */
1936 socket->s->uniq_id = 0;
1937 socket->s->unique_id = NULL;
1938
1939 /* XXX: ? */
1940 socket->s->pend_pos = NULL;
1941
1942 /* XXX: See later. */
1943 socket->s->txn.sessid = NULL;
1944 socket->s->txn.srv_cookie = NULL;
1945 socket->s->txn.cli_cookie = NULL;
1946 socket->s->txn.uri = NULL;
1947 socket->s->txn.req.cap = NULL;
1948 socket->s->txn.rsp.cap = NULL;
1949 socket->s->txn.hdr_idx.v = NULL;
1950 socket->s->txn.hdr_idx.size = 0;
1951 socket->s->txn.hdr_idx.used = 0;
1952
1953 /* Configure "left" stream interface as applet. This "si" produce
1954 * and use the data received from the server. The applet is initialized
1955 * and is attached to the stream interface.
1956 */
1957
1958 /* The data producer is already connected. It is the applet. */
1959 socket->s->req->flags = CF_READ_ATTACHED;
1960
1961 channel_auto_connect(socket->s->req); /* don't wait to establish connection */
1962 channel_auto_close(socket->s->req); /* let the producer forward close requests */
1963
1964 si_reset(&socket->s->si[0], socket->s->task);
1965 si_set_state(&socket->s->si[0], SI_ST_EST); /* connection established (resource exists) */
1966
1967 appctx = stream_int_register_handler(&socket->s->si[0], &update_applet);
1968 if (!appctx)
1969 goto out_fail_conn1;
1970 appctx->ctx.hlua.socket = socket;
1971 appctx->ctx.hlua.connected = 0;
1972 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
1973 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
1974
1975 /* Configure "right" stream interface. this "si" is used to connect
1976 * and retrieve data from the server. The connection is initialized
1977 * with the "struct server".
1978 */
1979 si_reset(&socket->s->si[1], socket->s->task);
1980 si_set_state(&socket->s->si[1], SI_ST_INI);
1981 socket->s->si[1].conn_retries = socket_proxy.conn_retries;
1982
1983 /* Force destination server. */
1984 socket->s->flags |= SN_DIRECT | SN_ASSIGNED | SN_ADDR_SET | SN_BE_ASSIGNED;
1985 socket->s->target = &socket_tcp.obj_type;
1986
1987 /* This session is added to te lists of alive sessions. */
1988 LIST_ADDQ(&sessions, &socket->s->list);
1989
1990 /* XXX: I think that this list is used by stats. */
1991 LIST_INIT(&socket->s->back_refs);
1992
1993 /* Update statistics counters. */
1994 socket_proxy.feconn++; /* beconn will be increased later */
1995 jobs++;
1996 totalconn++;
1997
1998 /* Return yield waiting for connection. */
1999 return 1;
2000
2001out_fail_conn1:
2002 pool_free2(pool2_buffer, socket->s->rep->buf);
2003out_fail_rep_buf:
2004 pool_free2(pool2_channel, socket->s->rep);
2005out_fail_rep:
2006 pool_free2(pool2_buffer, socket->s->req->buf);
2007out_fail_req_buf:
2008 pool_free2(pool2_channel, socket->s->req);
2009out_fail_req:
2010 task_free(socket->s->task);
2011out_free_session:
2012 pool_free2(pool2_session, socket->s);
2013out_fail_conf:
2014 WILL_LJMP(lua_error(L));
2015 return 0;
2016}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002017
2018/*
2019 *
2020 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002021 * Class Channel
2022 *
2023 *
2024 */
2025
2026/* Returns the struct hlua_channel join to the class channel in the
2027 * stack entry "ud" or throws an argument error.
2028 */
2029__LJMP static struct hlua_channel *hlua_checkchannel(lua_State *L, int ud)
2030{
2031 return (struct hlua_channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
2032}
2033
2034/* Creates new channel object and put it on the top of the stack.
2035 * If the stask does not have a free slots, the function fails
2036 * and returns 0;
2037 */
Thierry FOURNIERbd1f1322015-03-05 17:04:41 +01002038static int hlua_channel_new(lua_State *L, struct session *s, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002039{
2040 struct hlua_channel *chn;
2041
2042 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002043 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002044 return 0;
2045
2046 /* NOTE: The allocation never fails. The failure
2047 * throw an error, and the function never returns.
2048 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002049 lua_newtable(L);
2050 chn = MAY_LJMP(lua_newuserdata(L, sizeof(*chn)));
2051 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002052 chn->chn = channel;
Thierry FOURNIERbd1f1322015-03-05 17:04:41 +01002053 chn->s = s;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002054
2055 /* Pop a class sesison metatable and affect it to the userdata. */
2056 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2057 lua_setmetatable(L, -2);
2058
2059 return 1;
2060}
2061
2062/* Duplicate all the data present in the input channel and put it
2063 * in a string LUA variables. Returns -1 and push a nil value in
2064 * the stack if the channel is closed and all the data are consumed,
2065 * returns 0 if no data are available, otherwise it returns the length
2066 * of the builded string.
2067 */
2068static inline int _hlua_channel_dup(struct hlua_channel *chn, lua_State *L)
2069{
2070 char *blk1;
2071 char *blk2;
2072 int len1;
2073 int len2;
2074 int ret;
2075 luaL_Buffer b;
2076
2077 ret = bi_getblk_nc(chn->chn, &blk1, &len1, &blk2, &len2);
2078 if (unlikely(ret == 0))
2079 return 0;
2080
2081 if (unlikely(ret < 0)) {
2082 lua_pushnil(L);
2083 return -1;
2084 }
2085
2086 luaL_buffinit(L, &b);
2087 luaL_addlstring(&b, blk1, len1);
2088 if (unlikely(ret == 2))
2089 luaL_addlstring(&b, blk2, len2);
2090 luaL_pushresult(&b);
2091
2092 if (unlikely(ret == 2))
2093 return len1 + len2;
2094 return len1;
2095}
2096
2097/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2098 * a yield. This function keep the data in the buffer.
2099 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002100__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002101{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002102 struct hlua_channel *chn;
2103
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002104 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2105
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002106 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002107 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002108 return 1;
2109}
2110
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002111/* Check arguments for the function "hlua_channel_dup_yield". */
2112__LJMP static int hlua_channel_dup(lua_State *L)
2113{
2114 MAY_LJMP(check_args(L, 1, "dup"));
2115 MAY_LJMP(hlua_checkchannel(L, 1));
2116 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2117}
2118
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002119/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2120 * a yield. This function consumes the data in the buffer. It returns
2121 * a string containing the data or a nil pointer if no data are available
2122 * and the channel is closed.
2123 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002124__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002125{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002126 struct hlua_channel *chn;
2127 int ret;
2128
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002129 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002130
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002131 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002132 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002133 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002134
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002135 if (unlikely(ret == -1))
2136 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002137
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002138 chn->chn->buf->i -= ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002139 return 1;
2140}
2141
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002142/* Check arguments for the fucntion "hlua_channel_get_yield". */
2143__LJMP static int hlua_channel_get(lua_State *L)
2144{
2145 MAY_LJMP(check_args(L, 1, "get"));
2146 MAY_LJMP(hlua_checkchannel(L, 1));
2147 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2148}
2149
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002150/* This functions consumes and returns one line. If the channel is closed,
2151 * and the last data does not contains a final '\n', the data are returned
2152 * without the final '\n'. When no more data are avalaible, it returns nil
2153 * value.
2154 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002155__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002156{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002157 char *blk1;
2158 char *blk2;
2159 int len1;
2160 int len2;
2161 int len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002162 struct hlua_channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002163 int ret;
2164 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002165
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002166 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2167
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002168 ret = bi_getline_nc(chn->chn, &blk1, &len1, &blk2, &len2);
2169 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002170 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002171
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002172 if (ret == -1) {
2173 lua_pushnil(L);
2174 return 1;
2175 }
2176
2177 luaL_buffinit(L, &b);
2178 luaL_addlstring(&b, blk1, len1);
2179 len = len1;
2180 if (unlikely(ret == 2)) {
2181 luaL_addlstring(&b, blk2, len2);
2182 len += len2;
2183 }
2184 luaL_pushresult(&b);
2185 buffer_replace2(chn->chn->buf, chn->chn->buf->p, chn->chn->buf->p + len, NULL, 0);
2186 return 1;
2187}
2188
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002189/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2190__LJMP static int hlua_channel_getline(lua_State *L)
2191{
2192 MAY_LJMP(check_args(L, 1, "getline"));
2193 MAY_LJMP(hlua_checkchannel(L, 1));
2194 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2195}
2196
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002197/* This function takes a string as input, and append it at the
2198 * input side of channel. If the data is too big, but a space
2199 * is probably available after sending some data, the function
2200 * yield. If the data is bigger than the buffer, or if the
2201 * channel is closed, it returns -1. otherwise, it returns the
2202 * amount of data writed.
2203 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002204__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002205{
2206 struct hlua_channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
2207 size_t len;
2208 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2209 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2210 int ret;
2211 int max;
2212
2213 max = channel_recv_limit(chn->chn) - buffer_len(chn->chn->buf);
2214 if (max > len - l)
2215 max = len - l;
2216
2217 ret = bi_putblk(chn->chn, str+l, max);
2218 if (ret == -2 || ret == -3) {
2219 lua_pushinteger(L, -1);
2220 return 1;
2221 }
2222 if (ret == -1)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002223 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002224 l += ret;
2225 lua_pop(L, 1);
2226 lua_pushinteger(L, l);
2227
2228 max = channel_recv_limit(chn->chn) - buffer_len(chn->chn->buf);
2229 if (max == 0 && chn->chn->buf->o == 0) {
2230 /* There are no space avalaible, and the output buffer is empty.
2231 * in this case, we cannot add more data, so we cannot yield,
2232 * we return the amount of copyied data.
2233 */
2234 return 1;
2235 }
2236 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002237 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002238 return 1;
2239}
2240
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002241/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002242 * of the writed string, or -1 if the channel is closed or if the
2243 * buffer size is too little for the data.
2244 */
2245__LJMP static int hlua_channel_append(lua_State *L)
2246{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002247 size_t len;
2248
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002249 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002250 MAY_LJMP(hlua_checkchannel(L, 1));
2251 MAY_LJMP(luaL_checklstring(L, 2, &len));
2252 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002253 lua_pushinteger(L, 0);
2254
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002255 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002256}
2257
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002258/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002259 * his process by cleaning the buffer. The result is a replacement
2260 * of the current data. It returns the length of the writed string,
2261 * or -1 if the channel is closed or if the buffer size is too
2262 * little for the data.
2263 */
2264__LJMP static int hlua_channel_set(lua_State *L)
2265{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002266 struct hlua_channel *chn;
2267
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002268 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002269 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002270 lua_pushinteger(L, 0);
2271
2272 chn->chn->buf->i = 0;
2273
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002274 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002275}
2276
2277/* Append data in the output side of the buffer. This data is immediatly
2278 * sent. The fcuntion returns the ammount of data writed. If the buffer
2279 * cannot contains the data, the function yield. The function returns -1
2280 * if the channel is closed.
2281 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002282__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002283{
2284 struct hlua_channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
2285 size_t len;
2286 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2287 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2288 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002289 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002290
2291 if (unlikely(channel_output_closed(chn->chn))) {
2292 lua_pushinteger(L, -1);
2293 return 1;
2294 }
2295
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002296 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2297 * the request buffer if its not required.
2298 */
2299 if (chn->chn->buf->size == 0) {
2300 if (!session_alloc_recv_buffer(chn->s, &chn->chn->buf)) {
2301 chn->chn->prod->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002302 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002303 }
2304 }
2305
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002306 /* the writed data will be immediatly sent, so we can check
2307 * the avalaible space without taking in account the reserve.
2308 * The reserve is guaranted for the processing of incoming
2309 * data, because the buffer will be flushed.
2310 */
2311 max = chn->chn->buf->size - buffer_len(chn->chn->buf);
2312
2313 /* If there are no space avalaible, and the output buffer is empty.
2314 * in this case, we cannot add more data, so we cannot yield,
2315 * we return the amount of copyied data.
2316 */
2317 if (max == 0 && chn->chn->buf->o == 0)
2318 return 1;
2319
2320 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002321 if (max > len - l)
2322 max = len - l;
2323
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002324 /* The buffer avalaible size may be not contiguous. This test
2325 * detects a non contiguous buffer and realign it.
2326 */
Thierry FOURNIERd2b597a2015-03-07 14:38:50 +01002327 if (bi_space_for_replace(chn->chn->buf) < max)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002328 buffer_slow_realign(chn->chn->buf);
2329
2330 /* Copy input data in the buffer. */
Thierry FOURNIER506e46c2015-03-04 11:44:47 +01002331 max = buffer_replace2(chn->chn->buf, chn->chn->buf->p, chn->chn->buf->p, str+l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002332
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002333 /* buffer replace considers that the input part is filled.
2334 * so, I must forward these new data in the output part.
2335 */
2336 b_adv(chn->chn->buf, max);
2337
2338 l += max;
2339 lua_pop(L, 1);
2340 lua_pushinteger(L, l);
2341
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002342 /* If there are no space avalaible, and the output buffer is empty.
2343 * in this case, we cannot add more data, so we cannot yield,
2344 * we return the amount of copyied data.
2345 */
2346 max = chn->chn->buf->size - buffer_len(chn->chn->buf);
2347 if (max == 0 && chn->chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002348 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002349
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002350 if (l < len) {
2351 /* If we are waiting for space in the response buffer, we
2352 * must set the flag WAKERESWR. This flag required the task
2353 * wake up if any activity is detected on the response buffer.
2354 */
2355 if (chn->chn == chn->s->rep)
2356 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002357 else
2358 HLUA_SET_WAKEREQWR(hlua);
2359 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002360 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002361
2362 return 1;
2363}
2364
2365/* Just a wraper of "_hlua_channel_send". This wrapper permits
2366 * yield the LUA process, and resume it without checking the
2367 * input arguments.
2368 */
2369__LJMP static int hlua_channel_send(lua_State *L)
2370{
2371 MAY_LJMP(check_args(L, 2, "send"));
2372 lua_pushinteger(L, 0);
2373
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002374 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002375}
2376
2377/* This function forward and amount of butes. The data pass from
2378 * the input side of the buffer to the output side, and can be
2379 * forwarded. This function never fails.
2380 *
2381 * The Lua function takes an amount of bytes to be forwarded in
2382 * imput. It returns the number of bytes forwarded.
2383 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002384__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002385{
2386 struct hlua_channel *chn;
2387 int len;
2388 int l;
2389 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002390 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002391
2392 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2393 len = MAY_LJMP(luaL_checkinteger(L, 2));
2394 l = MAY_LJMP(luaL_checkinteger(L, -1));
2395
2396 max = len - l;
2397 if (max > chn->chn->buf->i)
2398 max = chn->chn->buf->i;
2399 channel_forward(chn->chn, max);
2400 l += max;
2401
2402 lua_pop(L, 1);
2403 lua_pushinteger(L, l);
2404
2405 /* Check if it miss bytes to forward. */
2406 if (l < len) {
2407 /* The the input channel or the output channel are closed, we
2408 * must return the amount of data forwarded.
2409 */
2410 if (channel_input_closed(chn->chn) || channel_output_closed(chn->chn))
2411 return 1;
2412
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002413 /* If we are waiting for space data in the response buffer, we
2414 * must set the flag WAKERESWR. This flag required the task
2415 * wake up if any activity is detected on the response buffer.
2416 */
2417 if (chn->chn == chn->s->rep)
2418 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002419 else
2420 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002421
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002422 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002423 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002424 }
2425
2426 return 1;
2427}
2428
2429/* Just check the input and prepare the stack for the previous
2430 * function "hlua_channel_forward_yield"
2431 */
2432__LJMP static int hlua_channel_forward(lua_State *L)
2433{
2434 MAY_LJMP(check_args(L, 2, "forward"));
2435 MAY_LJMP(hlua_checkchannel(L, 1));
2436 MAY_LJMP(luaL_checkinteger(L, 2));
2437
2438 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002439 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002440}
2441
2442/* Just returns the number of bytes available in the input
2443 * side of the buffer. This function never fails.
2444 */
2445__LJMP static int hlua_channel_get_in_len(lua_State *L)
2446{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002447 struct hlua_channel *chn;
2448
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002449 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002450 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002451 lua_pushinteger(L, chn->chn->buf->i);
2452 return 1;
2453}
2454
2455/* Just returns the number of bytes available in the output
2456 * side of the buffer. This function never fails.
2457 */
2458__LJMP static int hlua_channel_get_out_len(lua_State *L)
2459{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002460 struct hlua_channel *chn;
2461
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002462 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002463 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002464 lua_pushinteger(L, chn->chn->buf->o);
2465 return 1;
2466}
2467
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002468/*
2469 *
2470 *
2471 * Class Fetches
2472 *
2473 *
2474 */
2475
2476/* Returns a struct hlua_session if the stack entry "ud" is
2477 * a class session, otherwise it throws an error.
2478 */
2479__LJMP static struct hlua_txn *hlua_checkfetches(lua_State *L, int ud)
2480{
2481 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
2482}
2483
2484/* This function creates and push in the stack a fetch object according
2485 * with a current TXN.
2486 */
2487static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn)
2488{
2489 struct hlua_txn *hs;
2490
2491 /* Check stack size. */
2492 if (!lua_checkstack(L, 3))
2493 return 0;
2494
2495 /* Create the object: obj[0] = userdata.
2496 * Note that the base of the Fetches object is the
2497 * transaction object.
2498 */
2499 lua_newtable(L);
2500 hs = lua_newuserdata(L, sizeof(struct hlua_txn));
2501 lua_rawseti(L, -2, 0);
2502
2503 hs->s = txn->s;
2504 hs->p = txn->p;
2505 hs->l7 = txn->l7;
2506
2507 /* Pop a class sesison metatable and affect it to the userdata. */
2508 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2509 lua_setmetatable(L, -2);
2510
2511 return 1;
2512}
2513
2514/* This function is an LUA binding. It is called with each sample-fetch.
2515 * It uses closure argument to store the associated sample-fetch. It
2516 * returns only one argument or throws an error. An error is thrown
2517 * only if an error is encountered during the argument parsing. If
2518 * the "sample-fetch" function fails, nil is returned.
2519 */
2520__LJMP static int hlua_run_sample_fetch(lua_State *L)
2521{
2522 struct hlua_txn *s;
2523 struct hlua_sample_fetch *f;
2524 struct arg args[ARGM_NBARGS + 1];
2525 int i;
2526 struct sample smp;
2527
2528 /* Get closure arguments. */
2529 f = (struct hlua_sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
2530
2531 /* Get traditionnal arguments. */
2532 s = MAY_LJMP(hlua_checkfetches(L, 1));
2533
2534 /* Get extra arguments. */
2535 for (i = 0; i < lua_gettop(L) - 1; i++) {
2536 if (i >= ARGM_NBARGS)
2537 break;
2538 hlua_lua2arg(L, i + 2, &args[i]);
2539 }
2540 args[i].type = ARGT_STOP;
2541
2542 /* Check arguments. */
2543 MAY_LJMP(hlua_lua2arg_check(L, 1, args, f->f->arg_mask));
2544
2545 /* Run the special args checker. */
2546 if (f->f->val_args && !f->f->val_args(args, NULL)) {
2547 lua_pushfstring(L, "error in arguments");
2548 WILL_LJMP(lua_error(L));
2549 }
2550
2551 /* Initialise the sample. */
2552 memset(&smp, 0, sizeof(smp));
2553
2554 /* Run the sample fetch process. */
2555 if (!f->f->process(s->p, s->s, s->l7, 0, args, &smp, f->f->kw, f->f->private)) {
2556 lua_pushnil(L);
2557 return 1;
2558 }
2559
2560 /* Convert the returned sample in lua value. */
2561 hlua_smp2lua(L, &smp);
2562 return 1;
2563}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002564
2565/*
2566 *
2567 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002568 * Class TXN
2569 *
2570 *
2571 */
2572
2573/* Returns a struct hlua_session if the stack entry "ud" is
2574 * a class session, otherwise it throws an error.
2575 */
2576__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
2577{
2578 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
2579}
2580
Willy Tarreau59551662015-03-10 14:23:13 +01002581__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002582{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002583 struct hlua *hlua;
2584
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002585 MAY_LJMP(check_args(L, 2, "set_priv"));
2586
2587 /* It is useles to retrieve the session, but this function
2588 * runs only in a session context.
2589 */
2590 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002591 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002592
2593 /* Remove previous value. */
2594 if (hlua->Mref != -1)
2595 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
2596
2597 /* Get and store new value. */
2598 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
2599 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
2600
2601 return 0;
2602}
2603
Willy Tarreau59551662015-03-10 14:23:13 +01002604__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002605{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002606 struct hlua *hlua;
2607
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002608 MAY_LJMP(check_args(L, 1, "get_priv"));
2609
2610 /* It is useles to retrieve the session, but this function
2611 * runs only in a session context.
2612 */
2613 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002614 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002615
2616 /* Push configuration index in the stack. */
2617 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
2618
2619 return 1;
2620}
2621
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002622/* Create stack entry containing a class TXN. This function
2623 * return 0 if the stack does not contains free slots,
2624 * otherwise it returns 1.
2625 */
2626static int hlua_txn_new(lua_State *L, struct session *s, struct proxy *p, void *l7)
2627{
2628 struct hlua_txn *hs;
2629
2630 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002631 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002632 return 0;
2633
2634 /* NOTE: The allocation never fails. The failure
2635 * throw an error, and the function never returns.
2636 * if the throw is not avalaible, the process is aborted.
2637 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002638 /* Create the object: obj[0] = userdata. */
2639 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002640 hs = lua_newuserdata(L, sizeof(struct hlua_txn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002641 lua_rawseti(L, -2, 0);
2642
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002643 hs->s = s;
2644 hs->p = p;
2645 hs->l7 = l7;
2646
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002647 /* Create the "f" field that contains a list of fetches. */
2648 lua_pushstring(L, "f");
2649 if (!hlua_fetches_new(L, hs))
2650 return 0;
2651 lua_settable(L, -3);
2652
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002653 /* Pop a class sesison metatable and affect it to the userdata. */
2654 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
2655 lua_setmetatable(L, -2);
2656
2657 return 1;
2658}
2659
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002660/* This function returns a channel object associated
2661 * with the request channel. This function never fails,
2662 * however if the stack is full, it throws an error.
2663 */
2664__LJMP static int hlua_txn_req_channel(lua_State *L)
2665{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002666 struct hlua_txn *s;
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002667
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002668 MAY_LJMP(check_args(L, 1, "req_channel"));
2669 s = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002670
Thierry FOURNIERbd1f1322015-03-05 17:04:41 +01002671 if (!hlua_channel_new(L, s->s, s->s->req))
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002672 WILL_LJMP(luaL_error(L, "full stack"));
2673
2674 return 1;
2675}
2676
2677/* This function returns a channel object associated
2678 * with the response channel. This function never fails,
2679 * however if the stack is full, it throws an error.
2680 */
2681__LJMP static int hlua_txn_res_channel(lua_State *L)
2682{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002683 struct hlua_txn *s;
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002684
Willy Tarreaueee45392015-03-10 14:22:28 +01002685 MAY_LJMP(check_args(L, 1, "res_channel"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002686 s = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002687
Thierry FOURNIERbd1f1322015-03-05 17:04:41 +01002688 if (!hlua_channel_new(L, s->s, s->s->rep))
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002689 WILL_LJMP(luaL_error(L, "full stack"));
2690
2691 return 1;
2692}
2693
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002694/* This function is an Lua binding that send pending data
2695 * to the client, and close the stream interface.
2696 */
2697__LJMP static int hlua_txn_close(lua_State *L)
2698{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002699 struct hlua_txn *s;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002700
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002701 MAY_LJMP(check_args(L, 1, "close"));
2702 s = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002703
2704 channel_abort(s->s->si[0].ib);
2705 channel_auto_close(s->s->si[0].ib);
2706 channel_erase(s->s->si[0].ib);
2707 channel_auto_read(s->s->si[0].ob);
2708 channel_auto_close(s->s->si[0].ob);
2709 channel_shutr_now(s->s->si[0].ob);
2710
2711 return 0;
2712}
2713
Thierry FOURNIER9a819e72015-02-16 20:22:55 +01002714/* This function is an LUA binding. It creates ans returns
2715 * an array of HTTP headers. This function does not fails.
2716 */
Willy Tarreau59551662015-03-10 14:23:13 +01002717static int hlua_session_get_headers(lua_State *L)
Thierry FOURNIER9a819e72015-02-16 20:22:55 +01002718{
2719 struct hlua_txn *s = MAY_LJMP(hlua_checktxn(L, 1));
2720 struct session *sess = s->s;
2721 const char *cur_ptr, *cur_next, *p;
2722 int old_idx, cur_idx;
2723 struct hdr_idx_elem *cur_hdr;
2724 const char *hn, *hv;
2725 int hnl, hvl;
2726
2727 /* Create the table. */
2728 lua_newtable(L);
2729
2730 /* Build array of headers. */
2731 old_idx = 0;
2732 cur_next = sess->req->buf->p + hdr_idx_first_pos(&sess->txn.hdr_idx);
2733
2734 while (1) {
2735 cur_idx = sess->txn.hdr_idx.v[old_idx].next;
2736 if (!cur_idx)
2737 break;
2738 old_idx = cur_idx;
2739
2740 cur_hdr = &sess->txn.hdr_idx.v[cur_idx];
2741 cur_ptr = cur_next;
2742 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
2743
2744 /* Now we have one full header at cur_ptr of len cur_hdr->len,
2745 * and the next header starts at cur_next. We'll check
2746 * this header in the list as well as against the default
2747 * rule.
2748 */
2749
2750 /* look for ': *'. */
2751 hn = cur_ptr;
2752 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
2753 if (p >= cur_ptr+cur_hdr->len)
2754 continue;
2755 hnl = p - hn;
2756 p++;
2757 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
2758 p++;
2759 if (p >= cur_ptr+cur_hdr->len)
2760 continue;
2761 hv = p;
2762 hvl = cur_ptr+cur_hdr->len-p;
2763
2764 /* Push values in the table. */
2765 lua_pushlstring(L, hn, hnl);
2766 lua_pushlstring(L, hv, hvl);
2767 lua_settable(L, -3);
2768 }
2769
2770 return 1;
2771}
2772
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002773__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002774{
2775 int wakeup_ms = lua_tointeger(L, -1);
2776 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002777 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002778 return 0;
2779}
2780
2781__LJMP static int hlua_sleep(lua_State *L)
2782{
2783 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002784 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002785
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002786 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002787
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002788 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002789 wakeup_ms = tick_add(now_ms, delay);
2790 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002791
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002792 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
2793 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002794}
2795
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002796__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002797{
2798 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002799 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002800
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002801 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002802
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002803 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002804 wakeup_ms = tick_add(now_ms, delay);
2805 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002806
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002807 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
2808 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002809}
2810
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01002811/* This functionis an LUA binding. it permits to give back
2812 * the hand at the HAProxy scheduler. It is used when the
2813 * LUA processing consumes a lot of time.
2814 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002815__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002816{
2817 return 0;
2818}
2819
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01002820__LJMP static int hlua_yield(lua_State *L)
2821{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002822 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
2823 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01002824}
2825
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002826/* This function change the nice of the currently executed
2827 * task. It is used set low or high priority at the current
2828 * task.
2829 */
Willy Tarreau59551662015-03-10 14:23:13 +01002830__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002831{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002832 struct hlua *hlua;
2833 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002834
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002835 MAY_LJMP(check_args(L, 1, "set_nice"));
2836 hlua = hlua_gethlua(L);
2837 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002838
2839 /* If he task is not set, I'm in a start mode. */
2840 if (!hlua || !hlua->task)
2841 return 0;
2842
2843 if (nice < -1024)
2844 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002845 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002846 nice = 1024;
2847
2848 hlua->task->nice = nice;
2849 return 0;
2850}
2851
Thierry FOURNIER24f33532015-01-23 12:13:00 +01002852/* This function is used as a calback of a task. It is called by the
2853 * HAProxy task subsystem when the task is awaked. The LUA runtime can
2854 * return an E_AGAIN signal, the emmiter of this signal must set a
2855 * signal to wake the task.
2856 */
2857static struct task *hlua_process_task(struct task *task)
2858{
2859 struct hlua *hlua = task->context;
2860 enum hlua_exec status;
2861
2862 /* We need to remove the task from the wait queue before executing
2863 * the Lua code because we don't know if it needs to wait for
2864 * another timer or not in the case of E_AGAIN.
2865 */
2866 task_delete(task);
2867
Thierry FOURNIERbd413492015-03-03 16:52:26 +01002868 /* If it is the first call to the task, we must initialize the
2869 * execution timeouts.
2870 */
2871 if (!HLUA_IS_RUNNING(hlua))
2872 hlua->expire = tick_add(now_ms, hlua_timeout_task);
2873
Thierry FOURNIER24f33532015-01-23 12:13:00 +01002874 /* Execute the Lua code. */
2875 status = hlua_ctx_resume(hlua, 1);
2876
2877 switch (status) {
2878 /* finished or yield */
2879 case HLUA_E_OK:
2880 hlua_ctx_destroy(hlua);
2881 task_delete(task);
2882 task_free(task);
2883 break;
2884
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01002885 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
2886 if (hlua->wake_time != TICK_ETERNITY)
2887 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01002888 break;
2889
2890 /* finished with error. */
2891 case HLUA_E_ERRMSG:
2892 send_log(NULL, LOG_ERR, "Lua task: %s.", lua_tostring(hlua->T, -1));
2893 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2894 Alert("Lua task: %s.\n", lua_tostring(hlua->T, -1));
2895 hlua_ctx_destroy(hlua);
2896 task_delete(task);
2897 task_free(task);
2898 break;
2899
2900 case HLUA_E_ERR:
2901 default:
2902 send_log(NULL, LOG_ERR, "Lua task: unknown error.");
2903 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2904 Alert("Lua task: unknown error.\n");
2905 hlua_ctx_destroy(hlua);
2906 task_delete(task);
2907 task_free(task);
2908 break;
2909 }
2910 return NULL;
2911}
2912
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01002913/* This function is an LUA binding that register LUA function to be
2914 * executed after the HAProxy configuration parsing and before the
2915 * HAProxy scheduler starts. This function expect only one LUA
2916 * argument that is a function. This function returns nothing, but
2917 * throws if an error is encountered.
2918 */
2919__LJMP static int hlua_register_init(lua_State *L)
2920{
2921 struct hlua_init_function *init;
2922 int ref;
2923
2924 MAY_LJMP(check_args(L, 1, "register_init"));
2925
2926 ref = MAY_LJMP(hlua_checkfunction(L, 1));
2927
2928 init = malloc(sizeof(*init));
2929 if (!init)
2930 WILL_LJMP(luaL_error(L, "lua out of memory error."));
2931
2932 init->function_ref = ref;
2933 LIST_ADDQ(&hlua_init_functions, &init->l);
2934 return 0;
2935}
2936
Thierry FOURNIER24f33532015-01-23 12:13:00 +01002937/* This functio is an LUA binding. It permits to register a task
2938 * executed in parallel of the main HAroxy activity. The task is
2939 * created and it is set in the HAProxy scheduler. It can be called
2940 * from the "init" section, "post init" or during the runtime.
2941 *
2942 * Lua prototype:
2943 *
2944 * <none> core.register_task(<function>)
2945 */
2946static int hlua_register_task(lua_State *L)
2947{
2948 struct hlua *hlua;
2949 struct task *task;
2950 int ref;
2951
2952 MAY_LJMP(check_args(L, 1, "register_task"));
2953
2954 ref = MAY_LJMP(hlua_checkfunction(L, 1));
2955
2956 hlua = malloc(sizeof(*hlua));
2957 if (!hlua)
2958 WILL_LJMP(luaL_error(L, "lua out of memory error."));
2959
2960 task = task_new();
2961 task->context = hlua;
2962 task->process = hlua_process_task;
2963
2964 if (!hlua_ctx_init(hlua, task))
2965 WILL_LJMP(luaL_error(L, "lua out of memory error."));
2966
2967 /* Restore the function in the stack. */
2968 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
2969 hlua->nargs = 0;
2970
2971 /* Schedule task. */
2972 task_schedule(task, now_ms);
2973
2974 return 0;
2975}
2976
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01002977/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
2978 * doesn't allow "yield" functions because the HAProxy engine cannot
2979 * resume converters.
2980 */
2981static int hlua_sample_conv_wrapper(struct session *session, const struct arg *arg_p,
2982 struct sample *smp, void *private)
2983{
2984 struct hlua_function *fcn = (struct hlua_function *)private;
2985
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01002986 /* In the execution wrappers linked with a session, the
2987 * Lua context can be not initialized. This behavior
2988 * permits to save performances because a systematic
2989 * Lua initialization cause 5% performances loss.
2990 */
2991 if (!session->hlua.T && !hlua_ctx_init(&session->hlua, session->task)) {
2992 send_log(session->be, LOG_ERR, "Lua converter '%s': can't initialize Lua context.", fcn->name);
2993 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
2994 Alert("Lua converter '%s': can't initialize Lua context.\n", fcn->name);
2995 return 0;
2996 }
2997
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01002998 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01002999 if (!HLUA_IS_RUNNING(&session->hlua)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003000 /* Check stack available size. */
3001 if (!lua_checkstack(session->hlua.T, 1)) {
3002 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
3003 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3004 Alert("Lua converter '%s': full stack.\n", fcn->name);
3005 return 0;
3006 }
3007
3008 /* Restore the function in the stack. */
3009 lua_rawgeti(session->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
3010
3011 /* convert input sample and pust-it in the stack. */
3012 if (!lua_checkstack(session->hlua.T, 1)) {
3013 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
3014 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3015 Alert("Lua converter '%s': full stack.\n", fcn->name);
3016 return 0;
3017 }
3018 hlua_smp2lua(session->hlua.T, smp);
3019 session->hlua.nargs = 2;
3020
3021 /* push keywords in the stack. */
3022 if (arg_p) {
3023 for (; arg_p->type != ARGT_STOP; arg_p++) {
3024 if (!lua_checkstack(session->hlua.T, 1)) {
3025 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
3026 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3027 Alert("Lua converter '%s': full stack.\n", fcn->name);
3028 return 0;
3029 }
3030 hlua_arg2lua(session->hlua.T, arg_p);
3031 session->hlua.nargs++;
3032 }
3033 }
3034
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003035 /* We must initialize the execution timeouts. */
3036 session->hlua.expire = tick_add(now_ms, hlua_timeout_session);
3037
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003038 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003039 HLUA_SET_RUN(&session->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003040 }
3041
3042 /* Execute the function. */
3043 switch (hlua_ctx_resume(&session->hlua, 0)) {
3044 /* finished. */
3045 case HLUA_E_OK:
3046 /* Convert the returned value in sample. */
3047 hlua_lua2smp(session->hlua.T, -1, smp);
3048 lua_pop(session->hlua.T, 1);
3049 return 1;
3050
3051 /* yield. */
3052 case HLUA_E_AGAIN:
3053 send_log(session->be, LOG_ERR, "Lua converter '%s': cannot use yielded functions.", fcn->name);
3054 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3055 Alert("Lua converter '%s': cannot use yielded functions.\n", fcn->name);
3056 return 0;
3057
3058 /* finished with error. */
3059 case HLUA_E_ERRMSG:
3060 /* Display log. */
3061 send_log(session->be, LOG_ERR, "Lua converter '%s': %s.", fcn->name, lua_tostring(session->hlua.T, -1));
3062 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3063 Alert("Lua converter '%s': %s.\n", fcn->name, lua_tostring(session->hlua.T, -1));
3064 lua_pop(session->hlua.T, 1);
3065 return 0;
3066
3067 case HLUA_E_ERR:
3068 /* Display log. */
3069 send_log(session->be, LOG_ERR, "Lua converter '%s' returns an unknown error.", fcn->name);
3070 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3071 Alert("Lua converter '%s' returns an unknown error.\n", fcn->name);
3072
3073 default:
3074 return 0;
3075 }
3076}
3077
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003078/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
3079 * doesn't allow "yield" functions because the HAProxy engine cannot
3080 * resume sample-fetches.
3081 */
3082static int hlua_sample_fetch_wrapper(struct proxy *px, struct session *s, void *l7,
3083 unsigned int opt, const struct arg *arg_p,
3084 struct sample *smp, const char *kw, void *private)
3085{
3086 struct hlua_function *fcn = (struct hlua_function *)private;
3087
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003088 /* In the execution wrappers linked with a session, the
3089 * Lua context can be not initialized. This behavior
3090 * permits to save performances because a systematic
3091 * Lua initialization cause 5% performances loss.
3092 */
3093 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
3094 send_log(s->be, LOG_ERR, "Lua sample-fetch '%s': can't initialize Lua context.", fcn->name);
3095 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3096 Alert("Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
3097 return 0;
3098 }
3099
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003100 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003101 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003102 /* Check stack available size. */
3103 if (!lua_checkstack(s->hlua.T, 2)) {
3104 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3105 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3106 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3107 return 0;
3108 }
3109
3110 /* Restore the function in the stack. */
3111 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
3112
3113 /* push arguments in the stack. */
3114 if (!hlua_txn_new(s->hlua.T, s, px, l7)) {
3115 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3116 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3117 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3118 return 0;
3119 }
3120 s->hlua.nargs = 1;
3121
3122 /* push keywords in the stack. */
3123 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
3124 /* Check stack available size. */
3125 if (!lua_checkstack(s->hlua.T, 1)) {
3126 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3127 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3128 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3129 return 0;
3130 }
3131 if (!lua_checkstack(s->hlua.T, 1)) {
3132 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3133 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3134 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3135 return 0;
3136 }
3137 hlua_arg2lua(s->hlua.T, arg_p);
3138 s->hlua.nargs++;
3139 }
3140
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003141 /* We must initialize the execution timeouts. */
3142 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
3143
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003144 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003145 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003146 }
3147
3148 /* Execute the function. */
3149 switch (hlua_ctx_resume(&s->hlua, 0)) {
3150 /* finished. */
3151 case HLUA_E_OK:
3152 /* Convert the returned value in sample. */
3153 hlua_lua2smp(s->hlua.T, -1, smp);
3154 lua_pop(s->hlua.T, 1);
3155
3156 /* Set the end of execution flag. */
3157 smp->flags &= ~SMP_F_MAY_CHANGE;
3158 return 1;
3159
3160 /* yield. */
3161 case HLUA_E_AGAIN:
3162 send_log(px, LOG_ERR, "Lua sample-fetch '%s': cannot use yielded functions.", fcn->name);
3163 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3164 Alert("Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
3165 return 0;
3166
3167 /* finished with error. */
3168 case HLUA_E_ERRMSG:
3169 /* Display log. */
3170 send_log(px, LOG_ERR, "Lua sample-fetch '%s': %s.", fcn->name, lua_tostring(s->hlua.T, -1));
3171 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3172 Alert("Lua sample-fetch '%s': %s.\n", fcn->name, lua_tostring(s->hlua.T, -1));
3173 lua_pop(s->hlua.T, 1);
3174 return 0;
3175
3176 case HLUA_E_ERR:
3177 /* Display log. */
3178 send_log(px, LOG_ERR, "Lua sample-fetch '%s' returns an unknown error.", fcn->name);
3179 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3180 Alert("Lua sample-fetch '%s': returns an unknown error.\n", fcn->name);
3181
3182 default:
3183 return 0;
3184 }
3185}
3186
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003187/* This function is an LUA binding used for registering
3188 * "sample-conv" functions. It expects a converter name used
3189 * in the haproxy configuration file, and an LUA function.
3190 */
3191__LJMP static int hlua_register_converters(lua_State *L)
3192{
3193 struct sample_conv_kw_list *sck;
3194 const char *name;
3195 int ref;
3196 int len;
3197 struct hlua_function *fcn;
3198
3199 MAY_LJMP(check_args(L, 2, "register_converters"));
3200
3201 /* First argument : converter name. */
3202 name = MAY_LJMP(luaL_checkstring(L, 1));
3203
3204 /* Second argument : lua function. */
3205 ref = MAY_LJMP(hlua_checkfunction(L, 2));
3206
3207 /* Allocate and fill the sample fetch keyword struct. */
3208 sck = malloc(sizeof(struct sample_conv_kw_list) +
3209 sizeof(struct sample_conv) * 2);
3210 if (!sck)
3211 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3212 fcn = malloc(sizeof(*fcn));
3213 if (!fcn)
3214 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3215
3216 /* Fill fcn. */
3217 fcn->name = strdup(name);
3218 if (!fcn->name)
3219 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3220 fcn->function_ref = ref;
3221
3222 /* List head */
3223 sck->list.n = sck->list.p = NULL;
3224
3225 /* converter keyword. */
3226 len = strlen("lua.") + strlen(name) + 1;
3227 sck->kw[0].kw = malloc(len);
3228 if (!sck->kw[0].kw)
3229 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3230
3231 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
3232 sck->kw[0].process = hlua_sample_conv_wrapper;
3233 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
3234 sck->kw[0].val_args = NULL;
3235 sck->kw[0].in_type = SMP_T_STR;
3236 sck->kw[0].out_type = SMP_T_STR;
3237 sck->kw[0].private = fcn;
3238
3239 /* End of array. */
3240 memset(&sck->kw[1], 0, sizeof(struct sample_conv));
3241
3242 /* Register this new converter */
3243 sample_register_convs(sck);
3244
3245 return 0;
3246}
3247
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003248/* This fucntion is an LUA binding used for registering
3249 * "sample-fetch" functions. It expects a converter name used
3250 * in the haproxy configuration file, and an LUA function.
3251 */
3252__LJMP static int hlua_register_fetches(lua_State *L)
3253{
3254 const char *name;
3255 int ref;
3256 int len;
3257 struct sample_fetch_kw_list *sfk;
3258 struct hlua_function *fcn;
3259
3260 MAY_LJMP(check_args(L, 2, "register_fetches"));
3261
3262 /* First argument : sample-fetch name. */
3263 name = MAY_LJMP(luaL_checkstring(L, 1));
3264
3265 /* Second argument : lua function. */
3266 ref = MAY_LJMP(hlua_checkfunction(L, 2));
3267
3268 /* Allocate and fill the sample fetch keyword struct. */
3269 sfk = malloc(sizeof(struct sample_fetch_kw_list) +
3270 sizeof(struct sample_fetch) * 2);
3271 if (!sfk)
3272 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3273 fcn = malloc(sizeof(*fcn));
3274 if (!fcn)
3275 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3276
3277 /* Fill fcn. */
3278 fcn->name = strdup(name);
3279 if (!fcn->name)
3280 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3281 fcn->function_ref = ref;
3282
3283 /* List head */
3284 sfk->list.n = sfk->list.p = NULL;
3285
3286 /* sample-fetch keyword. */
3287 len = strlen("lua.") + strlen(name) + 1;
3288 sfk->kw[0].kw = malloc(len);
3289 if (!sfk->kw[0].kw)
3290 return luaL_error(L, "lua out of memory error.");
3291
3292 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
3293 sfk->kw[0].process = hlua_sample_fetch_wrapper;
3294 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
3295 sfk->kw[0].val_args = NULL;
3296 sfk->kw[0].out_type = SMP_T_STR;
3297 sfk->kw[0].use = SMP_USE_HTTP_ANY;
3298 sfk->kw[0].val = 0;
3299 sfk->kw[0].private = fcn;
3300
3301 /* End of array. */
3302 memset(&sfk->kw[1], 0, sizeof(struct sample_fetch));
3303
3304 /* Register this new fetch. */
3305 sample_register_fetches(sfk);
3306
3307 return 0;
3308}
3309
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003310/* global {tcp|http}-request parser. Return 1 in succes case, else return 0. */
3311static int hlua_parse_rule(const char **args, int *cur_arg, struct proxy *px,
3312 struct hlua_rule **rule_p, char **err)
3313{
3314 struct hlua_rule *rule;
3315
3316 /* Memory for the rule. */
3317 rule = malloc(sizeof(*rule));
3318 if (!rule) {
3319 memprintf(err, "out of memory error");
3320 return 0;
3321 }
3322 *rule_p = rule;
3323
3324 /* The requiered arg is a function name. */
3325 if (!args[*cur_arg]) {
3326 memprintf(err, "expect Lua function name");
3327 return 0;
3328 }
3329
3330 /* Lookup for the symbol, and check if it is a function. */
3331 lua_getglobal(gL.T, args[*cur_arg]);
3332 if (lua_isnil(gL.T, -1)) {
3333 lua_pop(gL.T, 1);
3334 memprintf(err, "Lua function '%s' not found", args[*cur_arg]);
3335 return 0;
3336 }
3337 if (!lua_isfunction(gL.T, -1)) {
3338 lua_pop(gL.T, 1);
3339 memprintf(err, "'%s' is not a function", args[*cur_arg]);
3340 return 0;
3341 }
3342
3343 /* Reference the Lua function and store the reference. */
3344 rule->fcn.function_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
3345 rule->fcn.name = strdup(args[*cur_arg]);
3346 if (!rule->fcn.name) {
3347 memprintf(err, "out of memory error.");
3348 return 0;
3349 }
3350 (*cur_arg)++;
3351
3352 /* TODO: later accept arguments. */
3353 rule->args = NULL;
3354
3355 return 1;
3356}
3357
3358/* This function is a wrapper to execute each LUA function declared
3359 * as an action wrapper during the initialisation period. This function
3360 * return 1 if the processing is finished (with oe without error) and
3361 * return 0 if the function must be called again because the LUA
3362 * returns a yield.
3363 */
3364static int hlua_request_act_wrapper(struct hlua_rule *rule, struct proxy *px,
3365 struct session *s, struct http_txn *http_txn,
3366 unsigned int analyzer)
3367{
3368 char **arg;
3369
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003370 /* In the execution wrappers linked with a session, the
3371 * Lua context can be not initialized. This behavior
3372 * permits to save performances because a systematic
3373 * Lua initialization cause 5% performances loss.
3374 */
3375 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
3376 send_log(px, LOG_ERR, "Lua action '%s': can't initialize Lua context.", rule->fcn.name);
3377 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3378 Alert("Lua action '%s': can't initialize Lua context.\n", rule->fcn.name);
3379 return 0;
3380 }
3381
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003382 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003383 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003384 /* Check stack available size. */
3385 if (!lua_checkstack(s->hlua.T, 1)) {
3386 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
3387 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3388 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
3389 return 0;
3390 }
3391
3392 /* Restore the function in the stack. */
3393 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->fcn.function_ref);
3394
3395 /* Create and and push object session in the stack. */
3396 if (!hlua_txn_new(s->hlua.T, s, px, http_txn)) {
3397 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
3398 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3399 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
3400 return 0;
3401 }
3402 s->hlua.nargs = 1;
3403
3404 /* push keywords in the stack. */
3405 for (arg = rule->args; arg && *arg; arg++) {
3406 if (!lua_checkstack(s->hlua.T, 1)) {
3407 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
3408 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3409 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
3410 return 0;
3411 }
3412 lua_pushstring(s->hlua.T, *arg);
3413 s->hlua.nargs++;
3414 }
3415
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003416 /* We must initialize the execution timeouts. */
3417 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
3418
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003419 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003420 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003421 }
3422
3423 /* Execute the function. */
3424 switch (hlua_ctx_resume(&s->hlua, 1)) {
3425 /* finished. */
3426 case HLUA_E_OK:
3427 return 1;
3428
3429 /* yield. */
3430 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003431 /* Set timeout in the required channel. */
3432 if (s->hlua.wake_time != TICK_ETERNITY) {
3433 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
3434 s->req->analyse_exp = s->hlua.wake_time;
3435 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
3436 s->rep->analyse_exp = s->hlua.wake_time;
3437 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003438 /* Some actions can be wake up when a "write" event
3439 * is detected on a response channel. This is useful
3440 * only for actions targetted on the requests.
3441 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003442 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003443 s->rep->flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01003444 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
3445 s->rep->analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003446 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003447 if (HLUA_IS_WAKEREQWR(&s->hlua))
3448 s->req->flags |= CF_WAKE_WRITE;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003449 return 0;
3450
3451 /* finished with error. */
3452 case HLUA_E_ERRMSG:
3453 /* Display log. */
3454 send_log(px, LOG_ERR, "Lua function '%s': %s.", rule->fcn.name, lua_tostring(s->hlua.T, -1));
3455 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3456 Alert("Lua function '%s': %s.\n", rule->fcn.name, lua_tostring(s->hlua.T, -1));
3457 lua_pop(s->hlua.T, 1);
3458 return 1;
3459
3460 case HLUA_E_ERR:
3461 /* Display log. */
3462 send_log(px, LOG_ERR, "Lua function '%s' return an unknown error.", rule->fcn.name);
3463 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3464 Alert("Lua function '%s' return an unknown error.\n", rule->fcn.name);
3465
3466 default:
3467 return 1;
3468 }
3469}
3470
3471/* Lua execution wrapper for "tcp-request". This function uses
3472 * "hlua_request_act_wrapper" for executing the LUA code.
3473 */
3474int hlua_tcp_req_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
3475 struct session *s)
3476{
3477 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
3478 px, s, NULL, AN_REQ_INSPECT_FE);
3479}
3480
3481/* Lua execution wrapper for "tcp-response". This function uses
3482 * "hlua_request_act_wrapper" for executing the LUA code.
3483 */
3484int hlua_tcp_res_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
3485 struct session *s)
3486{
3487 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
3488 px, s, NULL, AN_RES_INSPECT);
3489}
3490
3491/* Lua execution wrapper for http-request.
3492 * This function uses "hlua_request_act_wrapper" for executing
3493 * the LUA code.
3494 */
3495int hlua_http_req_act_wrapper(struct http_req_rule *rule, struct proxy *px,
3496 struct session *s, struct http_txn *http_txn)
3497{
3498 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
3499 s, http_txn, AN_REQ_HTTP_PROCESS_FE);
3500}
3501
3502/* Lua execution wrapper for http-response.
3503 * This function uses "hlua_request_act_wrapper" for executing
3504 * the LUA code.
3505 */
3506int hlua_http_res_act_wrapper(struct http_res_rule *rule, struct proxy *px,
3507 struct session *s, struct http_txn *http_txn)
3508{
3509 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
3510 s, http_txn, AN_RES_HTTP_PROCESS_BE);
3511}
3512
3513/* tcp-request <*> configuration wrapper. */
3514static int tcp_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3515 struct tcp_rule *rule, char **err)
3516{
3517 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003518 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003519 rule->action = TCP_ACT_CUSTOM;
3520 rule->action_ptr = hlua_tcp_req_act_wrapper;
3521 return 1;
3522}
3523
3524/* tcp-response <*> configuration wrapper. */
3525static int tcp_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3526 struct tcp_rule *rule, char **err)
3527{
3528 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003529 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003530 rule->action = TCP_ACT_CUSTOM;
3531 rule->action_ptr = hlua_tcp_res_act_wrapper;
3532 return 1;
3533}
3534
3535/* http-request <*> configuration wrapper. */
3536static int http_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3537 struct http_req_rule *rule, char **err)
3538{
3539 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
3540 return -1;
3541 rule->action = HTTP_REQ_ACT_CUSTOM_CONT;
3542 rule->action_ptr = hlua_http_req_act_wrapper;
3543 return 1;
3544}
3545
3546/* http-response <*> configuration wrapper. */
3547static int http_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3548 struct http_res_rule *rule, char **err)
3549{
3550 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
3551 return -1;
3552 rule->action = HTTP_RES_ACT_CUSTOM_CONT;
3553 rule->action_ptr = hlua_http_res_act_wrapper;
3554 return 1;
3555}
3556
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003557static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
3558 struct proxy *defpx, const char *file, int line,
3559 char **err, unsigned int *timeout)
3560{
3561 const char *error;
3562
3563 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
3564 if (error && *error != '\0') {
3565 memprintf(err, "%s: invalid timeout", args[0]);
3566 return -1;
3567 }
3568 return 0;
3569}
3570
3571static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
3572 struct proxy *defpx, const char *file, int line,
3573 char **err)
3574{
3575 return hlua_read_timeout(args, section_type, curpx, defpx,
3576 file, line, err, &hlua_timeout_session);
3577}
3578
3579static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
3580 struct proxy *defpx, const char *file, int line,
3581 char **err)
3582{
3583 return hlua_read_timeout(args, section_type, curpx, defpx,
3584 file, line, err, &hlua_timeout_task);
3585}
3586
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01003587static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
3588 struct proxy *defpx, const char *file, int line,
3589 char **err)
3590{
3591 char *error;
3592
3593 hlua_nb_instruction = strtoll(args[1], &error, 10);
3594 if (*error != '\0') {
3595 memprintf(err, "%s: invalid number", args[0]);
3596 return -1;
3597 }
3598 return 0;
3599}
3600
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01003601/* This function is called by the main configuration key "lua-load". It loads and
3602 * execute an lua file during the parsing of the HAProxy configuration file. It is
3603 * the main lua entry point.
3604 *
3605 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
3606 * occured, otherwise it returns 0.
3607 *
3608 * In some error case, LUA set an error message in top of the stack. This function
3609 * returns this error message in the HAProxy logs and pop it from the stack.
3610 */
3611static int hlua_load(char **args, int section_type, struct proxy *curpx,
3612 struct proxy *defpx, const char *file, int line,
3613 char **err)
3614{
3615 int error;
3616
3617 /* Just load and compile the file. */
3618 error = luaL_loadfile(gL.T, args[1]);
3619 if (error) {
3620 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
3621 lua_pop(gL.T, 1);
3622 return -1;
3623 }
3624
3625 /* If no syntax error where detected, execute the code. */
3626 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
3627 switch (error) {
3628 case LUA_OK:
3629 break;
3630 case LUA_ERRRUN:
3631 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
3632 lua_pop(gL.T, 1);
3633 return -1;
3634 case LUA_ERRMEM:
3635 memprintf(err, "lua out of memory error\n");
3636 return -1;
3637 case LUA_ERRERR:
3638 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
3639 lua_pop(gL.T, 1);
3640 return -1;
3641 case LUA_ERRGCMM:
3642 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
3643 lua_pop(gL.T, 1);
3644 return -1;
3645 default:
3646 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
3647 lua_pop(gL.T, 1);
3648 return -1;
3649 }
3650
3651 return 0;
3652}
3653
3654/* configuration keywords declaration */
3655static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003656 { CFG_GLOBAL, "lua-load", hlua_load },
3657 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
3658 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01003659 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01003660 { 0, NULL, NULL },
3661}};
3662
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003663static struct http_req_action_kw_list http_req_kws = {"lua", { }, {
3664 { "lua", http_req_action_register_lua },
3665 { NULL, NULL }
3666}};
3667
3668static struct http_res_action_kw_list http_res_kws = {"lua", { }, {
3669 { "lua", http_res_action_register_lua },
3670 { NULL, NULL }
3671}};
3672
3673static struct tcp_action_kw_list tcp_req_cont_kws = {"lua", { }, {
3674 { "lua", tcp_req_action_register_lua },
3675 { NULL, NULL }
3676}};
3677
3678static struct tcp_action_kw_list tcp_res_cont_kws = {"lua", { }, {
3679 { "lua", tcp_res_action_register_lua },
3680 { NULL, NULL }
3681}};
3682
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003683int hlua_post_init()
3684{
3685 struct hlua_init_function *init;
3686 const char *msg;
3687 enum hlua_exec ret;
3688
3689 list_for_each_entry(init, &hlua_init_functions, l) {
3690 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
3691 ret = hlua_ctx_resume(&gL, 0);
3692 switch (ret) {
3693 case HLUA_E_OK:
3694 lua_pop(gL.T, -1);
3695 return 1;
3696 case HLUA_E_AGAIN:
3697 Alert("lua init: yield not allowed.\n");
3698 return 0;
3699 case HLUA_E_ERRMSG:
3700 msg = lua_tostring(gL.T, -1);
3701 Alert("lua init: %s.\n", msg);
3702 return 0;
3703 case HLUA_E_ERR:
3704 default:
3705 Alert("lua init: unknown runtime error.\n");
3706 return 0;
3707 }
3708 }
3709 return 1;
3710}
3711
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01003712void hlua_init(void)
3713{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003714 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01003715 int idx;
3716 struct sample_fetch *sf;
3717 struct hlua_sample_fetch *hsf;
3718 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003719#ifdef USE_OPENSSL
3720 char *args[4];
3721 struct srv_kw *kw;
3722 int tmp_error;
3723 char *error;
3724#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003725
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01003726 /* Initialise com signals pool session. */
3727 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
3728
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003729 /* Initialise sleep pool. */
3730 pool2_hlua_sleep = create_pool("hlua_sleep", sizeof(struct hlua_sleep), MEM_F_SHARED);
3731
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01003732 /* Register configuration keywords. */
3733 cfg_register_keywords(&cfg_kws);
3734
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003735 /* Register custom HTTP rules. */
3736 http_req_keywords_register(&http_req_kws);
3737 http_res_keywords_register(&http_res_kws);
3738 tcp_req_cont_keywords_register(&tcp_req_cont_kws);
3739 tcp_res_cont_keywords_register(&tcp_res_cont_kws);
3740
Thierry FOURNIER380d0932015-01-23 14:27:52 +01003741 /* Init main lua stack. */
3742 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003743 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01003744 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01003745 gL.T = luaL_newstate();
3746 hlua_sethlua(&gL);
3747 gL.Tref = LUA_REFNIL;
3748 gL.task = NULL;
3749
3750 /* Initialise lua. */
3751 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003752
3753 /*
3754 *
3755 * Create "core" object.
3756 *
3757 */
3758
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01003759 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003760 lua_newtable(gL.T);
3761
3762 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003763 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003764 hlua_class_const_int(gL.T, log_levels[i], i);
3765
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003766 /* Register special functions. */
3767 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003768 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003769 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003770 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003771 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01003772 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003773 hlua_class_function(gL.T, "sleep", hlua_sleep);
3774 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01003775 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
3776 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
3777 hlua_class_function(gL.T, "set_map", hlua_set_map);
3778 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003779 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003780
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003781 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003782
3783 /*
3784 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003785 * Register class Channel
3786 *
3787 */
3788
3789 /* Create and fill the metatable. */
3790 lua_newtable(gL.T);
3791
3792 /* Create and fille the __index entry. */
3793 lua_pushstring(gL.T, "__index");
3794 lua_newtable(gL.T);
3795
3796 /* Register . */
3797 hlua_class_function(gL.T, "get", hlua_channel_get);
3798 hlua_class_function(gL.T, "dup", hlua_channel_dup);
3799 hlua_class_function(gL.T, "getline", hlua_channel_getline);
3800 hlua_class_function(gL.T, "set", hlua_channel_set);
3801 hlua_class_function(gL.T, "append", hlua_channel_append);
3802 hlua_class_function(gL.T, "send", hlua_channel_send);
3803 hlua_class_function(gL.T, "forward", hlua_channel_forward);
3804 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
3805 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
3806
3807 lua_settable(gL.T, -3);
3808
3809 /* Register previous table in the registry with reference and named entry. */
3810 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
3811 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
3812 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
3813
3814 /*
3815 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003816 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003817 *
3818 */
3819
3820 /* Create and fill the metatable. */
3821 lua_newtable(gL.T);
3822
3823 /* Create and fille the __index entry. */
3824 lua_pushstring(gL.T, "__index");
3825 lua_newtable(gL.T);
3826
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01003827 /* Browse existing fetches and create the associated
3828 * object method.
3829 */
3830 sf = NULL;
3831 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
3832
3833 /* Dont register the keywork if the arguments check function are
3834 * not safe during the runtime.
3835 */
3836 if ((sf->val_args != NULL) &&
3837 (sf->val_args != val_payload_lv) &&
3838 (sf->val_args != val_hdr))
3839 continue;
3840
3841 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
3842 * by an underscore.
3843 */
3844 strncpy(trash.str, sf->kw, trash.size);
3845 trash.str[trash.size - 1] = '\0';
3846 for (p = trash.str; *p; p++)
3847 if (*p == '.' || *p == '-' || *p == '+')
3848 *p = '_';
3849
3850 /* Register the function. */
3851 lua_pushstring(gL.T, trash.str);
3852 hsf = lua_newuserdata(gL.T, sizeof(struct hlua_sample_fetch));
3853 hsf->f = sf;
3854 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
3855 lua_settable(gL.T, -3);
3856 }
3857
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003858 lua_settable(gL.T, -3);
3859
3860 /* Register previous table in the registry with reference and named entry. */
3861 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
3862 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
3863 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
3864
3865 /*
3866 *
3867 * Register class TXN
3868 *
3869 */
3870
3871 /* Create and fill the metatable. */
3872 lua_newtable(gL.T);
3873
3874 /* Create and fille the __index entry. */
3875 lua_pushstring(gL.T, "__index");
3876 lua_newtable(gL.T);
3877
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003878 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01003879 hlua_class_function(gL.T, "get_headers", hlua_session_get_headers);
3880 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
3881 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01003882 hlua_class_function(gL.T, "req_channel", hlua_txn_req_channel);
3883 hlua_class_function(gL.T, "res_channel", hlua_txn_res_channel);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003884 hlua_class_function(gL.T, "close", hlua_txn_close);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003885
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003886 lua_settable(gL.T, -3);
3887
3888 /* Register previous table in the registry with reference and named entry. */
3889 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
3890 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
3891 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003892
3893 /*
3894 *
3895 * Register class Socket
3896 *
3897 */
3898
3899 /* Create and fill the metatable. */
3900 lua_newtable(gL.T);
3901
3902 /* Create and fille the __index entry. */
3903 lua_pushstring(gL.T, "__index");
3904 lua_newtable(gL.T);
3905
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003906#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003907 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01003908#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003909 hlua_class_function(gL.T, "connect", hlua_socket_connect);
3910 hlua_class_function(gL.T, "send", hlua_socket_send);
3911 hlua_class_function(gL.T, "receive", hlua_socket_receive);
3912 hlua_class_function(gL.T, "close", hlua_socket_close);
3913 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
3914 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
3915 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
3916 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
3917
3918 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
3919
3920 /* Register the garbage collector entry. */
3921 lua_pushstring(gL.T, "__gc");
3922 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
3923 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
3924
3925 /* Register previous table in the registry with reference and named entry. */
3926 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
3927 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
3928 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
3929 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
3930
3931 /* Proxy and server configuration initialisation. */
3932 memset(&socket_proxy, 0, sizeof(socket_proxy));
3933 init_new_proxy(&socket_proxy);
3934 socket_proxy.parent = NULL;
3935 socket_proxy.last_change = now.tv_sec;
3936 socket_proxy.id = "LUA-SOCKET";
3937 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
3938 socket_proxy.maxconn = 0;
3939 socket_proxy.accept = NULL;
3940 socket_proxy.options2 |= PR_O2_INDEPSTR;
3941 socket_proxy.srv = NULL;
3942 socket_proxy.conn_retries = 0;
3943 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
3944
3945 /* Init TCP server: unchanged parameters */
3946 memset(&socket_tcp, 0, sizeof(socket_tcp));
3947 socket_tcp.next = NULL;
3948 socket_tcp.proxy = &socket_proxy;
3949 socket_tcp.obj_type = OBJ_TYPE_SERVER;
3950 LIST_INIT(&socket_tcp.actconns);
3951 LIST_INIT(&socket_tcp.pendconns);
3952 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
3953 socket_tcp.last_change = 0;
3954 socket_tcp.id = "LUA-TCP-CONN";
3955 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
3956 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
3957 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
3958
3959 /* XXX: Copy default parameter from default server,
3960 * but the default server is not initialized.
3961 */
3962 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
3963 socket_tcp.minconn = socket_proxy.defsrv.minconn;
3964 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
3965 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
3966 socket_tcp.onerror = socket_proxy.defsrv.onerror;
3967 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
3968 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
3969 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
3970 socket_tcp.uweight = socket_proxy.defsrv.iweight;
3971 socket_tcp.iweight = socket_proxy.defsrv.iweight;
3972
3973 socket_tcp.check.status = HCHK_STATUS_INI;
3974 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
3975 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
3976 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
3977 socket_tcp.check.server = &socket_tcp;
3978
3979 socket_tcp.agent.status = HCHK_STATUS_INI;
3980 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
3981 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
3982 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
3983 socket_tcp.agent.server = &socket_tcp;
3984
3985 socket_tcp.xprt = &raw_sock;
3986
3987#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003988 /* Init TCP server: unchanged parameters */
3989 memset(&socket_ssl, 0, sizeof(socket_ssl));
3990 socket_ssl.next = NULL;
3991 socket_ssl.proxy = &socket_proxy;
3992 socket_ssl.obj_type = OBJ_TYPE_SERVER;
3993 LIST_INIT(&socket_ssl.actconns);
3994 LIST_INIT(&socket_ssl.pendconns);
3995 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
3996 socket_ssl.last_change = 0;
3997 socket_ssl.id = "LUA-SSL-CONN";
3998 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
3999 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
4000 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
4001
4002 /* XXX: Copy default parameter from default server,
4003 * but the default server is not initialized.
4004 */
4005 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
4006 socket_ssl.minconn = socket_proxy.defsrv.minconn;
4007 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
4008 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
4009 socket_ssl.onerror = socket_proxy.defsrv.onerror;
4010 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
4011 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
4012 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
4013 socket_ssl.uweight = socket_proxy.defsrv.iweight;
4014 socket_ssl.iweight = socket_proxy.defsrv.iweight;
4015
4016 socket_ssl.check.status = HCHK_STATUS_INI;
4017 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
4018 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
4019 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
4020 socket_ssl.check.server = &socket_ssl;
4021
4022 socket_ssl.agent.status = HCHK_STATUS_INI;
4023 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
4024 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
4025 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
4026 socket_ssl.agent.server = &socket_ssl;
4027
4028 socket_ssl.xprt = &raw_sock;
4029
4030 args[0] = "ssl";
4031 args[1] = "verify";
4032 args[2] = "none";
4033 args[3] = NULL;
4034
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004035 for (idx = 0; idx < 3; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004036 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
4037 /*
4038 *
4039 * If the keyword is not known, we can search in the registered
4040 * server keywords. This is usefull to configure special SSL
4041 * features like client certificates and ssl_verify.
4042 *
4043 */
4044 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
4045 if (tmp_error != 0) {
4046 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
4047 abort(); /* This must be never arrives because the command line
4048 not editable by the user. */
4049 }
4050 idx += kw->skip;
4051 }
4052 }
4053
4054 /* Initialize SSL server. */
4055 if (socket_ssl.xprt == &ssl_sock) {
4056 socket_ssl.use_ssl = 1;
4057 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
4058 }
4059#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01004060}