blob: 479b1c7506d08213a61fdb9523db715e2ca26d2d [file] [log] [blame]
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001#include <sys/socket.h>
2
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01003#include <lauxlib.h>
4#include <lua.h>
5#include <lualib.h>
6
Thierry FOURNIER463119c2015-03-10 00:35:36 +01007#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
8#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +01009#endif
10
Thierry FOURNIER380d0932015-01-23 14:27:52 +010011#include <ebpttree.h>
12
13#include <common/cfgparse.h>
14
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010015#include <types/connection.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010016#include <types/hlua.h>
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010017#include <types/proto_tcp.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010018#include <types/proxy.h>
19
Thierry FOURNIER55da1652015-01-23 11:36:30 +010020#include <proto/arg.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010021#include <proto/channel.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010022#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010023#include <proto/hlua.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010024#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010025#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010026#include <proto/payload.h>
27#include <proto/proto_http.h>
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010028#include <proto/proto_tcp.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010029#include <proto/raw_sock.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010030#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010031#include <proto/server.h>
32#include <proto/session.h>
33#include <proto/ssl_sock.h>
34#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010035#include <proto/task.h>
36
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010037/* Lua uses longjmp to perform yield or throwing errors. This
38 * macro is used only for identifying the function that can
39 * not return because a longjmp is executed.
40 * __LJMP marks a prototype of hlua file that can use longjmp.
41 * WILL_LJMP() marks an lua function that will use longjmp.
42 * MAY_LJMP() marks an lua function that may use longjmp.
43 */
44#define __LJMP
45#define WILL_LJMP(func) func
46#define MAY_LJMP(func) func
47
Thierry FOURNIER380d0932015-01-23 14:27:52 +010048/* The main Lua execution context. */
49struct hlua gL;
50
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010051/* This is the memory pool containing all the signal structs. These
52 * struct are used to store each requiered signal between two tasks.
53 */
54struct pool_head *pool2_hlua_com;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +010055struct pool_head *pool2_hlua_sleep;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010056
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010057/* Used for Socket connection. */
58static struct proxy socket_proxy;
59static struct server socket_tcp;
60#ifdef USE_OPENSSL
61static struct server socket_ssl;
62#endif
63
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010064/* List head of the function called at the initialisation time. */
65struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
66
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010067/* The following variables contains the reference of the different
68 * Lua classes. These references are useful for identify metadata
69 * associated with an object.
70 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010071static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010072static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010073static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010074static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010075static int class_converters_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010076
Thierry FOURNIERbd413492015-03-03 16:52:26 +010077/* Global Lua execution timeout. By default Lua, execution linked
78 * with session (actions, sample-fetches and converters) have a
79 * short timeout. Lua linked with tasks doesn't have a timeout
80 * because a task may remain alive during all the haproxy execution.
81 */
82static unsigned int hlua_timeout_session = 4000; /* session timeout. */
83static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
84
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010085/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
86 * it is used for preventing infinite loops.
87 *
88 * I test the scheer with an infinite loop containing one incrementation
89 * and one test. I run this loop between 10 seconds, I raise a ceil of
90 * 710M loops from one interrupt each 9000 instructions, so I fix the value
91 * to one interrupt each 10 000 instructions.
92 *
93 * configured | Number of
94 * instructions | loops executed
95 * between two | in milions
96 * forced yields |
97 * ---------------+---------------
98 * 10 | 160
99 * 500 | 670
100 * 1000 | 680
101 * 5000 | 700
102 * 7000 | 700
103 * 8000 | 700
104 * 9000 | 710 <- ceil
105 * 10000 | 710
106 * 100000 | 710
107 * 1000000 | 710
108 *
109 */
110static unsigned int hlua_nb_instruction = 10000;
111
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100112/* These functions converts types between HAProxy internal args or
113 * sample and LUA types. Another function permits to check if the
114 * LUA stack contains arguments according with an required ARG_T
115 * format.
116 */
117static int hlua_arg2lua(lua_State *L, const struct arg *arg);
118static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
119__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp, unsigned int mask);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100120static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100121static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
122
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100123/* Used to check an Lua function type in the stack. It creates and
124 * returns a reference of the function. This function throws an
125 * error if the rgument is not a "function".
126 */
127__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
128{
129 if (!lua_isfunction(L, argno)) {
130 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
131 WILL_LJMP(luaL_argerror(L, argno, msg));
132 }
133 lua_pushvalue(L, argno);
134 return luaL_ref(L, LUA_REGISTRYINDEX);
135}
136
137/* The three following functions are useful for adding entries
138 * in a table. These functions takes a string and respectively an
139 * integer, a string or a function and add it to the table in the
140 * top of the stack.
141 *
142 * These functions throws an error if no more stack size is
143 * available.
144 */
145__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100146 int value)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100147{
148 if (!lua_checkstack(L, 2))
149 WILL_LJMP(luaL_error(L, "full stack"));
150 lua_pushstring(L, name);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100151 lua_pushinteger(L, value);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100152 lua_settable(L, -3);
153}
154__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
155 const char *value)
156{
157 if (!lua_checkstack(L, 2))
158 WILL_LJMP(luaL_error(L, "full stack"));
159 lua_pushstring(L, name);
160 lua_pushstring(L, value);
161 lua_settable(L, -3);
162}
163__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
164 int (*function)(lua_State *L))
165{
166 if (!lua_checkstack(L, 2))
167 WILL_LJMP(luaL_error(L, "full stack"));
168 lua_pushstring(L, name);
169 lua_pushcclosure(L, function, 0);
170 lua_settable(L, -3);
171}
172
173/* This function check the number of arguments available in the
174 * stack. If the number of arguments available is not the same
175 * then <nb> an error is throwed.
176 */
177__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
178{
179 if (lua_gettop(L) == nb)
180 return;
181 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
182}
183
184/* Return true if the data in stack[<ud>] is an object of
185 * type <class_ref>.
186 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100187static int hlua_metaistype(lua_State *L, int ud, int class_ref)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100188{
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100189 if (!lua_getmetatable(L, ud))
190 return 0;
191
192 lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
193 if (!lua_rawequal(L, -1, -2)) {
194 lua_pop(L, 2);
195 return 0;
196 }
197
198 lua_pop(L, 2);
199 return 1;
200}
201
202/* Return an object of the expected type, or throws an error. */
203__LJMP static void *hlua_checkudata(lua_State *L, int ud, int class_ref)
204{
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100205 void *p;
206
207 /* Check if the stack entry is an array. */
208 if (!lua_istable(L, ud))
209 WILL_LJMP(luaL_argerror(L, ud, NULL));
210 /* Check if the metadata have the expected type. */
211 if (!hlua_metaistype(L, ud, class_ref))
212 WILL_LJMP(luaL_argerror(L, ud, NULL));
213 /* Push on the stack at the entry [0] of the table. */
214 lua_rawgeti(L, ud, 0);
215 /* Check if this entry is userdata. */
216 p = lua_touserdata(L, -1);
217 if (!p)
218 WILL_LJMP(luaL_argerror(L, ud, NULL));
219 /* Remove the entry returned by lua_rawgeti(). */
220 lua_pop(L, 1);
221 /* Return the associated struct. */
222 return p;
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100223}
224
225/* This fucntion push an error string prefixed by the file name
226 * and the line number where the error is encountered.
227 */
228static int hlua_pusherror(lua_State *L, const char *fmt, ...)
229{
230 va_list argp;
231 va_start(argp, fmt);
232 luaL_where(L, 1);
233 lua_pushvfstring(L, fmt, argp);
234 va_end(argp);
235 lua_concat(L, 2);
236 return 1;
237}
238
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100239/* This function register a new signal. "lua" is the current lua
240 * execution context. It contains a pointer to the associated task.
241 * "link" is a list head attached to an other task that must be wake
242 * the lua task if an event occurs. This is useful with external
243 * events like TCP I/O or sleep functions. This funcion allocate
244 * memory for the signal.
245 */
246static int hlua_com_new(struct hlua *lua, struct list *link)
247{
248 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
249 if (!com)
250 return 0;
251 LIST_ADDQ(&lua->com, &com->purge_me);
252 LIST_ADDQ(link, &com->wake_me);
253 com->task = lua->task;
254 return 1;
255}
256
257/* This function purge all the pending signals when the LUA execution
258 * is finished. This prevent than a coprocess try to wake a deleted
259 * task. This function remove the memory associated to the signal.
260 */
261static void hlua_com_purge(struct hlua *lua)
262{
263 struct hlua_com *com, *back;
264
265 /* Delete all pending communication signals. */
266 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
267 LIST_DEL(&com->purge_me);
268 LIST_DEL(&com->wake_me);
269 pool_free2(pool2_hlua_com, com);
270 }
271}
272
273/* This function sends signals. It wakes all the tasks attached
274 * to a list head, and remove the signal, and free the used
275 * memory.
276 */
277static void hlua_com_wake(struct list *wake)
278{
279 struct hlua_com *com, *back;
280
281 /* Wake task and delete all pending communication signals. */
282 list_for_each_entry_safe(com, back, wake, wake_me) {
283 LIST_DEL(&com->purge_me);
284 LIST_DEL(&com->wake_me);
285 task_wakeup(com->task, TASK_WOKEN_MSG);
286 pool_free2(pool2_hlua_com, com);
287 }
288}
289
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100290/* This functions is used with sample fetch and converters. It
291 * converts the HAProxy configuration argument in a lua stack
292 * values.
293 *
294 * It takes an array of "arg", and each entry of the array is
295 * converted and pushed in the LUA stack.
296 */
297static int hlua_arg2lua(lua_State *L, const struct arg *arg)
298{
299 switch (arg->type) {
300 case ARGT_SINT:
301 lua_pushinteger(L, arg->data.sint);
302 break;
303
304 case ARGT_UINT:
305 case ARGT_TIME:
306 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100307 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100308 break;
309
310 case ARGT_STR:
311 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
312 break;
313
314 case ARGT_IPV4:
315 case ARGT_IPV6:
316 case ARGT_MSK4:
317 case ARGT_MSK6:
318 case ARGT_FE:
319 case ARGT_BE:
320 case ARGT_TAB:
321 case ARGT_SRV:
322 case ARGT_USR:
323 case ARGT_MAP:
324 default:
325 lua_pushnil(L);
326 break;
327 }
328 return 1;
329}
330
331/* This function take one entrie in an LUA stack at the index "ud",
332 * and try to convert it in an HAProxy argument entry. This is useful
333 * with sample fetch wrappers. The input arguments are gived to the
334 * lua wrapper and converted as arg list by thi function.
335 */
336static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
337{
338 switch (lua_type(L, ud)) {
339
340 case LUA_TNUMBER:
341 case LUA_TBOOLEAN:
342 arg->type = ARGT_SINT;
343 arg->data.sint = lua_tointeger(L, ud);
344 break;
345
346 case LUA_TSTRING:
347 arg->type = ARGT_STR;
348 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
349 break;
350
351 case LUA_TUSERDATA:
352 case LUA_TNIL:
353 case LUA_TTABLE:
354 case LUA_TFUNCTION:
355 case LUA_TTHREAD:
356 case LUA_TLIGHTUSERDATA:
357 arg->type = ARGT_SINT;
358 arg->data.uint = 0;
359 break;
360 }
361 return 1;
362}
363
364/* the following functions are used to convert a struct sample
365 * in Lua type. This useful to convert the return of the
366 * fetchs or converters.
367 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100368static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100369{
370 switch (smp->type) {
371 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100372 case SMP_T_BOOL:
373 case SMP_T_UINT:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100374 lua_pushinteger(L, smp->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100375 break;
376
377 case SMP_T_BIN:
378 case SMP_T_STR:
379 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
380 break;
381
382 case SMP_T_METH:
383 switch (smp->data.meth.meth) {
384 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
385 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
386 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
387 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
388 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
389 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
390 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
391 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
392 case HTTP_METH_OTHER:
393 lua_pushlstring(L, smp->data.meth.str.str, smp->data.meth.str.len);
394 break;
395 default:
396 lua_pushnil(L);
397 break;
398 }
399 break;
400
401 case SMP_T_IPV4:
402 case SMP_T_IPV6:
403 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100404 if (sample_casts[smp->type][SMP_T_STR] &&
405 sample_casts[smp->type][SMP_T_STR](smp))
406 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
407 else
408 lua_pushnil(L);
409 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100410 default:
411 lua_pushnil(L);
412 break;
413 }
414 return 1;
415}
416
417/* the following functions are used to convert an Lua type in a
418 * struct sample. This is useful to provide data from a converter
419 * to the LUA code.
420 */
421static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
422{
423 switch (lua_type(L, ud)) {
424
425 case LUA_TNUMBER:
426 smp->type = SMP_T_SINT;
427 smp->data.sint = lua_tointeger(L, ud);
428 break;
429
430
431 case LUA_TBOOLEAN:
432 smp->type = SMP_T_BOOL;
433 smp->data.uint = lua_toboolean(L, ud);
434 break;
435
436 case LUA_TSTRING:
437 smp->type = SMP_T_STR;
438 smp->flags |= SMP_F_CONST;
439 smp->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.str.len);
440 break;
441
442 case LUA_TUSERDATA:
443 case LUA_TNIL:
444 case LUA_TTABLE:
445 case LUA_TFUNCTION:
446 case LUA_TTHREAD:
447 case LUA_TLIGHTUSERDATA:
448 smp->type = SMP_T_BOOL;
449 smp->data.uint = 0;
450 break;
451 }
452 return 1;
453}
454
455/* This function check the "argp" builded by another conversion function
456 * is in accord with the expected argp defined by the "mask". The fucntion
457 * returns true or false. It can be adjust the types if there compatibles.
458 */
459__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp, unsigned int mask)
460{
461 int min_arg;
462 int idx;
463
464 idx = 0;
465 min_arg = ARGM(mask);
466 mask >>= ARGM_BITS;
467
468 while (1) {
469
470 /* Check oversize. */
471 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100472 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100473 }
474
475 /* Check for mandatory arguments. */
476 if (argp[idx].type == ARGT_STOP) {
477 if (idx + 1 < min_arg)
478 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
479 return 0;
480 }
481
482 /* Check for exceed the number of requiered argument. */
483 if ((mask & ARGT_MASK) == ARGT_STOP &&
484 argp[idx].type != ARGT_STOP) {
485 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
486 }
487
488 if ((mask & ARGT_MASK) == ARGT_STOP &&
489 argp[idx].type == ARGT_STOP) {
490 return 0;
491 }
492
493 /* Compatibility mask. */
494 switch (argp[idx].type) {
495 case ARGT_SINT:
496 switch (mask & ARGT_MASK) {
497 case ARGT_UINT: argp[idx].type = mask & ARGT_MASK; break;
498 case ARGT_TIME: argp[idx].type = mask & ARGT_MASK; break;
499 case ARGT_SIZE: argp[idx].type = mask & ARGT_MASK; break;
500 }
501 break;
502 }
503
504 /* Check for type of argument. */
505 if ((mask & ARGT_MASK) != argp[idx].type) {
506 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
507 arg_type_names[(mask & ARGT_MASK)],
508 arg_type_names[argp[idx].type & ARGT_MASK]);
509 WILL_LJMP(luaL_argerror(L, first + idx, msg));
510 }
511
512 /* Next argument. */
513 mask >>= ARGT_BITS;
514 idx++;
515 }
516}
517
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100518/*
519 * The following functions are used to make correspondance between the the
520 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100521 *
522 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100523 * - hlua_sethlua : create the association between hlua context and lua_state.
524 */
525static inline struct hlua *hlua_gethlua(lua_State *L)
526{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100527 struct hlua **hlua = lua_getextraspace(L);
528 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100529}
530static inline void hlua_sethlua(struct hlua *hlua)
531{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100532 struct hlua **hlua_store = lua_getextraspace(hlua->T);
533 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100534}
535
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100536/* This function just ensure that the yield will be always
537 * returned with a timeout and permit to set some flags
538 */
539__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100540 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100541{
542 struct hlua *hlua = hlua_gethlua(L);
543
544 /* Set the wake timeout. If timeout is required, we set
545 * the expiration time.
546 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100547 hlua->wake_time = tick_first(timeout, hlua->expire);
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100548
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100549 hlua->flags |= flags;
550
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100551 /* Process the yield. */
552 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
553}
554
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100555/* This function initialises the Lua environment stored in the session.
556 * It must be called at the start of the session. This function creates
557 * an LUA coroutine. It can not be use to crete the main LUA context.
558 */
559int hlua_ctx_init(struct hlua *lua, struct task *task)
560{
561 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100562 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100563 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100564 lua->T = lua_newthread(gL.T);
565 if (!lua->T) {
566 lua->Tref = LUA_REFNIL;
567 return 0;
568 }
569 hlua_sethlua(lua);
570 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
571 lua->task = task;
572 return 1;
573}
574
575/* Used to destroy the Lua coroutine when the attached session or task
576 * is destroyed. The destroy also the memory context. The struct "lua"
577 * is not freed.
578 */
579void hlua_ctx_destroy(struct hlua *lua)
580{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100581 if (!lua->T)
582 return;
583
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100584 /* Purge all the pending signals. */
585 hlua_com_purge(lua);
586
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100587 /* The thread is garbage collected by Lua. */
588 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
589 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
590}
591
592/* This function is used to restore the Lua context when a coroutine
593 * fails. This function copy the common memory between old coroutine
594 * and the new coroutine. The old coroutine is destroyed, and its
595 * replaced by the new coroutine.
596 * If the flag "keep_msg" is set, the last entry of the old is assumed
597 * as string error message and it is copied in the new stack.
598 */
599static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
600{
601 lua_State *T;
602 int new_ref;
603
604 /* Renew the main LUA stack doesn't have sense. */
605 if (lua == &gL)
606 return 0;
607
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100608 /* New Lua coroutine. */
609 T = lua_newthread(gL.T);
610 if (!T)
611 return 0;
612
613 /* Copy last error message. */
614 if (keep_msg)
615 lua_xmove(lua->T, T, 1);
616
617 /* Copy data between the coroutines. */
618 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
619 lua_xmove(lua->T, T, 1);
620 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
621
622 /* Destroy old data. */
623 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
624
625 /* The thread is garbage collected by Lua. */
626 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
627
628 /* Fill the struct with the new coroutine values. */
629 lua->Mref = new_ref;
630 lua->T = T;
631 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
632
633 /* Set context. */
634 hlua_sethlua(lua);
635
636 return 1;
637}
638
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100639void hlua_hook(lua_State *L, lua_Debug *ar)
640{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100641 struct hlua *hlua = hlua_gethlua(L);
642
643 /* Lua cannot yield when its returning from a function,
644 * so, we can fix the interrupt hook to 1 instruction,
645 * expecting that the function is finnished.
646 */
647 if (lua_gethookmask(L) & LUA_MASKRET) {
648 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
649 return;
650 }
651
652 /* restore the interrupt condition. */
653 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
654
655 /* If we interrupt the Lua processing in yieldable state, we yield.
656 * If the state is not yieldable, trying yield causes an error.
657 */
658 if (lua_isyieldable(L))
659 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
660
661 /* If we cannot yield, check the timeout. */
662 if (tick_is_expired(hlua->expire, now_ms)) {
663 lua_pushfstring(L, "execution timeout");
664 WILL_LJMP(lua_error(L));
665 }
666
667 /* Try to interrupt the process at the end of the current
668 * unyieldable function.
669 */
670 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100671}
672
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100673/* This function start or resumes the Lua stack execution. If the flag
674 * "yield_allowed" if no set and the LUA stack execution returns a yield
675 * The function return an error.
676 *
677 * The function can returns 4 values:
678 * - HLUA_E_OK : The execution is terminated without any errors.
679 * - HLUA_E_AGAIN : The execution must continue at the next associated
680 * task wakeup.
681 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
682 * the top of the stack.
683 * - HLUA_E_ERR : An error has occured without error message.
684 *
685 * If an error occured, the stack is renewed and it is ready to run new
686 * LUA code.
687 */
688static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
689{
690 int ret;
691 const char *msg;
692
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100693 HLUA_SET_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100694
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100695 /* If we want to resume the task, then check first the execution timeout.
696 * if it is reached, we can interrupt the Lua processing.
697 */
698 if (tick_is_expired(lua->expire, now_ms))
699 goto timeout_reached;
700
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100701resume_execution:
702
703 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
704 * instructions. it is used for preventing infinite loops.
705 */
706 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
707
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +0100708 /* Remove all flags except the running flags. */
709 lua->flags = HLUA_RUN;
710
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100711 /* Call the function. */
712 ret = lua_resume(lua->T, gL.T, lua->nargs);
713 switch (ret) {
714
715 case LUA_OK:
716 ret = HLUA_E_OK;
717 break;
718
719 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100720 /* Check if the execution timeout is expired. It it is the case, we
721 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100722 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100723 if (tick_is_expired(lua->expire, now_ms)) {
724
725timeout_reached:
726
727 lua_settop(lua->T, 0); /* Empty the stack. */
728 if (!lua_checkstack(lua->T, 1)) {
729 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100730 break;
731 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100732 lua_pushfstring(lua->T, "execution timeout");
733 ret = HLUA_E_ERRMSG;
734 break;
735 }
736 /* Process the forced yield. if the general yield is not allowed or
737 * if no task were associated this the current Lua execution
738 * coroutine, we resume the execution. Else we want to return in the
739 * scheduler and we want to be waked up again, to continue the
740 * current Lua execution. So we schedule our own task.
741 */
742 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100743 if (!yield_allowed || !lua->task)
744 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100745 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100746 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100747 if (!yield_allowed) {
748 lua_settop(lua->T, 0); /* Empty the stack. */
749 if (!lua_checkstack(lua->T, 1)) {
750 ret = HLUA_E_ERR;
751 break;
752 }
753 lua_pushfstring(lua->T, "yield not allowed");
754 ret = HLUA_E_ERRMSG;
755 break;
756 }
757 ret = HLUA_E_AGAIN;
758 break;
759
760 case LUA_ERRRUN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100761 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100762 if (!lua_checkstack(lua->T, 1)) {
763 ret = HLUA_E_ERR;
764 break;
765 }
766 msg = lua_tostring(lua->T, -1);
767 lua_settop(lua->T, 0); /* Empty the stack. */
768 lua_pop(lua->T, 1);
769 if (msg)
770 lua_pushfstring(lua->T, "runtime error: %s", msg);
771 else
772 lua_pushfstring(lua->T, "unknown runtime error");
773 ret = HLUA_E_ERRMSG;
774 break;
775
776 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100777 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100778 lua_settop(lua->T, 0); /* Empty the stack. */
779 if (!lua_checkstack(lua->T, 1)) {
780 ret = HLUA_E_ERR;
781 break;
782 }
783 lua_pushfstring(lua->T, "out of memory error");
784 ret = HLUA_E_ERRMSG;
785 break;
786
787 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100788 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100789 if (!lua_checkstack(lua->T, 1)) {
790 ret = HLUA_E_ERR;
791 break;
792 }
793 msg = lua_tostring(lua->T, -1);
794 lua_settop(lua->T, 0); /* Empty the stack. */
795 lua_pop(lua->T, 1);
796 if (msg)
797 lua_pushfstring(lua->T, "message handler error: %s", msg);
798 else
799 lua_pushfstring(lua->T, "message handler error");
800 ret = HLUA_E_ERRMSG;
801 break;
802
803 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100804 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100805 lua_settop(lua->T, 0); /* Empty the stack. */
806 if (!lua_checkstack(lua->T, 1)) {
807 ret = HLUA_E_ERR;
808 break;
809 }
810 lua_pushfstring(lua->T, "unknonwn error");
811 ret = HLUA_E_ERRMSG;
812 break;
813 }
814
815 switch (ret) {
816 case HLUA_E_AGAIN:
817 break;
818
819 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100820 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100821 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100822 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100823 break;
824
825 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100826 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100827 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100828 hlua_ctx_renew(lua, 0);
829 break;
830
831 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100832 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100833 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100834 break;
835 }
836
837 return ret;
838}
839
Thierry FOURNIER83758bb2015-02-04 13:21:04 +0100840/* This function is an LUA binding. It provides a function
841 * for deleting ACL from a referenced ACL file.
842 */
843__LJMP static int hlua_del_acl(lua_State *L)
844{
845 const char *name;
846 const char *key;
847 struct pat_ref *ref;
848
849 MAY_LJMP(check_args(L, 2, "del_acl"));
850
851 name = MAY_LJMP(luaL_checkstring(L, 1));
852 key = MAY_LJMP(luaL_checkstring(L, 2));
853
854 ref = pat_ref_lookup(name);
855 if (!ref)
856 WILL_LJMP(luaL_error(L, "'del_acl': unkown acl file '%s'", name));
857
858 pat_ref_delete(ref, key);
859 return 0;
860}
861
862/* This function is an LUA binding. It provides a function
863 * for deleting map entry from a referenced map file.
864 */
865static int hlua_del_map(lua_State *L)
866{
867 const char *name;
868 const char *key;
869 struct pat_ref *ref;
870
871 MAY_LJMP(check_args(L, 2, "del_map"));
872
873 name = MAY_LJMP(luaL_checkstring(L, 1));
874 key = MAY_LJMP(luaL_checkstring(L, 2));
875
876 ref = pat_ref_lookup(name);
877 if (!ref)
878 WILL_LJMP(luaL_error(L, "'del_map': unkown acl file '%s'", name));
879
880 pat_ref_delete(ref, key);
881 return 0;
882}
883
884/* This function is an LUA binding. It provides a function
885 * for adding ACL pattern from a referenced ACL file.
886 */
887static int hlua_add_acl(lua_State *L)
888{
889 const char *name;
890 const char *key;
891 struct pat_ref *ref;
892
893 MAY_LJMP(check_args(L, 2, "add_acl"));
894
895 name = MAY_LJMP(luaL_checkstring(L, 1));
896 key = MAY_LJMP(luaL_checkstring(L, 2));
897
898 ref = pat_ref_lookup(name);
899 if (!ref)
900 WILL_LJMP(luaL_error(L, "'add_acl': unkown acl file '%s'", name));
901
902 if (pat_ref_find_elt(ref, key) == NULL)
903 pat_ref_add(ref, key, NULL, NULL);
904 return 0;
905}
906
907/* This function is an LUA binding. It provides a function
908 * for setting map pattern and sample from a referenced map
909 * file.
910 */
911static int hlua_set_map(lua_State *L)
912{
913 const char *name;
914 const char *key;
915 const char *value;
916 struct pat_ref *ref;
917
918 MAY_LJMP(check_args(L, 3, "set_map"));
919
920 name = MAY_LJMP(luaL_checkstring(L, 1));
921 key = MAY_LJMP(luaL_checkstring(L, 2));
922 value = MAY_LJMP(luaL_checkstring(L, 3));
923
924 ref = pat_ref_lookup(name);
925 if (!ref)
926 WILL_LJMP(luaL_error(L, "'set_map': unkown map file '%s'", name));
927
928 if (pat_ref_find_elt(ref, key) != NULL)
929 pat_ref_set(ref, key, value, NULL);
930 else
931 pat_ref_add(ref, key, value, NULL);
932 return 0;
933}
934
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100935/* A class is a lot of memory that contain data. This data can be a table,
936 * an integer or user data. This data is associated with a metatable. This
937 * metatable have an original version registred in the global context with
938 * the name of the object (_G[<name>] = <metable> ).
939 *
940 * A metable is a table that modify the standard behavior of a standard
941 * access to the associated data. The entries of this new metatable are
942 * defined as is:
943 *
944 * http://lua-users.org/wiki/MetatableEvents
945 *
946 * __index
947 *
948 * we access an absent field in a table, the result is nil. This is
949 * true, but it is not the whole truth. Actually, such access triggers
950 * the interpreter to look for an __index metamethod: If there is no
951 * such method, as usually happens, then the access results in nil;
952 * otherwise, the metamethod will provide the result.
953 *
954 * Control 'prototype' inheritance. When accessing "myTable[key]" and
955 * the key does not appear in the table, but the metatable has an __index
956 * property:
957 *
958 * - if the value is a function, the function is called, passing in the
959 * table and the key; the return value of that function is returned as
960 * the result.
961 *
962 * - if the value is another table, the value of the key in that table is
963 * asked for and returned (and if it doesn't exist in that table, but that
964 * table's metatable has an __index property, then it continues on up)
965 *
966 * - Use "rawget(myTable,key)" to skip this metamethod.
967 *
968 * http://www.lua.org/pil/13.4.1.html
969 *
970 * __newindex
971 *
972 * Like __index, but control property assignment.
973 *
974 * __mode - Control weak references. A string value with one or both
975 * of the characters 'k' and 'v' which specifies that the the
976 * keys and/or values in the table are weak references.
977 *
978 * __call - Treat a table like a function. When a table is followed by
979 * parenthesis such as "myTable( 'foo' )" and the metatable has
980 * a __call key pointing to a function, that function is invoked
981 * (passing any specified arguments) and the return value is
982 * returned.
983 *
984 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
985 * called, if the metatable for myTable has a __metatable
986 * key, the value of that key is returned instead of the
987 * actual metatable.
988 *
989 * __tostring - Control string representation. When the builtin
990 * "tostring( myTable )" function is called, if the metatable
991 * for myTable has a __tostring property set to a function,
992 * that function is invoked (passing myTable to it) and the
993 * return value is used as the string representation.
994 *
995 * __len - Control table length. When the table length is requested using
996 * the length operator ( '#' ), if the metatable for myTable has
997 * a __len key pointing to a function, that function is invoked
998 * (passing myTable to it) and the return value used as the value
999 * of "#myTable".
1000 *
1001 * __gc - Userdata finalizer code. When userdata is set to be garbage
1002 * collected, if the metatable has a __gc field pointing to a
1003 * function, that function is first invoked, passing the userdata
1004 * to it. The __gc metamethod is not called for tables.
1005 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1006 *
1007 * Special metamethods for redefining standard operators:
1008 * http://www.lua.org/pil/13.1.html
1009 *
1010 * __add "+"
1011 * __sub "-"
1012 * __mul "*"
1013 * __div "/"
1014 * __unm "!"
1015 * __pow "^"
1016 * __concat ".."
1017 *
1018 * Special methods for redfining standar relations
1019 * http://www.lua.org/pil/13.2.html
1020 *
1021 * __eq "=="
1022 * __lt "<"
1023 * __le "<="
1024 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001025
1026/*
1027 *
1028 *
1029 * Class Socket
1030 *
1031 *
1032 */
1033
1034__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1035{
1036 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1037}
1038
1039/* This function is the handler called for each I/O on the established
1040 * connection. It is used for notify space avalaible to send or data
1041 * received.
1042 */
1043static void hlua_socket_handler(struct stream_interface *si)
1044{
1045 struct appctx *appctx = objt_appctx(si->end);
1046 struct connection *c = objt_conn(si->ib->cons->end);
1047
1048 /* Wakeup the main session if the client connection is closed. */
1049 if (!c || channel_output_closed(si->ib) || channel_input_closed(si->ob)) {
1050 if (appctx->ctx.hlua.socket) {
1051 appctx->ctx.hlua.socket->s = NULL;
1052 appctx->ctx.hlua.socket = NULL;
1053 }
1054 si_shutw(si);
1055 si_shutr(si);
1056 si->ib->flags |= CF_READ_NULL;
1057 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1058 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1059 return;
1060 }
1061
1062 if (!(c->flags & CO_FL_CONNECTED))
1063 return;
1064
1065 /* This function is called after the connect. */
1066 appctx->ctx.hlua.connected = 1;
1067
1068 /* Wake the tasks which wants to write if the buffer have avalaible space. */
1069 if (channel_may_recv(si->ob))
1070 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1071
1072 /* Wake the tasks which wants to read if the buffer contains data. */
1073 if (channel_is_empty(si->ib))
1074 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1075}
1076
1077/* This function is called when the "struct session" is destroyed.
1078 * Remove the link from the object to this session.
1079 * Wake all the pending signals.
1080 */
1081static void hlua_socket_release(struct stream_interface *si)
1082{
1083 struct appctx *appctx = objt_appctx(si->end);
1084
1085 /* Remove my link in the original object. */
1086 if (appctx->ctx.hlua.socket)
1087 appctx->ctx.hlua.socket->s = NULL;
1088
1089 /* Wake all the task waiting for me. */
1090 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1091 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1092}
1093
1094/* If the garbage collectio of the object is launch, nobody
1095 * uses this object. If the session does not exists, just quit.
1096 * Send the shutdown signal to the session. In some cases,
1097 * pending signal can rest in the read and write lists. destroy
1098 * it.
1099 */
1100__LJMP static int hlua_socket_gc(lua_State *L)
1101{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001102 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001103 struct appctx *appctx;
1104
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001105 MAY_LJMP(check_args(L, 1, "__gc"));
1106
1107 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001108 if (!socket->s)
1109 return 0;
1110
1111 /* Remove all reference between the Lua stack and the coroutine session. */
1112 appctx = objt_appctx(socket->s->si[0].end);
1113 session_shutdown(socket->s, SN_ERR_KILLED);
1114 socket->s = NULL;
1115 appctx->ctx.hlua.socket = NULL;
1116
1117 return 0;
1118}
1119
1120/* The close function send shutdown signal and break the
1121 * links between the session and the object.
1122 */
1123__LJMP static int hlua_socket_close(lua_State *L)
1124{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001125 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001126 struct appctx *appctx;
1127
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001128 MAY_LJMP(check_args(L, 1, "close"));
1129
1130 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001131 if (!socket->s)
1132 return 0;
1133
1134 /* Close the session and remove the associated stop task. */
1135 session_shutdown(socket->s, SN_ERR_KILLED);
1136 appctx = objt_appctx(socket->s->si[0].end);
1137 appctx->ctx.hlua.socket = NULL;
1138 socket->s = NULL;
1139
1140 return 0;
1141}
1142
1143/* This Lua function assumes that the stack contain three parameters.
1144 * 1 - USERDATA containing a struct socket
1145 * 2 - INTEGER with values of the macro defined below
1146 * If the integer is -1, we must read at most one line.
1147 * If the integer is -2, we ust read all the data until the
1148 * end of the stream.
1149 * If the integer is positive value, we must read a number of
1150 * bytes corresponding to this value.
1151 */
1152#define HLSR_READ_LINE (-1)
1153#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001154__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001155{
1156 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1157 int wanted = lua_tointeger(L, 2);
1158 struct hlua *hlua = hlua_gethlua(L);
1159 struct appctx *appctx;
1160 int len;
1161 int nblk;
1162 char *blk1;
1163 int len1;
1164 char *blk2;
1165 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001166 int skip_at_end = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001167
1168 /* Check if this lua stack is schedulable. */
1169 if (!hlua || !hlua->task)
1170 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1171 "'frontend', 'backend' or 'task'"));
1172
1173 /* check for connection closed. If some data where read, return it. */
1174 if (!socket->s)
1175 goto connection_closed;
1176
1177 if (wanted == HLSR_READ_LINE) {
1178
1179 /* Read line. */
1180 nblk = bo_getline_nc(socket->s->si[0].ob, &blk1, &len1, &blk2, &len2);
1181 if (nblk < 0) /* Connection close. */
1182 goto connection_closed;
1183 if (nblk == 0) /* No data avalaible. */
1184 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001185
1186 /* remove final \r\n. */
1187 if (nblk == 1) {
1188 if (blk1[len1-1] == '\n') {
1189 len1--;
1190 skip_at_end++;
1191 if (blk1[len1-1] == '\r') {
1192 len1--;
1193 skip_at_end++;
1194 }
1195 }
1196 }
1197 else {
1198 if (blk2[len2-1] == '\n') {
1199 len2--;
1200 skip_at_end++;
1201 if (blk2[len2-1] == '\r') {
1202 len2--;
1203 skip_at_end++;
1204 }
1205 }
1206 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001207 }
1208
1209 else if (wanted == HLSR_READ_ALL) {
1210
1211 /* Read all the available data. */
1212 nblk = bo_getblk_nc(socket->s->si[0].ob, &blk1, &len1, &blk2, &len2);
1213 if (nblk < 0) /* Connection close. */
1214 goto connection_closed;
1215 if (nblk == 0) /* No data avalaible. */
1216 goto connection_empty;
1217 }
1218
1219 else {
1220
1221 /* Read a block of data. */
1222 nblk = bo_getblk_nc(socket->s->si[0].ob, &blk1, &len1, &blk2, &len2);
1223 if (nblk < 0) /* Connection close. */
1224 goto connection_closed;
1225 if (nblk == 0) /* No data avalaible. */
1226 goto connection_empty;
1227
1228 if (len1 > wanted) {
1229 nblk = 1;
1230 len1 = wanted;
1231 } if (nblk == 2 && len1 + len2 > wanted)
1232 len2 = wanted - len1;
1233 }
1234
1235 len = len1;
1236
1237 luaL_addlstring(&socket->b, blk1, len1);
1238 if (nblk == 2) {
1239 len += len2;
1240 luaL_addlstring(&socket->b, blk2, len2);
1241 }
1242
1243 /* Consume data. */
Thierry FOURNIER00543922015-03-09 18:35:06 +01001244 bo_skip(socket->s->si[0].ob, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001245
1246 /* Don't wait anything. */
1247 si_update(&socket->s->si[0]);
1248
1249 /* If the pattern reclaim to read all the data
1250 * in the connection, got out.
1251 */
1252 if (wanted == HLSR_READ_ALL)
1253 goto connection_empty;
1254 else if (wanted >= 0 && len < wanted)
1255 goto connection_empty;
1256
1257 /* Return result. */
1258 luaL_pushresult(&socket->b);
1259 return 1;
1260
1261connection_closed:
1262
1263 /* If the buffer containds data. */
1264 if (socket->b.n > 0) {
1265 luaL_pushresult(&socket->b);
1266 return 1;
1267 }
1268 lua_pushnil(L);
1269 lua_pushstring(L, "connection closed.");
1270 return 2;
1271
1272connection_empty:
1273
1274 appctx = objt_appctx(socket->s->si[0].end);
1275 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1276 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001277 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001278 return 0;
1279}
1280
1281/* This Lus function gets two parameters. The first one can be string
1282 * or a number. If the string is "*l", the user require one line. If
1283 * the string is "*a", the user require all the content of the stream.
1284 * If the value is a number, the user require a number of bytes equal
1285 * to the value. The default value is "*l" (a line).
1286 *
1287 * This paraeter with a variable type is converted in integer. This
1288 * integer takes this values:
1289 * -1 : read a line
1290 * -2 : read all the stream
1291 * >0 : amount if bytes.
1292 *
1293 * The second parameter is optinal. It contains a string that must be
1294 * concatenated with the read data.
1295 */
1296__LJMP static int hlua_socket_receive(struct lua_State *L)
1297{
1298 int wanted = HLSR_READ_LINE;
1299 const char *pattern;
1300 int type;
1301 char *error;
1302 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001303 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001304
1305 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1306 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1307
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001308 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001309
1310 /* check for pattern. */
1311 if (lua_gettop(L) >= 2) {
1312 type = lua_type(L, 2);
1313 if (type == LUA_TSTRING) {
1314 pattern = lua_tostring(L, 2);
1315 if (strcmp(pattern, "*a") == 0)
1316 wanted = HLSR_READ_ALL;
1317 else if (strcmp(pattern, "*l") == 0)
1318 wanted = HLSR_READ_LINE;
1319 else {
1320 wanted = strtoll(pattern, &error, 10);
1321 if (*error != '\0')
1322 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1323 }
1324 }
1325 else if (type == LUA_TNUMBER) {
1326 wanted = lua_tointeger(L, 2);
1327 if (wanted < 0)
1328 WILL_LJMP(luaL_error(L, "Unsupported size."));
1329 }
1330 }
1331
1332 /* Set pattern. */
1333 lua_pushinteger(L, wanted);
1334 lua_replace(L, 2);
1335
1336 /* init bufffer, and fiil it wih prefix. */
1337 luaL_buffinit(L, &socket->b);
1338
1339 /* Check prefix. */
1340 if (lua_gettop(L) >= 3) {
1341 if (lua_type(L, 3) != LUA_TSTRING)
1342 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1343 pattern = lua_tolstring(L, 3, &len);
1344 luaL_addlstring(&socket->b, pattern, len);
1345 }
1346
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001347 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001348}
1349
1350/* Write the Lua input string in the output buffer.
1351 * This fucntion returns a yield if no space are available.
1352 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001353static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001354{
1355 struct hlua_socket *socket;
1356 struct hlua *hlua = hlua_gethlua(L);
1357 struct appctx *appctx;
1358 size_t buf_len;
1359 const char *buf;
1360 int len;
1361 int send_len;
1362 int sent;
1363
1364 /* Check if this lua stack is schedulable. */
1365 if (!hlua || !hlua->task)
1366 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1367 "'frontend', 'backend' or 'task'"));
1368
1369 /* Get object */
1370 socket = MAY_LJMP(hlua_checksocket(L, 1));
1371 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001372 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001373
1374 /* Check for connection close. */
1375 if (!socket->s || channel_output_closed(socket->s->req)) {
1376 lua_pushinteger(L, -1);
1377 return 1;
1378 }
1379
1380 /* Update the input buffer data. */
1381 buf += sent;
1382 send_len = buf_len - sent;
1383
1384 /* All the data are sent. */
1385 if (sent >= buf_len)
1386 return 1; /* Implicitly return the length sent. */
1387
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001388 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1389 * the request buffer if its not required.
1390 */
1391 if (socket->s->req->buf->size == 0) {
1392 if (!session_alloc_recv_buffer(socket->s, &socket->s->req->buf)) {
1393 socket->s->req->prod->flags |= SI_FL_WAIT_ROOM;
1394 goto hlua_socket_write_yield_return;
1395 }
1396 }
1397
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001398 /* Check for avalaible space. */
1399 len = buffer_total_space(socket->s->si[0].ib->buf);
1400 if (len <= 0)
1401 goto hlua_socket_write_yield_return;
1402
1403 /* send data */
1404 if (len < send_len)
1405 send_len = len;
1406 len = bi_putblk(socket->s->si[0].ib, buf+sent, send_len);
1407
1408 /* "Not enough space" (-1), "Buffer too little to contain
1409 * the data" (-2) are not expected because the available length
1410 * is tested.
1411 * Other unknown error are also not expected.
1412 */
1413 if (len <= 0) {
1414 MAY_LJMP(hlua_socket_close(L));
1415 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001416 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001417 return 1;
1418 }
1419
1420 /* update buffers. */
1421 si_update(&socket->s->si[0]);
1422 socket->s->si[0].ib->rex = TICK_ETERNITY;
1423 socket->s->si[0].ob->wex = TICK_ETERNITY;
1424
1425 /* Update length sent. */
1426 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001427 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001428
1429 /* All the data buffer is sent ? */
1430 if (sent + len >= buf_len)
1431 return 1;
1432
1433hlua_socket_write_yield_return:
1434 appctx = objt_appctx(socket->s->si[0].end);
1435 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1436 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001437 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001438 return 0;
1439}
1440
1441/* This function initiate the send of data. It just check the input
1442 * parameters and push an integer in the Lua stack that contain the
1443 * amount of data writed in the buffer. This is used by the function
1444 * "hlua_socket_write_yield" that can yield.
1445 *
1446 * The Lua function gets between 3 and 4 parameters. The first one is
1447 * the associated object. The second is a string buffer. The third is
1448 * a facultative integer that represents where is the buffer position
1449 * of the start of the data that can send. The first byte is the
1450 * position "1". The default value is "1". The fourth argument is a
1451 * facultative integer that represents where is the buffer position
1452 * of the end of the data that can send. The default is the last byte.
1453 */
1454static int hlua_socket_send(struct lua_State *L)
1455{
1456 int i;
1457 int j;
1458 const char *buf;
1459 size_t buf_len;
1460
1461 /* Check number of arguments. */
1462 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1463 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1464
1465 /* Get the string. */
1466 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1467
1468 /* Get and check j. */
1469 if (lua_gettop(L) == 4) {
1470 j = MAY_LJMP(luaL_checkinteger(L, 4));
1471 if (j < 0)
1472 j = buf_len + j + 1;
1473 if (j > buf_len)
1474 j = buf_len + 1;
1475 lua_pop(L, 1);
1476 }
1477 else
1478 j = buf_len;
1479
1480 /* Get and check i. */
1481 if (lua_gettop(L) == 3) {
1482 i = MAY_LJMP(luaL_checkinteger(L, 3));
1483 if (i < 0)
1484 i = buf_len + i + 1;
1485 if (i > buf_len)
1486 i = buf_len + 1;
1487 lua_pop(L, 1);
1488 } else
1489 i = 1;
1490
1491 /* Check bth i and j. */
1492 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001493 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001494 return 1;
1495 }
1496 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001497 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001498 return 1;
1499 }
1500 if (i == 0)
1501 i = 1;
1502 if (j == 0)
1503 j = 1;
1504
1505 /* Pop the string. */
1506 lua_pop(L, 1);
1507
1508 /* Update the buffer length. */
1509 buf += i - 1;
1510 buf_len = j - i + 1;
1511 lua_pushlstring(L, buf, buf_len);
1512
1513 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001514 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001515
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001516 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001517}
1518
1519#define SOCKET_INFO_EXPANDED_FORM "[0000:0000:0000:0000:0000:0000:0000:0000]:12345"
1520static char _socket_info_expanded_form[] = SOCKET_INFO_EXPANDED_FORM;
1521#define SOCKET_INFO_MAX_LEN (sizeof(_socket_info_expanded_form))
1522__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
1523{
1524 static char buffer[SOCKET_INFO_MAX_LEN];
1525 int ret;
1526 int len;
1527 char *p;
1528
1529 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
1530 if (ret <= 0) {
1531 lua_pushnil(L);
1532 return 1;
1533 }
1534
1535 if (ret == AF_UNIX) {
1536 lua_pushstring(L, buffer+1);
1537 return 1;
1538 }
1539 else if (ret == AF_INET6) {
1540 buffer[0] = '[';
1541 len = strlen(buffer);
1542 buffer[len] = ']';
1543 len++;
1544 buffer[len] = ':';
1545 len++;
1546 p = buffer;
1547 }
1548 else if (ret == AF_INET) {
1549 p = buffer + 1;
1550 len = strlen(p);
1551 p[len] = ':';
1552 len++;
1553 }
1554 else {
1555 lua_pushnil(L);
1556 return 1;
1557 }
1558
1559 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
1560 lua_pushnil(L);
1561 return 1;
1562 }
1563
1564 lua_pushstring(L, p);
1565 return 1;
1566}
1567
1568/* Returns information about the peer of the connection. */
1569__LJMP static int hlua_socket_getpeername(struct lua_State *L)
1570{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001571 struct hlua_socket *socket;
1572 struct connection *conn;
1573
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001574 MAY_LJMP(check_args(L, 1, "getpeername"));
1575
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001576 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001577
1578 /* Check if the tcp object is avalaible. */
1579 if (!socket->s) {
1580 lua_pushnil(L);
1581 return 1;
1582 }
1583
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001584 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001585 if (!conn) {
1586 lua_pushnil(L);
1587 return 1;
1588 }
1589
1590 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
1591 unsigned int salen = sizeof(conn->addr.to);
1592 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
1593 lua_pushnil(L);
1594 return 1;
1595 }
1596 conn->flags |= CO_FL_ADDR_TO_SET;
1597 }
1598
1599 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
1600}
1601
1602/* Returns information about my connection side. */
1603static int hlua_socket_getsockname(struct lua_State *L)
1604{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001605 struct hlua_socket *socket;
1606 struct connection *conn;
1607
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001608 MAY_LJMP(check_args(L, 1, "getsockname"));
1609
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001610 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001611
1612 /* Check if the tcp object is avalaible. */
1613 if (!socket->s) {
1614 lua_pushnil(L);
1615 return 1;
1616 }
1617
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001618 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001619 if (!conn) {
1620 lua_pushnil(L);
1621 return 1;
1622 }
1623
1624 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
1625 unsigned int salen = sizeof(conn->addr.from);
1626 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
1627 lua_pushnil(L);
1628 return 1;
1629 }
1630 conn->flags |= CO_FL_ADDR_FROM_SET;
1631 }
1632
1633 return hlua_socket_info(L, &conn->addr.from);
1634}
1635
1636/* This struct define the applet. */
1637static struct si_applet update_applet = {
1638 .obj_type = OBJ_TYPE_APPLET,
1639 .name = "<LUA_TCP>",
1640 .fct = hlua_socket_handler,
1641 .release = hlua_socket_release,
1642};
1643
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001644__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001645{
1646 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1647 struct hlua *hlua = hlua_gethlua(L);
1648 struct appctx *appctx;
1649
1650 /* Check for connection close. */
1651 if (!hlua || !socket->s || channel_output_closed(socket->s->req)) {
1652 lua_pushnil(L);
1653 lua_pushstring(L, "Can't connect");
1654 return 2;
1655 }
1656
1657 appctx = objt_appctx(socket->s->si[0].end);
1658
1659 /* Check for connection established. */
1660 if (appctx->ctx.hlua.connected) {
1661 lua_pushinteger(L, 1);
1662 return 1;
1663 }
1664
1665 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1666 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001667 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001668 return 0;
1669}
1670
1671/* This function fail or initite the connection. */
1672__LJMP static int hlua_socket_connect(struct lua_State *L)
1673{
1674 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001675 int port;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001676 const char *ip;
1677 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01001678 struct hlua *hlua;
1679 struct appctx *appctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001680
1681 MAY_LJMP(check_args(L, 3, "connect"));
1682
1683 /* Get args. */
1684 socket = MAY_LJMP(hlua_checksocket(L, 1));
1685 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001686 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001687
1688 conn = si_alloc_conn(socket->s->req->cons, 0);
1689 if (!conn)
1690 WILL_LJMP(luaL_error(L, "connect: internal error"));
1691
1692 /* Parse ip address. */
1693 conn->addr.to.ss_family = AF_UNSPEC;
1694 if (!str2ip2(ip, &conn->addr.to, 0))
1695 WILL_LJMP(luaL_error(L, "connect: cannot parse ip address '%s'", ip));
1696
1697 /* Set port. */
1698 if (conn->addr.to.ss_family == AF_INET)
1699 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
1700 else if (conn->addr.to.ss_family == AF_INET6)
1701 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
1702
1703 /* it is important not to call the wakeup function directly but to
1704 * pass through task_wakeup(), because this one knows how to apply
1705 * priorities to tasks.
1706 */
1707 task_wakeup(socket->s->task, TASK_WOKEN_INIT);
1708
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01001709 hlua = hlua_gethlua(L);
1710 appctx = objt_appctx(socket->s->si[0].end);
1711 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1712 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001713 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001714
1715 return 0;
1716}
1717
Baptiste Assmann84bb4932015-03-02 21:40:06 +01001718#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001719__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
1720{
1721 struct hlua_socket *socket;
1722
1723 MAY_LJMP(check_args(L, 3, "connect_ssl"));
1724 socket = MAY_LJMP(hlua_checksocket(L, 1));
1725 socket->s->target = &socket_ssl.obj_type;
1726 return MAY_LJMP(hlua_socket_connect(L));
1727}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01001728#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001729
1730__LJMP static int hlua_socket_setoption(struct lua_State *L)
1731{
1732 return 0;
1733}
1734
1735__LJMP static int hlua_socket_settimeout(struct lua_State *L)
1736{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001737 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001738 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001739
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001740 MAY_LJMP(check_args(L, 2, "settimeout"));
1741
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001742 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001743 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001744
1745 socket->s->req->rto = tmout;
1746 socket->s->req->wto = tmout;
1747 socket->s->rep->rto = tmout;
1748 socket->s->rep->wto = tmout;
1749
1750 return 0;
1751}
1752
1753__LJMP static int hlua_socket_new(lua_State *L)
1754{
1755 struct hlua_socket *socket;
1756 struct appctx *appctx;
1757
1758 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01001759 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001760 hlua_pusherror(L, "socket: full stack");
1761 goto out_fail_conf;
1762 }
1763
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01001764 /* Create the object: obj[0] = userdata. */
1765 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001766 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01001767 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001768 memset(socket, 0, sizeof(*socket));
1769
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01001770 /* Check if the various memory pools are intialized. */
1771 if (!pool2_session || !pool2_channel || !pool2_buffer) {
1772 hlua_pusherror(L, "socket: uninitialized pools.");
1773 goto out_fail_conf;
1774 }
1775
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001776 /* Pop a class session metatable and affect it to the userdata. */
1777 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
1778 lua_setmetatable(L, -2);
1779
1780 /*
1781 *
1782 * Get memory for the request.
1783 *
1784 */
1785
1786 socket->s = pool_alloc2(pool2_session);
1787 if (!socket->s) {
1788 hlua_pusherror(L, "socket: out of memory");
1789 goto out_fail_conf;
1790 }
1791
1792 socket->s->task = task_new();
1793 if (!socket->s->task) {
1794 hlua_pusherror(L, "socket: out of memory");
1795 goto out_free_session;
1796 }
1797
1798 socket->s->req = pool_alloc2(pool2_channel);
1799 if (!socket->s->req) {
1800 hlua_pusherror(L, "socket: out of memory");
1801 goto out_fail_req;
1802 }
1803
1804 socket->s->req->buf = pool_alloc2(pool2_buffer);
1805 if (!socket->s->req->buf) {
1806 hlua_pusherror(L, "socket: out of memory");
1807 goto out_fail_req_buf;
1808 }
1809
1810 socket->s->rep = pool_alloc2(pool2_channel);
1811 if (!socket->s->rep) {
1812 hlua_pusherror(L, "socket: out of memory");
1813 goto out_fail_rep;
1814 }
1815
1816 socket->s->rep->buf = pool_alloc2(pool2_buffer);
1817 if (!socket->s->rep->buf) {
1818 hlua_pusherror(L, "socket: out of memory");
1819 goto out_fail_rep_buf;
1820 }
1821
1822 /* Configura empty Lua for the session. */
1823 socket->s->hlua.T = NULL;
1824 socket->s->hlua.Tref = LUA_REFNIL;
1825 socket->s->hlua.Mref = LUA_REFNIL;
1826 socket->s->hlua.nargs = 0;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001827 socket->s->hlua.flags = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001828 LIST_INIT(&socket->s->hlua.com);
1829
1830 /* session initialisation. */
1831 session_init_srv_conn(socket->s);
1832
1833 /*
1834 *
1835 * Configure the associated task.
1836 *
1837 */
1838
1839 /* This is the dedicated function to process the session. This function
1840 * is able to establish the conection, process the timeouts, etc ...
1841 */
1842 socket->s->task->process = process_session;
1843
1844 /* Back reference to session. This is used by process_session(). */
1845 socket->s->task->context = socket->s;
1846
1847 /* The priority of the task is normal. */
1848 socket->s->task->nice = 0;
1849
1850 /* Init the next run to eternity. Later in this function, this task is
1851 * waked.
1852 */
1853 socket->s->task->expire = TICK_ETERNITY;
1854
1855 /*
1856 *
1857 * Initialize the attached buffers
1858 *
1859 */
1860 socket->s->req->buf->size = global.tune.bufsize;
1861 socket->s->rep->buf->size = global.tune.bufsize;
1862
1863 /*
1864 *
1865 * Initialize channels.
1866 *
1867 */
1868
1869 /* This function reset the struct. It must be called
1870 * before the configuration.
1871 */
1872 channel_init(socket->s->req);
1873 channel_init(socket->s->rep);
1874
1875 socket->s->req->prod = &socket->s->si[0];
1876 socket->s->req->cons = &socket->s->si[1];
1877
1878 socket->s->rep->prod = &socket->s->si[1];
1879 socket->s->rep->cons = &socket->s->si[0];
1880
1881 socket->s->si[0].ib = socket->s->req;
1882 socket->s->si[0].ob = socket->s->rep;
1883
1884 socket->s->si[1].ib = socket->s->rep;
1885 socket->s->si[1].ob = socket->s->req;
1886
1887 socket->s->req->analysers = 0;
1888 socket->s->req->rto = socket_proxy.timeout.client;
1889 socket->s->req->wto = socket_proxy.timeout.server;
1890 socket->s->req->rex = TICK_ETERNITY;
1891 socket->s->req->wex = TICK_ETERNITY;
1892 socket->s->req->analyse_exp = TICK_ETERNITY;
1893
1894 socket->s->rep->analysers = 0;
1895 socket->s->rep->rto = socket_proxy.timeout.server;
1896 socket->s->rep->wto = socket_proxy.timeout.client;
1897 socket->s->rep->rex = TICK_ETERNITY;
1898 socket->s->rep->wex = TICK_ETERNITY;
1899 socket->s->rep->analyse_exp = TICK_ETERNITY;
1900
1901 /*
1902 *
1903 * Configure the session.
1904 *
1905 */
1906
1907 /* The session dont have listener. The listener is used with real
1908 * proxies.
1909 */
1910 socket->s->listener = NULL;
1911
1912 /* The flags are initialized to 0. Values are setted later. */
1913 socket->s->flags = 0;
1914
1915 /* Assign the configured proxy to the new session. */
1916 socket->s->be = &socket_proxy;
1917 socket->s->fe = &socket_proxy;
1918
1919 /* XXX: Set namy variables */
1920 socket->s->store_count = 0;
1921 memset(socket->s->stkctr, 0, sizeof(socket->s->stkctr));
1922
1923 /* Configure logs. */
1924 socket->s->logs.logwait = 0;
1925 socket->s->logs.level = 0;
1926 socket->s->logs.accept_date = date; /* user-visible date for logging */
1927 socket->s->logs.tv_accept = now; /* corrected date for internal use */
1928 socket->s->do_log = NULL;
1929
1930 /* Function used if an error is occured. */
1931 socket->s->srv_error = default_srv_error;
1932
1933 /* Init the list of buffers. */
1934 LIST_INIT(&socket->s->buffer_wait);
1935
1936 /* Dont configure the unique ID. */
1937 socket->s->uniq_id = 0;
1938 socket->s->unique_id = NULL;
1939
1940 /* XXX: ? */
1941 socket->s->pend_pos = NULL;
1942
1943 /* XXX: See later. */
1944 socket->s->txn.sessid = NULL;
1945 socket->s->txn.srv_cookie = NULL;
1946 socket->s->txn.cli_cookie = NULL;
1947 socket->s->txn.uri = NULL;
1948 socket->s->txn.req.cap = NULL;
1949 socket->s->txn.rsp.cap = NULL;
1950 socket->s->txn.hdr_idx.v = NULL;
1951 socket->s->txn.hdr_idx.size = 0;
1952 socket->s->txn.hdr_idx.used = 0;
1953
1954 /* Configure "left" stream interface as applet. This "si" produce
1955 * and use the data received from the server. The applet is initialized
1956 * and is attached to the stream interface.
1957 */
1958
1959 /* The data producer is already connected. It is the applet. */
1960 socket->s->req->flags = CF_READ_ATTACHED;
1961
1962 channel_auto_connect(socket->s->req); /* don't wait to establish connection */
1963 channel_auto_close(socket->s->req); /* let the producer forward close requests */
1964
1965 si_reset(&socket->s->si[0], socket->s->task);
1966 si_set_state(&socket->s->si[0], SI_ST_EST); /* connection established (resource exists) */
1967
1968 appctx = stream_int_register_handler(&socket->s->si[0], &update_applet);
1969 if (!appctx)
1970 goto out_fail_conn1;
1971 appctx->ctx.hlua.socket = socket;
1972 appctx->ctx.hlua.connected = 0;
1973 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
1974 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
1975
1976 /* Configure "right" stream interface. this "si" is used to connect
1977 * and retrieve data from the server. The connection is initialized
1978 * with the "struct server".
1979 */
1980 si_reset(&socket->s->si[1], socket->s->task);
1981 si_set_state(&socket->s->si[1], SI_ST_INI);
1982 socket->s->si[1].conn_retries = socket_proxy.conn_retries;
1983
1984 /* Force destination server. */
1985 socket->s->flags |= SN_DIRECT | SN_ASSIGNED | SN_ADDR_SET | SN_BE_ASSIGNED;
1986 socket->s->target = &socket_tcp.obj_type;
1987
1988 /* This session is added to te lists of alive sessions. */
1989 LIST_ADDQ(&sessions, &socket->s->list);
1990
1991 /* XXX: I think that this list is used by stats. */
1992 LIST_INIT(&socket->s->back_refs);
1993
1994 /* Update statistics counters. */
1995 socket_proxy.feconn++; /* beconn will be increased later */
1996 jobs++;
1997 totalconn++;
1998
1999 /* Return yield waiting for connection. */
2000 return 1;
2001
2002out_fail_conn1:
2003 pool_free2(pool2_buffer, socket->s->rep->buf);
2004out_fail_rep_buf:
2005 pool_free2(pool2_channel, socket->s->rep);
2006out_fail_rep:
2007 pool_free2(pool2_buffer, socket->s->req->buf);
2008out_fail_req_buf:
2009 pool_free2(pool2_channel, socket->s->req);
2010out_fail_req:
2011 task_free(socket->s->task);
2012out_free_session:
2013 pool_free2(pool2_session, socket->s);
2014out_fail_conf:
2015 WILL_LJMP(lua_error(L));
2016 return 0;
2017}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002018
2019/*
2020 *
2021 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002022 * Class Channel
2023 *
2024 *
2025 */
2026
2027/* Returns the struct hlua_channel join to the class channel in the
2028 * stack entry "ud" or throws an argument error.
2029 */
2030__LJMP static struct hlua_channel *hlua_checkchannel(lua_State *L, int ud)
2031{
2032 return (struct hlua_channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
2033}
2034
2035/* Creates new channel object and put it on the top of the stack.
2036 * If the stask does not have a free slots, the function fails
2037 * and returns 0;
2038 */
Thierry FOURNIERbd1f1322015-03-05 17:04:41 +01002039static int hlua_channel_new(lua_State *L, struct session *s, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002040{
2041 struct hlua_channel *chn;
2042
2043 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002044 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002045 return 0;
2046
2047 /* NOTE: The allocation never fails. The failure
2048 * throw an error, and the function never returns.
2049 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002050 lua_newtable(L);
2051 chn = MAY_LJMP(lua_newuserdata(L, sizeof(*chn)));
2052 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002053 chn->chn = channel;
Thierry FOURNIERbd1f1322015-03-05 17:04:41 +01002054 chn->s = s;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002055
2056 /* Pop a class sesison metatable and affect it to the userdata. */
2057 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2058 lua_setmetatable(L, -2);
2059
2060 return 1;
2061}
2062
2063/* Duplicate all the data present in the input channel and put it
2064 * in a string LUA variables. Returns -1 and push a nil value in
2065 * the stack if the channel is closed and all the data are consumed,
2066 * returns 0 if no data are available, otherwise it returns the length
2067 * of the builded string.
2068 */
2069static inline int _hlua_channel_dup(struct hlua_channel *chn, lua_State *L)
2070{
2071 char *blk1;
2072 char *blk2;
2073 int len1;
2074 int len2;
2075 int ret;
2076 luaL_Buffer b;
2077
2078 ret = bi_getblk_nc(chn->chn, &blk1, &len1, &blk2, &len2);
2079 if (unlikely(ret == 0))
2080 return 0;
2081
2082 if (unlikely(ret < 0)) {
2083 lua_pushnil(L);
2084 return -1;
2085 }
2086
2087 luaL_buffinit(L, &b);
2088 luaL_addlstring(&b, blk1, len1);
2089 if (unlikely(ret == 2))
2090 luaL_addlstring(&b, blk2, len2);
2091 luaL_pushresult(&b);
2092
2093 if (unlikely(ret == 2))
2094 return len1 + len2;
2095 return len1;
2096}
2097
2098/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2099 * a yield. This function keep the data in the buffer.
2100 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002101__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002102{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002103 struct hlua_channel *chn;
2104
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002105 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2106
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002107 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002108 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002109 return 1;
2110}
2111
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002112/* Check arguments for the function "hlua_channel_dup_yield". */
2113__LJMP static int hlua_channel_dup(lua_State *L)
2114{
2115 MAY_LJMP(check_args(L, 1, "dup"));
2116 MAY_LJMP(hlua_checkchannel(L, 1));
2117 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2118}
2119
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002120/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2121 * a yield. This function consumes the data in the buffer. It returns
2122 * a string containing the data or a nil pointer if no data are available
2123 * and the channel is closed.
2124 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002125__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002126{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002127 struct hlua_channel *chn;
2128 int ret;
2129
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002130 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002131
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002132 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002133 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002134 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002135
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002136 if (unlikely(ret == -1))
2137 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002138
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002139 chn->chn->buf->i -= ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002140 return 1;
2141}
2142
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002143/* Check arguments for the fucntion "hlua_channel_get_yield". */
2144__LJMP static int hlua_channel_get(lua_State *L)
2145{
2146 MAY_LJMP(check_args(L, 1, "get"));
2147 MAY_LJMP(hlua_checkchannel(L, 1));
2148 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2149}
2150
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002151/* This functions consumes and returns one line. If the channel is closed,
2152 * and the last data does not contains a final '\n', the data are returned
2153 * without the final '\n'. When no more data are avalaible, it returns nil
2154 * value.
2155 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002156__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002157{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002158 char *blk1;
2159 char *blk2;
2160 int len1;
2161 int len2;
2162 int len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002163 struct hlua_channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002164 int ret;
2165 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002166
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002167 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2168
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002169 ret = bi_getline_nc(chn->chn, &blk1, &len1, &blk2, &len2);
2170 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002171 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002172
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002173 if (ret == -1) {
2174 lua_pushnil(L);
2175 return 1;
2176 }
2177
2178 luaL_buffinit(L, &b);
2179 luaL_addlstring(&b, blk1, len1);
2180 len = len1;
2181 if (unlikely(ret == 2)) {
2182 luaL_addlstring(&b, blk2, len2);
2183 len += len2;
2184 }
2185 luaL_pushresult(&b);
2186 buffer_replace2(chn->chn->buf, chn->chn->buf->p, chn->chn->buf->p + len, NULL, 0);
2187 return 1;
2188}
2189
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002190/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2191__LJMP static int hlua_channel_getline(lua_State *L)
2192{
2193 MAY_LJMP(check_args(L, 1, "getline"));
2194 MAY_LJMP(hlua_checkchannel(L, 1));
2195 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2196}
2197
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002198/* This function takes a string as input, and append it at the
2199 * input side of channel. If the data is too big, but a space
2200 * is probably available after sending some data, the function
2201 * yield. If the data is bigger than the buffer, or if the
2202 * channel is closed, it returns -1. otherwise, it returns the
2203 * amount of data writed.
2204 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002205__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002206{
2207 struct hlua_channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
2208 size_t len;
2209 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2210 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2211 int ret;
2212 int max;
2213
2214 max = channel_recv_limit(chn->chn) - buffer_len(chn->chn->buf);
2215 if (max > len - l)
2216 max = len - l;
2217
2218 ret = bi_putblk(chn->chn, str+l, max);
2219 if (ret == -2 || ret == -3) {
2220 lua_pushinteger(L, -1);
2221 return 1;
2222 }
2223 if (ret == -1)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002224 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002225 l += ret;
2226 lua_pop(L, 1);
2227 lua_pushinteger(L, l);
2228
2229 max = channel_recv_limit(chn->chn) - buffer_len(chn->chn->buf);
2230 if (max == 0 && chn->chn->buf->o == 0) {
2231 /* There are no space avalaible, and the output buffer is empty.
2232 * in this case, we cannot add more data, so we cannot yield,
2233 * we return the amount of copyied data.
2234 */
2235 return 1;
2236 }
2237 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002238 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002239 return 1;
2240}
2241
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002242/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002243 * of the writed string, or -1 if the channel is closed or if the
2244 * buffer size is too little for the data.
2245 */
2246__LJMP static int hlua_channel_append(lua_State *L)
2247{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002248 size_t len;
2249
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002250 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002251 MAY_LJMP(hlua_checkchannel(L, 1));
2252 MAY_LJMP(luaL_checklstring(L, 2, &len));
2253 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002254 lua_pushinteger(L, 0);
2255
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002256 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002257}
2258
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002259/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002260 * his process by cleaning the buffer. The result is a replacement
2261 * of the current data. It returns the length of the writed string,
2262 * or -1 if the channel is closed or if the buffer size is too
2263 * little for the data.
2264 */
2265__LJMP static int hlua_channel_set(lua_State *L)
2266{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002267 struct hlua_channel *chn;
2268
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002269 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002270 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002271 lua_pushinteger(L, 0);
2272
2273 chn->chn->buf->i = 0;
2274
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002275 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002276}
2277
2278/* Append data in the output side of the buffer. This data is immediatly
2279 * sent. The fcuntion returns the ammount of data writed. If the buffer
2280 * cannot contains the data, the function yield. The function returns -1
2281 * if the channel is closed.
2282 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002283__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002284{
2285 struct hlua_channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
2286 size_t len;
2287 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2288 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2289 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002290 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002291
2292 if (unlikely(channel_output_closed(chn->chn))) {
2293 lua_pushinteger(L, -1);
2294 return 1;
2295 }
2296
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002297 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2298 * the request buffer if its not required.
2299 */
2300 if (chn->chn->buf->size == 0) {
2301 if (!session_alloc_recv_buffer(chn->s, &chn->chn->buf)) {
2302 chn->chn->prod->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002303 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002304 }
2305 }
2306
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002307 /* the writed data will be immediatly sent, so we can check
2308 * the avalaible space without taking in account the reserve.
2309 * The reserve is guaranted for the processing of incoming
2310 * data, because the buffer will be flushed.
2311 */
2312 max = chn->chn->buf->size - buffer_len(chn->chn->buf);
2313
2314 /* If there are no space avalaible, and the output buffer is empty.
2315 * in this case, we cannot add more data, so we cannot yield,
2316 * we return the amount of copyied data.
2317 */
2318 if (max == 0 && chn->chn->buf->o == 0)
2319 return 1;
2320
2321 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002322 if (max > len - l)
2323 max = len - l;
2324
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002325 /* The buffer avalaible size may be not contiguous. This test
2326 * detects a non contiguous buffer and realign it.
2327 */
Thierry FOURNIERd2b597a2015-03-07 14:38:50 +01002328 if (bi_space_for_replace(chn->chn->buf) < max)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002329 buffer_slow_realign(chn->chn->buf);
2330
2331 /* Copy input data in the buffer. */
Thierry FOURNIER506e46c2015-03-04 11:44:47 +01002332 max = buffer_replace2(chn->chn->buf, chn->chn->buf->p, chn->chn->buf->p, str+l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002333
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002334 /* buffer replace considers that the input part is filled.
2335 * so, I must forward these new data in the output part.
2336 */
2337 b_adv(chn->chn->buf, max);
2338
2339 l += max;
2340 lua_pop(L, 1);
2341 lua_pushinteger(L, l);
2342
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002343 /* If there are no space avalaible, and the output buffer is empty.
2344 * in this case, we cannot add more data, so we cannot yield,
2345 * we return the amount of copyied data.
2346 */
2347 max = chn->chn->buf->size - buffer_len(chn->chn->buf);
2348 if (max == 0 && chn->chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002349 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002350
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002351 if (l < len) {
2352 /* If we are waiting for space in the response buffer, we
2353 * must set the flag WAKERESWR. This flag required the task
2354 * wake up if any activity is detected on the response buffer.
2355 */
2356 if (chn->chn == chn->s->rep)
2357 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002358 else
2359 HLUA_SET_WAKEREQWR(hlua);
2360 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002361 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002362
2363 return 1;
2364}
2365
2366/* Just a wraper of "_hlua_channel_send". This wrapper permits
2367 * yield the LUA process, and resume it without checking the
2368 * input arguments.
2369 */
2370__LJMP static int hlua_channel_send(lua_State *L)
2371{
2372 MAY_LJMP(check_args(L, 2, "send"));
2373 lua_pushinteger(L, 0);
2374
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002375 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002376}
2377
2378/* This function forward and amount of butes. The data pass from
2379 * the input side of the buffer to the output side, and can be
2380 * forwarded. This function never fails.
2381 *
2382 * The Lua function takes an amount of bytes to be forwarded in
2383 * imput. It returns the number of bytes forwarded.
2384 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002385__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002386{
2387 struct hlua_channel *chn;
2388 int len;
2389 int l;
2390 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002391 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002392
2393 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2394 len = MAY_LJMP(luaL_checkinteger(L, 2));
2395 l = MAY_LJMP(luaL_checkinteger(L, -1));
2396
2397 max = len - l;
2398 if (max > chn->chn->buf->i)
2399 max = chn->chn->buf->i;
2400 channel_forward(chn->chn, max);
2401 l += max;
2402
2403 lua_pop(L, 1);
2404 lua_pushinteger(L, l);
2405
2406 /* Check if it miss bytes to forward. */
2407 if (l < len) {
2408 /* The the input channel or the output channel are closed, we
2409 * must return the amount of data forwarded.
2410 */
2411 if (channel_input_closed(chn->chn) || channel_output_closed(chn->chn))
2412 return 1;
2413
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002414 /* If we are waiting for space data in the response buffer, we
2415 * must set the flag WAKERESWR. This flag required the task
2416 * wake up if any activity is detected on the response buffer.
2417 */
2418 if (chn->chn == chn->s->rep)
2419 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002420 else
2421 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002422
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002423 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002424 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002425 }
2426
2427 return 1;
2428}
2429
2430/* Just check the input and prepare the stack for the previous
2431 * function "hlua_channel_forward_yield"
2432 */
2433__LJMP static int hlua_channel_forward(lua_State *L)
2434{
2435 MAY_LJMP(check_args(L, 2, "forward"));
2436 MAY_LJMP(hlua_checkchannel(L, 1));
2437 MAY_LJMP(luaL_checkinteger(L, 2));
2438
2439 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002440 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002441}
2442
2443/* Just returns the number of bytes available in the input
2444 * side of the buffer. This function never fails.
2445 */
2446__LJMP static int hlua_channel_get_in_len(lua_State *L)
2447{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002448 struct hlua_channel *chn;
2449
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002450 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002451 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002452 lua_pushinteger(L, chn->chn->buf->i);
2453 return 1;
2454}
2455
2456/* Just returns the number of bytes available in the output
2457 * side of the buffer. This function never fails.
2458 */
2459__LJMP static int hlua_channel_get_out_len(lua_State *L)
2460{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002461 struct hlua_channel *chn;
2462
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002463 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002464 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002465 lua_pushinteger(L, chn->chn->buf->o);
2466 return 1;
2467}
2468
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002469/*
2470 *
2471 *
2472 * Class Fetches
2473 *
2474 *
2475 */
2476
2477/* Returns a struct hlua_session if the stack entry "ud" is
2478 * a class session, otherwise it throws an error.
2479 */
2480__LJMP static struct hlua_txn *hlua_checkfetches(lua_State *L, int ud)
2481{
2482 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
2483}
2484
2485/* This function creates and push in the stack a fetch object according
2486 * with a current TXN.
2487 */
2488static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn)
2489{
2490 struct hlua_txn *hs;
2491
2492 /* Check stack size. */
2493 if (!lua_checkstack(L, 3))
2494 return 0;
2495
2496 /* Create the object: obj[0] = userdata.
2497 * Note that the base of the Fetches object is the
2498 * transaction object.
2499 */
2500 lua_newtable(L);
2501 hs = lua_newuserdata(L, sizeof(struct hlua_txn));
2502 lua_rawseti(L, -2, 0);
2503
2504 hs->s = txn->s;
2505 hs->p = txn->p;
2506 hs->l7 = txn->l7;
2507
2508 /* Pop a class sesison metatable and affect it to the userdata. */
2509 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2510 lua_setmetatable(L, -2);
2511
2512 return 1;
2513}
2514
2515/* This function is an LUA binding. It is called with each sample-fetch.
2516 * It uses closure argument to store the associated sample-fetch. It
2517 * returns only one argument or throws an error. An error is thrown
2518 * only if an error is encountered during the argument parsing. If
2519 * the "sample-fetch" function fails, nil is returned.
2520 */
2521__LJMP static int hlua_run_sample_fetch(lua_State *L)
2522{
2523 struct hlua_txn *s;
2524 struct hlua_sample_fetch *f;
2525 struct arg args[ARGM_NBARGS + 1];
2526 int i;
2527 struct sample smp;
2528
2529 /* Get closure arguments. */
2530 f = (struct hlua_sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
2531
2532 /* Get traditionnal arguments. */
2533 s = MAY_LJMP(hlua_checkfetches(L, 1));
2534
2535 /* Get extra arguments. */
2536 for (i = 0; i < lua_gettop(L) - 1; i++) {
2537 if (i >= ARGM_NBARGS)
2538 break;
2539 hlua_lua2arg(L, i + 2, &args[i]);
2540 }
2541 args[i].type = ARGT_STOP;
2542
2543 /* Check arguments. */
2544 MAY_LJMP(hlua_lua2arg_check(L, 1, args, f->f->arg_mask));
2545
2546 /* Run the special args checker. */
2547 if (f->f->val_args && !f->f->val_args(args, NULL)) {
2548 lua_pushfstring(L, "error in arguments");
2549 WILL_LJMP(lua_error(L));
2550 }
2551
2552 /* Initialise the sample. */
2553 memset(&smp, 0, sizeof(smp));
2554
2555 /* Run the sample fetch process. */
2556 if (!f->f->process(s->p, s->s, s->l7, 0, args, &smp, f->f->kw, f->f->private)) {
2557 lua_pushnil(L);
2558 return 1;
2559 }
2560
2561 /* Convert the returned sample in lua value. */
2562 hlua_smp2lua(L, &smp);
2563 return 1;
2564}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002565
2566/*
2567 *
2568 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002569 * Class Converters
2570 *
2571 *
2572 */
2573
2574/* Returns a struct hlua_session if the stack entry "ud" is
2575 * a class session, otherwise it throws an error.
2576 */
2577__LJMP static struct hlua_txn *hlua_checkconverters(lua_State *L, int ud)
2578{
2579 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
2580}
2581
2582/* This function creates and push in the stack a Converters object
2583 * according with a current TXN.
2584 */
2585static int hlua_converters_new(lua_State *L, struct hlua_txn *txn)
2586{
2587 struct hlua_txn *hs;
2588
2589 /* Check stack size. */
2590 if (!lua_checkstack(L, 3))
2591 return 0;
2592
2593 /* Create the object: obj[0] = userdata.
2594 * Note that the base of the Converters object is the
2595 * same than the TXN object.
2596 */
2597 lua_newtable(L);
2598 hs = lua_newuserdata(L, sizeof(struct hlua_txn));
2599 lua_rawseti(L, -2, 0);
2600
2601 hs->s = txn->s;
2602 hs->p = txn->p;
2603 hs->l7 = txn->l7;
2604
2605 /* Pop a class session metatable and affect it to the table. */
2606 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
2607 lua_setmetatable(L, -2);
2608
2609 return 1;
2610}
2611
2612/* This function is an LUA binding. It is called with each converter.
2613 * It uses closure argument to store the associated converter. It
2614 * returns only one argument or throws an error. An error is thrown
2615 * only if an error is encountered during the argument parsing. If
2616 * the converter function function fails, nil is returned.
2617 */
2618__LJMP static int hlua_run_sample_conv(lua_State *L)
2619{
2620 struct hlua_txn *txn;
2621 struct sample_conv *conv;
2622 struct arg args[ARGM_NBARGS + 1];
2623 int i;
2624 struct sample smp;
2625
2626 /* Get closure arguments. */
2627 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
2628
2629 /* Get traditionnal arguments. */
2630 txn = MAY_LJMP(hlua_checkconverters(L, 1));
2631
2632 /* Get extra arguments. */
2633 for (i = 0; i < lua_gettop(L) - 2; i++) {
2634 if (i >= ARGM_NBARGS)
2635 break;
2636 hlua_lua2arg(L, i + 3, &args[i]);
2637 }
2638 args[i].type = ARGT_STOP;
2639
2640 /* Check arguments. */
2641 MAY_LJMP(hlua_lua2arg_check(L, 1, args, conv->arg_mask));
2642
2643 /* Run the special args checker. */
2644 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
2645 hlua_pusherror(L, "error in arguments");
2646 WILL_LJMP(lua_error(L));
2647 }
2648
2649 /* Initialise the sample. */
2650 if (!hlua_lua2smp(L, 2, &smp)) {
2651 hlua_pusherror(L, "error in the input argument");
2652 WILL_LJMP(lua_error(L));
2653 }
2654
2655 /* Apply expected cast. */
2656 if (!sample_casts[smp.type][conv->in_type]) {
2657 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
2658 smp_to_type[smp.type], smp_to_type[conv->in_type]);
2659 WILL_LJMP(lua_error(L));
2660 }
2661 if (sample_casts[smp.type][conv->in_type] != c_none &&
2662 !sample_casts[smp.type][conv->in_type](&smp)) {
2663 hlua_pusherror(L, "error during the input argument casting");
2664 WILL_LJMP(lua_error(L));
2665 }
2666
2667 /* Run the sample conversion process. */
2668 if (!conv->process(txn->s, args, &smp, conv->private)) {
2669 lua_pushnil(L);
2670 return 1;
2671 }
2672
2673 /* Convert the returned sample in lua value. */
2674 hlua_smp2lua(L, &smp);
2675 return 1;
2676}
2677
2678/*
2679 *
2680 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002681 * Class TXN
2682 *
2683 *
2684 */
2685
2686/* Returns a struct hlua_session if the stack entry "ud" is
2687 * a class session, otherwise it throws an error.
2688 */
2689__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
2690{
2691 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
2692}
2693
Willy Tarreau59551662015-03-10 14:23:13 +01002694__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002695{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002696 struct hlua *hlua;
2697
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002698 MAY_LJMP(check_args(L, 2, "set_priv"));
2699
2700 /* It is useles to retrieve the session, but this function
2701 * runs only in a session context.
2702 */
2703 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002704 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002705
2706 /* Remove previous value. */
2707 if (hlua->Mref != -1)
2708 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
2709
2710 /* Get and store new value. */
2711 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
2712 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
2713
2714 return 0;
2715}
2716
Willy Tarreau59551662015-03-10 14:23:13 +01002717__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002718{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002719 struct hlua *hlua;
2720
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002721 MAY_LJMP(check_args(L, 1, "get_priv"));
2722
2723 /* It is useles to retrieve the session, but this function
2724 * runs only in a session context.
2725 */
2726 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002727 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01002728
2729 /* Push configuration index in the stack. */
2730 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
2731
2732 return 1;
2733}
2734
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002735/* Create stack entry containing a class TXN. This function
2736 * return 0 if the stack does not contains free slots,
2737 * otherwise it returns 1.
2738 */
2739static int hlua_txn_new(lua_State *L, struct session *s, struct proxy *p, void *l7)
2740{
2741 struct hlua_txn *hs;
2742
2743 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002744 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002745 return 0;
2746
2747 /* NOTE: The allocation never fails. The failure
2748 * throw an error, and the function never returns.
2749 * if the throw is not avalaible, the process is aborted.
2750 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002751 /* Create the object: obj[0] = userdata. */
2752 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002753 hs = lua_newuserdata(L, sizeof(struct hlua_txn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002754 lua_rawseti(L, -2, 0);
2755
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002756 hs->s = s;
2757 hs->p = p;
2758 hs->l7 = l7;
2759
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002760 /* Create the "f" field that contains a list of fetches. */
2761 lua_pushstring(L, "f");
2762 if (!hlua_fetches_new(L, hs))
2763 return 0;
2764 lua_settable(L, -3);
2765
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002766 /* Create the "c" field that contains a list of converters. */
2767 lua_pushstring(L, "c");
2768 if (!hlua_converters_new(L, hs))
2769 return 0;
2770 lua_settable(L, -3);
2771
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002772 /* Pop a class sesison metatable and affect it to the userdata. */
2773 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
2774 lua_setmetatable(L, -2);
2775
2776 return 1;
2777}
2778
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002779/* This function returns a channel object associated
2780 * with the request channel. This function never fails,
2781 * however if the stack is full, it throws an error.
2782 */
2783__LJMP static int hlua_txn_req_channel(lua_State *L)
2784{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002785 struct hlua_txn *s;
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002786
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002787 MAY_LJMP(check_args(L, 1, "req_channel"));
2788 s = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002789
Thierry FOURNIERbd1f1322015-03-05 17:04:41 +01002790 if (!hlua_channel_new(L, s->s, s->s->req))
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002791 WILL_LJMP(luaL_error(L, "full stack"));
2792
2793 return 1;
2794}
2795
2796/* This function returns a channel object associated
2797 * with the response channel. This function never fails,
2798 * however if the stack is full, it throws an error.
2799 */
2800__LJMP static int hlua_txn_res_channel(lua_State *L)
2801{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002802 struct hlua_txn *s;
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002803
Willy Tarreaueee45392015-03-10 14:22:28 +01002804 MAY_LJMP(check_args(L, 1, "res_channel"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002805 s = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002806
Thierry FOURNIERbd1f1322015-03-05 17:04:41 +01002807 if (!hlua_channel_new(L, s->s, s->s->rep))
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01002808 WILL_LJMP(luaL_error(L, "full stack"));
2809
2810 return 1;
2811}
2812
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002813/* This function is an Lua binding that send pending data
2814 * to the client, and close the stream interface.
2815 */
2816__LJMP static int hlua_txn_close(lua_State *L)
2817{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002818 struct hlua_txn *s;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002819
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002820 MAY_LJMP(check_args(L, 1, "close"));
2821 s = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01002822
2823 channel_abort(s->s->si[0].ib);
2824 channel_auto_close(s->s->si[0].ib);
2825 channel_erase(s->s->si[0].ib);
2826 channel_auto_read(s->s->si[0].ob);
2827 channel_auto_close(s->s->si[0].ob);
2828 channel_shutr_now(s->s->si[0].ob);
2829
2830 return 0;
2831}
2832
Thierry FOURNIER9a819e72015-02-16 20:22:55 +01002833/* This function is an LUA binding. It creates ans returns
2834 * an array of HTTP headers. This function does not fails.
2835 */
Willy Tarreau59551662015-03-10 14:23:13 +01002836static int hlua_session_get_headers(lua_State *L)
Thierry FOURNIER9a819e72015-02-16 20:22:55 +01002837{
2838 struct hlua_txn *s = MAY_LJMP(hlua_checktxn(L, 1));
2839 struct session *sess = s->s;
2840 const char *cur_ptr, *cur_next, *p;
2841 int old_idx, cur_idx;
2842 struct hdr_idx_elem *cur_hdr;
2843 const char *hn, *hv;
2844 int hnl, hvl;
2845
2846 /* Create the table. */
2847 lua_newtable(L);
2848
2849 /* Build array of headers. */
2850 old_idx = 0;
2851 cur_next = sess->req->buf->p + hdr_idx_first_pos(&sess->txn.hdr_idx);
2852
2853 while (1) {
2854 cur_idx = sess->txn.hdr_idx.v[old_idx].next;
2855 if (!cur_idx)
2856 break;
2857 old_idx = cur_idx;
2858
2859 cur_hdr = &sess->txn.hdr_idx.v[cur_idx];
2860 cur_ptr = cur_next;
2861 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
2862
2863 /* Now we have one full header at cur_ptr of len cur_hdr->len,
2864 * and the next header starts at cur_next. We'll check
2865 * this header in the list as well as against the default
2866 * rule.
2867 */
2868
2869 /* look for ': *'. */
2870 hn = cur_ptr;
2871 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
2872 if (p >= cur_ptr+cur_hdr->len)
2873 continue;
2874 hnl = p - hn;
2875 p++;
2876 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
2877 p++;
2878 if (p >= cur_ptr+cur_hdr->len)
2879 continue;
2880 hv = p;
2881 hvl = cur_ptr+cur_hdr->len-p;
2882
2883 /* Push values in the table. */
2884 lua_pushlstring(L, hn, hnl);
2885 lua_pushlstring(L, hv, hvl);
2886 lua_settable(L, -3);
2887 }
2888
2889 return 1;
2890}
2891
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002892__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002893{
2894 int wakeup_ms = lua_tointeger(L, -1);
2895 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002896 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002897 return 0;
2898}
2899
2900__LJMP static int hlua_sleep(lua_State *L)
2901{
2902 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002903 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002904
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002905 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002906
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002907 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002908 wakeup_ms = tick_add(now_ms, delay);
2909 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002910
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002911 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
2912 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002913}
2914
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002915__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002916{
2917 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002918 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002919
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002920 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002921
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002922 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002923 wakeup_ms = tick_add(now_ms, delay);
2924 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002925
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002926 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
2927 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01002928}
2929
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01002930/* This functionis an LUA binding. it permits to give back
2931 * the hand at the HAProxy scheduler. It is used when the
2932 * LUA processing consumes a lot of time.
2933 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002934__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002935{
2936 return 0;
2937}
2938
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01002939__LJMP static int hlua_yield(lua_State *L)
2940{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01002941 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
2942 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01002943}
2944
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002945/* This function change the nice of the currently executed
2946 * task. It is used set low or high priority at the current
2947 * task.
2948 */
Willy Tarreau59551662015-03-10 14:23:13 +01002949__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002950{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002951 struct hlua *hlua;
2952 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002953
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002954 MAY_LJMP(check_args(L, 1, "set_nice"));
2955 hlua = hlua_gethlua(L);
2956 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002957
2958 /* If he task is not set, I'm in a start mode. */
2959 if (!hlua || !hlua->task)
2960 return 0;
2961
2962 if (nice < -1024)
2963 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002964 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01002965 nice = 1024;
2966
2967 hlua->task->nice = nice;
2968 return 0;
2969}
2970
Thierry FOURNIER24f33532015-01-23 12:13:00 +01002971/* This function is used as a calback of a task. It is called by the
2972 * HAProxy task subsystem when the task is awaked. The LUA runtime can
2973 * return an E_AGAIN signal, the emmiter of this signal must set a
2974 * signal to wake the task.
2975 */
2976static struct task *hlua_process_task(struct task *task)
2977{
2978 struct hlua *hlua = task->context;
2979 enum hlua_exec status;
2980
2981 /* We need to remove the task from the wait queue before executing
2982 * the Lua code because we don't know if it needs to wait for
2983 * another timer or not in the case of E_AGAIN.
2984 */
2985 task_delete(task);
2986
Thierry FOURNIERbd413492015-03-03 16:52:26 +01002987 /* If it is the first call to the task, we must initialize the
2988 * execution timeouts.
2989 */
2990 if (!HLUA_IS_RUNNING(hlua))
2991 hlua->expire = tick_add(now_ms, hlua_timeout_task);
2992
Thierry FOURNIER24f33532015-01-23 12:13:00 +01002993 /* Execute the Lua code. */
2994 status = hlua_ctx_resume(hlua, 1);
2995
2996 switch (status) {
2997 /* finished or yield */
2998 case HLUA_E_OK:
2999 hlua_ctx_destroy(hlua);
3000 task_delete(task);
3001 task_free(task);
3002 break;
3003
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003004 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
3005 if (hlua->wake_time != TICK_ETERNITY)
3006 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003007 break;
3008
3009 /* finished with error. */
3010 case HLUA_E_ERRMSG:
3011 send_log(NULL, LOG_ERR, "Lua task: %s.", lua_tostring(hlua->T, -1));
3012 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3013 Alert("Lua task: %s.\n", lua_tostring(hlua->T, -1));
3014 hlua_ctx_destroy(hlua);
3015 task_delete(task);
3016 task_free(task);
3017 break;
3018
3019 case HLUA_E_ERR:
3020 default:
3021 send_log(NULL, LOG_ERR, "Lua task: unknown error.");
3022 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3023 Alert("Lua task: unknown error.\n");
3024 hlua_ctx_destroy(hlua);
3025 task_delete(task);
3026 task_free(task);
3027 break;
3028 }
3029 return NULL;
3030}
3031
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003032/* This function is an LUA binding that register LUA function to be
3033 * executed after the HAProxy configuration parsing and before the
3034 * HAProxy scheduler starts. This function expect only one LUA
3035 * argument that is a function. This function returns nothing, but
3036 * throws if an error is encountered.
3037 */
3038__LJMP static int hlua_register_init(lua_State *L)
3039{
3040 struct hlua_init_function *init;
3041 int ref;
3042
3043 MAY_LJMP(check_args(L, 1, "register_init"));
3044
3045 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3046
3047 init = malloc(sizeof(*init));
3048 if (!init)
3049 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3050
3051 init->function_ref = ref;
3052 LIST_ADDQ(&hlua_init_functions, &init->l);
3053 return 0;
3054}
3055
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003056/* This functio is an LUA binding. It permits to register a task
3057 * executed in parallel of the main HAroxy activity. The task is
3058 * created and it is set in the HAProxy scheduler. It can be called
3059 * from the "init" section, "post init" or during the runtime.
3060 *
3061 * Lua prototype:
3062 *
3063 * <none> core.register_task(<function>)
3064 */
3065static int hlua_register_task(lua_State *L)
3066{
3067 struct hlua *hlua;
3068 struct task *task;
3069 int ref;
3070
3071 MAY_LJMP(check_args(L, 1, "register_task"));
3072
3073 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3074
3075 hlua = malloc(sizeof(*hlua));
3076 if (!hlua)
3077 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3078
3079 task = task_new();
3080 task->context = hlua;
3081 task->process = hlua_process_task;
3082
3083 if (!hlua_ctx_init(hlua, task))
3084 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3085
3086 /* Restore the function in the stack. */
3087 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
3088 hlua->nargs = 0;
3089
3090 /* Schedule task. */
3091 task_schedule(task, now_ms);
3092
3093 return 0;
3094}
3095
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003096/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
3097 * doesn't allow "yield" functions because the HAProxy engine cannot
3098 * resume converters.
3099 */
3100static int hlua_sample_conv_wrapper(struct session *session, const struct arg *arg_p,
3101 struct sample *smp, void *private)
3102{
3103 struct hlua_function *fcn = (struct hlua_function *)private;
3104
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003105 /* In the execution wrappers linked with a session, the
3106 * Lua context can be not initialized. This behavior
3107 * permits to save performances because a systematic
3108 * Lua initialization cause 5% performances loss.
3109 */
3110 if (!session->hlua.T && !hlua_ctx_init(&session->hlua, session->task)) {
3111 send_log(session->be, LOG_ERR, "Lua converter '%s': can't initialize Lua context.", fcn->name);
3112 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3113 Alert("Lua converter '%s': can't initialize Lua context.\n", fcn->name);
3114 return 0;
3115 }
3116
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003117 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003118 if (!HLUA_IS_RUNNING(&session->hlua)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003119 /* Check stack available size. */
3120 if (!lua_checkstack(session->hlua.T, 1)) {
3121 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
3122 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3123 Alert("Lua converter '%s': full stack.\n", fcn->name);
3124 return 0;
3125 }
3126
3127 /* Restore the function in the stack. */
3128 lua_rawgeti(session->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
3129
3130 /* convert input sample and pust-it in the stack. */
3131 if (!lua_checkstack(session->hlua.T, 1)) {
3132 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
3133 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3134 Alert("Lua converter '%s': full stack.\n", fcn->name);
3135 return 0;
3136 }
3137 hlua_smp2lua(session->hlua.T, smp);
3138 session->hlua.nargs = 2;
3139
3140 /* push keywords in the stack. */
3141 if (arg_p) {
3142 for (; arg_p->type != ARGT_STOP; arg_p++) {
3143 if (!lua_checkstack(session->hlua.T, 1)) {
3144 send_log(session->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
3145 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3146 Alert("Lua converter '%s': full stack.\n", fcn->name);
3147 return 0;
3148 }
3149 hlua_arg2lua(session->hlua.T, arg_p);
3150 session->hlua.nargs++;
3151 }
3152 }
3153
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003154 /* We must initialize the execution timeouts. */
3155 session->hlua.expire = tick_add(now_ms, hlua_timeout_session);
3156
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003157 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003158 HLUA_SET_RUN(&session->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003159 }
3160
3161 /* Execute the function. */
3162 switch (hlua_ctx_resume(&session->hlua, 0)) {
3163 /* finished. */
3164 case HLUA_E_OK:
3165 /* Convert the returned value in sample. */
3166 hlua_lua2smp(session->hlua.T, -1, smp);
3167 lua_pop(session->hlua.T, 1);
3168 return 1;
3169
3170 /* yield. */
3171 case HLUA_E_AGAIN:
3172 send_log(session->be, LOG_ERR, "Lua converter '%s': cannot use yielded functions.", fcn->name);
3173 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3174 Alert("Lua converter '%s': cannot use yielded functions.\n", fcn->name);
3175 return 0;
3176
3177 /* finished with error. */
3178 case HLUA_E_ERRMSG:
3179 /* Display log. */
3180 send_log(session->be, LOG_ERR, "Lua converter '%s': %s.", fcn->name, lua_tostring(session->hlua.T, -1));
3181 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3182 Alert("Lua converter '%s': %s.\n", fcn->name, lua_tostring(session->hlua.T, -1));
3183 lua_pop(session->hlua.T, 1);
3184 return 0;
3185
3186 case HLUA_E_ERR:
3187 /* Display log. */
3188 send_log(session->be, LOG_ERR, "Lua converter '%s' returns an unknown error.", fcn->name);
3189 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3190 Alert("Lua converter '%s' returns an unknown error.\n", fcn->name);
3191
3192 default:
3193 return 0;
3194 }
3195}
3196
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003197/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
3198 * doesn't allow "yield" functions because the HAProxy engine cannot
3199 * resume sample-fetches.
3200 */
3201static int hlua_sample_fetch_wrapper(struct proxy *px, struct session *s, void *l7,
3202 unsigned int opt, const struct arg *arg_p,
3203 struct sample *smp, const char *kw, void *private)
3204{
3205 struct hlua_function *fcn = (struct hlua_function *)private;
3206
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003207 /* In the execution wrappers linked with a session, the
3208 * Lua context can be not initialized. This behavior
3209 * permits to save performances because a systematic
3210 * Lua initialization cause 5% performances loss.
3211 */
3212 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
3213 send_log(s->be, LOG_ERR, "Lua sample-fetch '%s': can't initialize Lua context.", fcn->name);
3214 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3215 Alert("Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
3216 return 0;
3217 }
3218
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003219 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003220 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003221 /* Check stack available size. */
3222 if (!lua_checkstack(s->hlua.T, 2)) {
3223 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3224 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3225 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3226 return 0;
3227 }
3228
3229 /* Restore the function in the stack. */
3230 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
3231
3232 /* push arguments in the stack. */
3233 if (!hlua_txn_new(s->hlua.T, s, px, l7)) {
3234 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3235 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3236 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3237 return 0;
3238 }
3239 s->hlua.nargs = 1;
3240
3241 /* push keywords in the stack. */
3242 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
3243 /* Check stack available size. */
3244 if (!lua_checkstack(s->hlua.T, 1)) {
3245 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3246 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3247 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3248 return 0;
3249 }
3250 if (!lua_checkstack(s->hlua.T, 1)) {
3251 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3252 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3253 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3254 return 0;
3255 }
3256 hlua_arg2lua(s->hlua.T, arg_p);
3257 s->hlua.nargs++;
3258 }
3259
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003260 /* We must initialize the execution timeouts. */
3261 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
3262
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003263 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003264 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003265 }
3266
3267 /* Execute the function. */
3268 switch (hlua_ctx_resume(&s->hlua, 0)) {
3269 /* finished. */
3270 case HLUA_E_OK:
3271 /* Convert the returned value in sample. */
3272 hlua_lua2smp(s->hlua.T, -1, smp);
3273 lua_pop(s->hlua.T, 1);
3274
3275 /* Set the end of execution flag. */
3276 smp->flags &= ~SMP_F_MAY_CHANGE;
3277 return 1;
3278
3279 /* yield. */
3280 case HLUA_E_AGAIN:
3281 send_log(px, LOG_ERR, "Lua sample-fetch '%s': cannot use yielded functions.", fcn->name);
3282 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3283 Alert("Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
3284 return 0;
3285
3286 /* finished with error. */
3287 case HLUA_E_ERRMSG:
3288 /* Display log. */
3289 send_log(px, LOG_ERR, "Lua sample-fetch '%s': %s.", fcn->name, lua_tostring(s->hlua.T, -1));
3290 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3291 Alert("Lua sample-fetch '%s': %s.\n", fcn->name, lua_tostring(s->hlua.T, -1));
3292 lua_pop(s->hlua.T, 1);
3293 return 0;
3294
3295 case HLUA_E_ERR:
3296 /* Display log. */
3297 send_log(px, LOG_ERR, "Lua sample-fetch '%s' returns an unknown error.", fcn->name);
3298 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3299 Alert("Lua sample-fetch '%s': returns an unknown error.\n", fcn->name);
3300
3301 default:
3302 return 0;
3303 }
3304}
3305
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003306/* This function is an LUA binding used for registering
3307 * "sample-conv" functions. It expects a converter name used
3308 * in the haproxy configuration file, and an LUA function.
3309 */
3310__LJMP static int hlua_register_converters(lua_State *L)
3311{
3312 struct sample_conv_kw_list *sck;
3313 const char *name;
3314 int ref;
3315 int len;
3316 struct hlua_function *fcn;
3317
3318 MAY_LJMP(check_args(L, 2, "register_converters"));
3319
3320 /* First argument : converter name. */
3321 name = MAY_LJMP(luaL_checkstring(L, 1));
3322
3323 /* Second argument : lua function. */
3324 ref = MAY_LJMP(hlua_checkfunction(L, 2));
3325
3326 /* Allocate and fill the sample fetch keyword struct. */
3327 sck = malloc(sizeof(struct sample_conv_kw_list) +
3328 sizeof(struct sample_conv) * 2);
3329 if (!sck)
3330 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3331 fcn = malloc(sizeof(*fcn));
3332 if (!fcn)
3333 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3334
3335 /* Fill fcn. */
3336 fcn->name = strdup(name);
3337 if (!fcn->name)
3338 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3339 fcn->function_ref = ref;
3340
3341 /* List head */
3342 sck->list.n = sck->list.p = NULL;
3343
3344 /* converter keyword. */
3345 len = strlen("lua.") + strlen(name) + 1;
3346 sck->kw[0].kw = malloc(len);
3347 if (!sck->kw[0].kw)
3348 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3349
3350 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
3351 sck->kw[0].process = hlua_sample_conv_wrapper;
3352 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
3353 sck->kw[0].val_args = NULL;
3354 sck->kw[0].in_type = SMP_T_STR;
3355 sck->kw[0].out_type = SMP_T_STR;
3356 sck->kw[0].private = fcn;
3357
3358 /* End of array. */
3359 memset(&sck->kw[1], 0, sizeof(struct sample_conv));
3360
3361 /* Register this new converter */
3362 sample_register_convs(sck);
3363
3364 return 0;
3365}
3366
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003367/* This fucntion is an LUA binding used for registering
3368 * "sample-fetch" functions. It expects a converter name used
3369 * in the haproxy configuration file, and an LUA function.
3370 */
3371__LJMP static int hlua_register_fetches(lua_State *L)
3372{
3373 const char *name;
3374 int ref;
3375 int len;
3376 struct sample_fetch_kw_list *sfk;
3377 struct hlua_function *fcn;
3378
3379 MAY_LJMP(check_args(L, 2, "register_fetches"));
3380
3381 /* First argument : sample-fetch name. */
3382 name = MAY_LJMP(luaL_checkstring(L, 1));
3383
3384 /* Second argument : lua function. */
3385 ref = MAY_LJMP(hlua_checkfunction(L, 2));
3386
3387 /* Allocate and fill the sample fetch keyword struct. */
3388 sfk = malloc(sizeof(struct sample_fetch_kw_list) +
3389 sizeof(struct sample_fetch) * 2);
3390 if (!sfk)
3391 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3392 fcn = malloc(sizeof(*fcn));
3393 if (!fcn)
3394 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3395
3396 /* Fill fcn. */
3397 fcn->name = strdup(name);
3398 if (!fcn->name)
3399 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3400 fcn->function_ref = ref;
3401
3402 /* List head */
3403 sfk->list.n = sfk->list.p = NULL;
3404
3405 /* sample-fetch keyword. */
3406 len = strlen("lua.") + strlen(name) + 1;
3407 sfk->kw[0].kw = malloc(len);
3408 if (!sfk->kw[0].kw)
3409 return luaL_error(L, "lua out of memory error.");
3410
3411 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
3412 sfk->kw[0].process = hlua_sample_fetch_wrapper;
3413 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
3414 sfk->kw[0].val_args = NULL;
3415 sfk->kw[0].out_type = SMP_T_STR;
3416 sfk->kw[0].use = SMP_USE_HTTP_ANY;
3417 sfk->kw[0].val = 0;
3418 sfk->kw[0].private = fcn;
3419
3420 /* End of array. */
3421 memset(&sfk->kw[1], 0, sizeof(struct sample_fetch));
3422
3423 /* Register this new fetch. */
3424 sample_register_fetches(sfk);
3425
3426 return 0;
3427}
3428
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003429/* global {tcp|http}-request parser. Return 1 in succes case, else return 0. */
3430static int hlua_parse_rule(const char **args, int *cur_arg, struct proxy *px,
3431 struct hlua_rule **rule_p, char **err)
3432{
3433 struct hlua_rule *rule;
3434
3435 /* Memory for the rule. */
3436 rule = malloc(sizeof(*rule));
3437 if (!rule) {
3438 memprintf(err, "out of memory error");
3439 return 0;
3440 }
3441 *rule_p = rule;
3442
3443 /* The requiered arg is a function name. */
3444 if (!args[*cur_arg]) {
3445 memprintf(err, "expect Lua function name");
3446 return 0;
3447 }
3448
3449 /* Lookup for the symbol, and check if it is a function. */
3450 lua_getglobal(gL.T, args[*cur_arg]);
3451 if (lua_isnil(gL.T, -1)) {
3452 lua_pop(gL.T, 1);
3453 memprintf(err, "Lua function '%s' not found", args[*cur_arg]);
3454 return 0;
3455 }
3456 if (!lua_isfunction(gL.T, -1)) {
3457 lua_pop(gL.T, 1);
3458 memprintf(err, "'%s' is not a function", args[*cur_arg]);
3459 return 0;
3460 }
3461
3462 /* Reference the Lua function and store the reference. */
3463 rule->fcn.function_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
3464 rule->fcn.name = strdup(args[*cur_arg]);
3465 if (!rule->fcn.name) {
3466 memprintf(err, "out of memory error.");
3467 return 0;
3468 }
3469 (*cur_arg)++;
3470
3471 /* TODO: later accept arguments. */
3472 rule->args = NULL;
3473
3474 return 1;
3475}
3476
3477/* This function is a wrapper to execute each LUA function declared
3478 * as an action wrapper during the initialisation period. This function
3479 * return 1 if the processing is finished (with oe without error) and
3480 * return 0 if the function must be called again because the LUA
3481 * returns a yield.
3482 */
3483static int hlua_request_act_wrapper(struct hlua_rule *rule, struct proxy *px,
3484 struct session *s, struct http_txn *http_txn,
3485 unsigned int analyzer)
3486{
3487 char **arg;
3488
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003489 /* In the execution wrappers linked with a session, the
3490 * Lua context can be not initialized. This behavior
3491 * permits to save performances because a systematic
3492 * Lua initialization cause 5% performances loss.
3493 */
3494 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
3495 send_log(px, LOG_ERR, "Lua action '%s': can't initialize Lua context.", rule->fcn.name);
3496 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3497 Alert("Lua action '%s': can't initialize Lua context.\n", rule->fcn.name);
3498 return 0;
3499 }
3500
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003501 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003502 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003503 /* Check stack available size. */
3504 if (!lua_checkstack(s->hlua.T, 1)) {
3505 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
3506 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3507 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
3508 return 0;
3509 }
3510
3511 /* Restore the function in the stack. */
3512 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->fcn.function_ref);
3513
3514 /* Create and and push object session in the stack. */
3515 if (!hlua_txn_new(s->hlua.T, s, px, http_txn)) {
3516 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
3517 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3518 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
3519 return 0;
3520 }
3521 s->hlua.nargs = 1;
3522
3523 /* push keywords in the stack. */
3524 for (arg = rule->args; arg && *arg; arg++) {
3525 if (!lua_checkstack(s->hlua.T, 1)) {
3526 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
3527 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3528 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
3529 return 0;
3530 }
3531 lua_pushstring(s->hlua.T, *arg);
3532 s->hlua.nargs++;
3533 }
3534
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003535 /* We must initialize the execution timeouts. */
3536 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
3537
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003538 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003539 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003540 }
3541
3542 /* Execute the function. */
3543 switch (hlua_ctx_resume(&s->hlua, 1)) {
3544 /* finished. */
3545 case HLUA_E_OK:
3546 return 1;
3547
3548 /* yield. */
3549 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003550 /* Set timeout in the required channel. */
3551 if (s->hlua.wake_time != TICK_ETERNITY) {
3552 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
3553 s->req->analyse_exp = s->hlua.wake_time;
3554 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
3555 s->rep->analyse_exp = s->hlua.wake_time;
3556 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003557 /* Some actions can be wake up when a "write" event
3558 * is detected on a response channel. This is useful
3559 * only for actions targetted on the requests.
3560 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003561 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003562 s->rep->flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01003563 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
3564 s->rep->analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003565 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003566 if (HLUA_IS_WAKEREQWR(&s->hlua))
3567 s->req->flags |= CF_WAKE_WRITE;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003568 return 0;
3569
3570 /* finished with error. */
3571 case HLUA_E_ERRMSG:
3572 /* Display log. */
3573 send_log(px, LOG_ERR, "Lua function '%s': %s.", rule->fcn.name, lua_tostring(s->hlua.T, -1));
3574 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3575 Alert("Lua function '%s': %s.\n", rule->fcn.name, lua_tostring(s->hlua.T, -1));
3576 lua_pop(s->hlua.T, 1);
3577 return 1;
3578
3579 case HLUA_E_ERR:
3580 /* Display log. */
3581 send_log(px, LOG_ERR, "Lua function '%s' return an unknown error.", rule->fcn.name);
3582 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3583 Alert("Lua function '%s' return an unknown error.\n", rule->fcn.name);
3584
3585 default:
3586 return 1;
3587 }
3588}
3589
3590/* Lua execution wrapper for "tcp-request". This function uses
3591 * "hlua_request_act_wrapper" for executing the LUA code.
3592 */
3593int hlua_tcp_req_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
3594 struct session *s)
3595{
3596 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
3597 px, s, NULL, AN_REQ_INSPECT_FE);
3598}
3599
3600/* Lua execution wrapper for "tcp-response". This function uses
3601 * "hlua_request_act_wrapper" for executing the LUA code.
3602 */
3603int hlua_tcp_res_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
3604 struct session *s)
3605{
3606 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
3607 px, s, NULL, AN_RES_INSPECT);
3608}
3609
3610/* Lua execution wrapper for http-request.
3611 * This function uses "hlua_request_act_wrapper" for executing
3612 * the LUA code.
3613 */
3614int hlua_http_req_act_wrapper(struct http_req_rule *rule, struct proxy *px,
3615 struct session *s, struct http_txn *http_txn)
3616{
3617 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
3618 s, http_txn, AN_REQ_HTTP_PROCESS_FE);
3619}
3620
3621/* Lua execution wrapper for http-response.
3622 * This function uses "hlua_request_act_wrapper" for executing
3623 * the LUA code.
3624 */
3625int hlua_http_res_act_wrapper(struct http_res_rule *rule, struct proxy *px,
3626 struct session *s, struct http_txn *http_txn)
3627{
3628 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
3629 s, http_txn, AN_RES_HTTP_PROCESS_BE);
3630}
3631
3632/* tcp-request <*> configuration wrapper. */
3633static int tcp_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3634 struct tcp_rule *rule, char **err)
3635{
3636 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003637 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003638 rule->action = TCP_ACT_CUSTOM;
3639 rule->action_ptr = hlua_tcp_req_act_wrapper;
3640 return 1;
3641}
3642
3643/* tcp-response <*> configuration wrapper. */
3644static int tcp_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3645 struct tcp_rule *rule, char **err)
3646{
3647 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003648 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003649 rule->action = TCP_ACT_CUSTOM;
3650 rule->action_ptr = hlua_tcp_res_act_wrapper;
3651 return 1;
3652}
3653
3654/* http-request <*> configuration wrapper. */
3655static int http_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3656 struct http_req_rule *rule, char **err)
3657{
3658 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
3659 return -1;
3660 rule->action = HTTP_REQ_ACT_CUSTOM_CONT;
3661 rule->action_ptr = hlua_http_req_act_wrapper;
3662 return 1;
3663}
3664
3665/* http-response <*> configuration wrapper. */
3666static int http_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
3667 struct http_res_rule *rule, char **err)
3668{
3669 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
3670 return -1;
3671 rule->action = HTTP_RES_ACT_CUSTOM_CONT;
3672 rule->action_ptr = hlua_http_res_act_wrapper;
3673 return 1;
3674}
3675
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003676static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
3677 struct proxy *defpx, const char *file, int line,
3678 char **err, unsigned int *timeout)
3679{
3680 const char *error;
3681
3682 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
3683 if (error && *error != '\0') {
3684 memprintf(err, "%s: invalid timeout", args[0]);
3685 return -1;
3686 }
3687 return 0;
3688}
3689
3690static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
3691 struct proxy *defpx, const char *file, int line,
3692 char **err)
3693{
3694 return hlua_read_timeout(args, section_type, curpx, defpx,
3695 file, line, err, &hlua_timeout_session);
3696}
3697
3698static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
3699 struct proxy *defpx, const char *file, int line,
3700 char **err)
3701{
3702 return hlua_read_timeout(args, section_type, curpx, defpx,
3703 file, line, err, &hlua_timeout_task);
3704}
3705
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01003706static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
3707 struct proxy *defpx, const char *file, int line,
3708 char **err)
3709{
3710 char *error;
3711
3712 hlua_nb_instruction = strtoll(args[1], &error, 10);
3713 if (*error != '\0') {
3714 memprintf(err, "%s: invalid number", args[0]);
3715 return -1;
3716 }
3717 return 0;
3718}
3719
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01003720/* This function is called by the main configuration key "lua-load". It loads and
3721 * execute an lua file during the parsing of the HAProxy configuration file. It is
3722 * the main lua entry point.
3723 *
3724 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
3725 * occured, otherwise it returns 0.
3726 *
3727 * In some error case, LUA set an error message in top of the stack. This function
3728 * returns this error message in the HAProxy logs and pop it from the stack.
3729 */
3730static int hlua_load(char **args, int section_type, struct proxy *curpx,
3731 struct proxy *defpx, const char *file, int line,
3732 char **err)
3733{
3734 int error;
3735
3736 /* Just load and compile the file. */
3737 error = luaL_loadfile(gL.T, args[1]);
3738 if (error) {
3739 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
3740 lua_pop(gL.T, 1);
3741 return -1;
3742 }
3743
3744 /* If no syntax error where detected, execute the code. */
3745 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
3746 switch (error) {
3747 case LUA_OK:
3748 break;
3749 case LUA_ERRRUN:
3750 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
3751 lua_pop(gL.T, 1);
3752 return -1;
3753 case LUA_ERRMEM:
3754 memprintf(err, "lua out of memory error\n");
3755 return -1;
3756 case LUA_ERRERR:
3757 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
3758 lua_pop(gL.T, 1);
3759 return -1;
3760 case LUA_ERRGCMM:
3761 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
3762 lua_pop(gL.T, 1);
3763 return -1;
3764 default:
3765 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
3766 lua_pop(gL.T, 1);
3767 return -1;
3768 }
3769
3770 return 0;
3771}
3772
3773/* configuration keywords declaration */
3774static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003775 { CFG_GLOBAL, "lua-load", hlua_load },
3776 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
3777 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01003778 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01003779 { 0, NULL, NULL },
3780}};
3781
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003782static struct http_req_action_kw_list http_req_kws = {"lua", { }, {
3783 { "lua", http_req_action_register_lua },
3784 { NULL, NULL }
3785}};
3786
3787static struct http_res_action_kw_list http_res_kws = {"lua", { }, {
3788 { "lua", http_res_action_register_lua },
3789 { NULL, NULL }
3790}};
3791
3792static struct tcp_action_kw_list tcp_req_cont_kws = {"lua", { }, {
3793 { "lua", tcp_req_action_register_lua },
3794 { NULL, NULL }
3795}};
3796
3797static struct tcp_action_kw_list tcp_res_cont_kws = {"lua", { }, {
3798 { "lua", tcp_res_action_register_lua },
3799 { NULL, NULL }
3800}};
3801
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003802int hlua_post_init()
3803{
3804 struct hlua_init_function *init;
3805 const char *msg;
3806 enum hlua_exec ret;
3807
3808 list_for_each_entry(init, &hlua_init_functions, l) {
3809 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
3810 ret = hlua_ctx_resume(&gL, 0);
3811 switch (ret) {
3812 case HLUA_E_OK:
3813 lua_pop(gL.T, -1);
3814 return 1;
3815 case HLUA_E_AGAIN:
3816 Alert("lua init: yield not allowed.\n");
3817 return 0;
3818 case HLUA_E_ERRMSG:
3819 msg = lua_tostring(gL.T, -1);
3820 Alert("lua init: %s.\n", msg);
3821 return 0;
3822 case HLUA_E_ERR:
3823 default:
3824 Alert("lua init: unknown runtime error.\n");
3825 return 0;
3826 }
3827 }
3828 return 1;
3829}
3830
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01003831void hlua_init(void)
3832{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003833 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01003834 int idx;
3835 struct sample_fetch *sf;
3836 struct hlua_sample_fetch *hsf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003837 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01003838 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003839#ifdef USE_OPENSSL
3840 char *args[4];
3841 struct srv_kw *kw;
3842 int tmp_error;
3843 char *error;
3844#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003845
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01003846 /* Initialise com signals pool session. */
3847 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
3848
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003849 /* Initialise sleep pool. */
3850 pool2_hlua_sleep = create_pool("hlua_sleep", sizeof(struct hlua_sleep), MEM_F_SHARED);
3851
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01003852 /* Register configuration keywords. */
3853 cfg_register_keywords(&cfg_kws);
3854
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01003855 /* Register custom HTTP rules. */
3856 http_req_keywords_register(&http_req_kws);
3857 http_res_keywords_register(&http_res_kws);
3858 tcp_req_cont_keywords_register(&tcp_req_cont_kws);
3859 tcp_res_cont_keywords_register(&tcp_res_cont_kws);
3860
Thierry FOURNIER380d0932015-01-23 14:27:52 +01003861 /* Init main lua stack. */
3862 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003863 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01003864 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01003865 gL.T = luaL_newstate();
3866 hlua_sethlua(&gL);
3867 gL.Tref = LUA_REFNIL;
3868 gL.task = NULL;
3869
3870 /* Initialise lua. */
3871 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003872
3873 /*
3874 *
3875 * Create "core" object.
3876 *
3877 */
3878
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01003879 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003880 lua_newtable(gL.T);
3881
3882 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003883 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003884 hlua_class_const_int(gL.T, log_levels[i], i);
3885
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003886 /* Register special functions. */
3887 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003888 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003889 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003890 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003891 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01003892 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003893 hlua_class_function(gL.T, "sleep", hlua_sleep);
3894 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01003895 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
3896 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
3897 hlua_class_function(gL.T, "set_map", hlua_set_map);
3898 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01003899 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003900
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01003901 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003902
3903 /*
3904 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003905 * Register class Channel
3906 *
3907 */
3908
3909 /* Create and fill the metatable. */
3910 lua_newtable(gL.T);
3911
3912 /* Create and fille the __index entry. */
3913 lua_pushstring(gL.T, "__index");
3914 lua_newtable(gL.T);
3915
3916 /* Register . */
3917 hlua_class_function(gL.T, "get", hlua_channel_get);
3918 hlua_class_function(gL.T, "dup", hlua_channel_dup);
3919 hlua_class_function(gL.T, "getline", hlua_channel_getline);
3920 hlua_class_function(gL.T, "set", hlua_channel_set);
3921 hlua_class_function(gL.T, "append", hlua_channel_append);
3922 hlua_class_function(gL.T, "send", hlua_channel_send);
3923 hlua_class_function(gL.T, "forward", hlua_channel_forward);
3924 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
3925 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
3926
3927 lua_settable(gL.T, -3);
3928
3929 /* Register previous table in the registry with reference and named entry. */
3930 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
3931 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
3932 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
3933
3934 /*
3935 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003936 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003937 *
3938 */
3939
3940 /* Create and fill the metatable. */
3941 lua_newtable(gL.T);
3942
3943 /* Create and fille the __index entry. */
3944 lua_pushstring(gL.T, "__index");
3945 lua_newtable(gL.T);
3946
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01003947 /* Browse existing fetches and create the associated
3948 * object method.
3949 */
3950 sf = NULL;
3951 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
3952
3953 /* Dont register the keywork if the arguments check function are
3954 * not safe during the runtime.
3955 */
3956 if ((sf->val_args != NULL) &&
3957 (sf->val_args != val_payload_lv) &&
3958 (sf->val_args != val_hdr))
3959 continue;
3960
3961 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
3962 * by an underscore.
3963 */
3964 strncpy(trash.str, sf->kw, trash.size);
3965 trash.str[trash.size - 1] = '\0';
3966 for (p = trash.str; *p; p++)
3967 if (*p == '.' || *p == '-' || *p == '+')
3968 *p = '_';
3969
3970 /* Register the function. */
3971 lua_pushstring(gL.T, trash.str);
3972 hsf = lua_newuserdata(gL.T, sizeof(struct hlua_sample_fetch));
3973 hsf->f = sf;
3974 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
3975 lua_settable(gL.T, -3);
3976 }
3977
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003978 lua_settable(gL.T, -3);
3979
3980 /* Register previous table in the registry with reference and named entry. */
3981 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
3982 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
3983 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
3984
3985 /*
3986 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003987 * Register class Converters
3988 *
3989 */
3990
3991 /* Create and fill the metatable. */
3992 lua_newtable(gL.T);
3993
3994 /* Create and fill the __index entry. */
3995 lua_pushstring(gL.T, "__index");
3996 lua_newtable(gL.T);
3997
3998 /* Browse existing converters and create the associated
3999 * object method.
4000 */
4001 sc = NULL;
4002 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
4003 /* Dont register the keywork if the arguments check function are
4004 * not safe during the runtime.
4005 */
4006 if (sc->val_args != NULL)
4007 continue;
4008
4009 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4010 * by an underscore.
4011 */
4012 strncpy(trash.str, sc->kw, trash.size);
4013 trash.str[trash.size - 1] = '\0';
4014 for (p = trash.str; *p; p++)
4015 if (*p == '.' || *p == '-' || *p == '+')
4016 *p = '_';
4017
4018 /* Register the function. */
4019 lua_pushstring(gL.T, trash.str);
4020 lua_pushlightuserdata(gL.T, sc);
4021 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
4022 lua_settable(gL.T, -3);
4023 }
4024
4025 lua_settable(gL.T, -3);
4026
4027 /* Register previous table in the registry with reference and named entry. */
4028 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4029 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
4030 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4031
4032 /*
4033 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004034 * Register class TXN
4035 *
4036 */
4037
4038 /* Create and fill the metatable. */
4039 lua_newtable(gL.T);
4040
4041 /* Create and fille the __index entry. */
4042 lua_pushstring(gL.T, "__index");
4043 lua_newtable(gL.T);
4044
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004045 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01004046 hlua_class_function(gL.T, "get_headers", hlua_session_get_headers);
4047 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
4048 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIERe94e7742015-02-17 14:59:53 +01004049 hlua_class_function(gL.T, "req_channel", hlua_txn_req_channel);
4050 hlua_class_function(gL.T, "res_channel", hlua_txn_res_channel);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004051 hlua_class_function(gL.T, "close", hlua_txn_close);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004052
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004053 lua_settable(gL.T, -3);
4054
4055 /* Register previous table in the registry with reference and named entry. */
4056 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4057 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
4058 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004059
4060 /*
4061 *
4062 * Register class Socket
4063 *
4064 */
4065
4066 /* Create and fill the metatable. */
4067 lua_newtable(gL.T);
4068
4069 /* Create and fille the __index entry. */
4070 lua_pushstring(gL.T, "__index");
4071 lua_newtable(gL.T);
4072
Baptiste Assmann84bb4932015-03-02 21:40:06 +01004073#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004074 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01004075#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004076 hlua_class_function(gL.T, "connect", hlua_socket_connect);
4077 hlua_class_function(gL.T, "send", hlua_socket_send);
4078 hlua_class_function(gL.T, "receive", hlua_socket_receive);
4079 hlua_class_function(gL.T, "close", hlua_socket_close);
4080 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
4081 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
4082 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
4083 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
4084
4085 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
4086
4087 /* Register the garbage collector entry. */
4088 lua_pushstring(gL.T, "__gc");
4089 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
4090 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
4091
4092 /* Register previous table in the registry with reference and named entry. */
4093 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4094 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4095 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
4096 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
4097
4098 /* Proxy and server configuration initialisation. */
4099 memset(&socket_proxy, 0, sizeof(socket_proxy));
4100 init_new_proxy(&socket_proxy);
4101 socket_proxy.parent = NULL;
4102 socket_proxy.last_change = now.tv_sec;
4103 socket_proxy.id = "LUA-SOCKET";
4104 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
4105 socket_proxy.maxconn = 0;
4106 socket_proxy.accept = NULL;
4107 socket_proxy.options2 |= PR_O2_INDEPSTR;
4108 socket_proxy.srv = NULL;
4109 socket_proxy.conn_retries = 0;
4110 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
4111
4112 /* Init TCP server: unchanged parameters */
4113 memset(&socket_tcp, 0, sizeof(socket_tcp));
4114 socket_tcp.next = NULL;
4115 socket_tcp.proxy = &socket_proxy;
4116 socket_tcp.obj_type = OBJ_TYPE_SERVER;
4117 LIST_INIT(&socket_tcp.actconns);
4118 LIST_INIT(&socket_tcp.pendconns);
4119 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
4120 socket_tcp.last_change = 0;
4121 socket_tcp.id = "LUA-TCP-CONN";
4122 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
4123 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
4124 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
4125
4126 /* XXX: Copy default parameter from default server,
4127 * but the default server is not initialized.
4128 */
4129 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
4130 socket_tcp.minconn = socket_proxy.defsrv.minconn;
4131 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
4132 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
4133 socket_tcp.onerror = socket_proxy.defsrv.onerror;
4134 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
4135 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
4136 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
4137 socket_tcp.uweight = socket_proxy.defsrv.iweight;
4138 socket_tcp.iweight = socket_proxy.defsrv.iweight;
4139
4140 socket_tcp.check.status = HCHK_STATUS_INI;
4141 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
4142 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
4143 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
4144 socket_tcp.check.server = &socket_tcp;
4145
4146 socket_tcp.agent.status = HCHK_STATUS_INI;
4147 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
4148 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
4149 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
4150 socket_tcp.agent.server = &socket_tcp;
4151
4152 socket_tcp.xprt = &raw_sock;
4153
4154#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004155 /* Init TCP server: unchanged parameters */
4156 memset(&socket_ssl, 0, sizeof(socket_ssl));
4157 socket_ssl.next = NULL;
4158 socket_ssl.proxy = &socket_proxy;
4159 socket_ssl.obj_type = OBJ_TYPE_SERVER;
4160 LIST_INIT(&socket_ssl.actconns);
4161 LIST_INIT(&socket_ssl.pendconns);
4162 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
4163 socket_ssl.last_change = 0;
4164 socket_ssl.id = "LUA-SSL-CONN";
4165 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
4166 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
4167 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
4168
4169 /* XXX: Copy default parameter from default server,
4170 * but the default server is not initialized.
4171 */
4172 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
4173 socket_ssl.minconn = socket_proxy.defsrv.minconn;
4174 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
4175 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
4176 socket_ssl.onerror = socket_proxy.defsrv.onerror;
4177 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
4178 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
4179 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
4180 socket_ssl.uweight = socket_proxy.defsrv.iweight;
4181 socket_ssl.iweight = socket_proxy.defsrv.iweight;
4182
4183 socket_ssl.check.status = HCHK_STATUS_INI;
4184 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
4185 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
4186 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
4187 socket_ssl.check.server = &socket_ssl;
4188
4189 socket_ssl.agent.status = HCHK_STATUS_INI;
4190 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
4191 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
4192 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
4193 socket_ssl.agent.server = &socket_ssl;
4194
4195 socket_ssl.xprt = &raw_sock;
4196
4197 args[0] = "ssl";
4198 args[1] = "verify";
4199 args[2] = "none";
4200 args[3] = NULL;
4201
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004202 for (idx = 0; idx < 3; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004203 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
4204 /*
4205 *
4206 * If the keyword is not known, we can search in the registered
4207 * server keywords. This is usefull to configure special SSL
4208 * features like client certificates and ssl_verify.
4209 *
4210 */
4211 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
4212 if (tmp_error != 0) {
4213 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
4214 abort(); /* This must be never arrives because the command line
4215 not editable by the user. */
4216 }
4217 idx += kw->skip;
4218 }
4219 }
4220
4221 /* Initialize SSL server. */
4222 if (socket_ssl.xprt == &ssl_sock) {
4223 socket_ssl.use_ssl = 1;
4224 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
4225 }
4226#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01004227}