blob: 702ba4093b8652e7e2ca57c56e2c3823257a4967 [file] [log] [blame]
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001#include <sys/socket.h>
2
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003#include <ctype.h>
4
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01005#include <lauxlib.h>
6#include <lua.h>
7#include <lualib.h>
8
Thierry FOURNIER463119c2015-03-10 00:35:36 +01009#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
10#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010011#endif
12
Thierry FOURNIER380d0932015-01-23 14:27:52 +010013#include <ebpttree.h>
14
15#include <common/cfgparse.h>
16
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010017#include <types/connection.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010018#include <types/hlua.h>
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010019#include <types/proto_tcp.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010020#include <types/proxy.h>
21
Thierry FOURNIER55da1652015-01-23 11:36:30 +010022#include <proto/arg.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010023#include <proto/channel.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010024#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010025#include <proto/hlua.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020026#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010027#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010028#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010029#include <proto/payload.h>
30#include <proto/proto_http.h>
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010031#include <proto/proto_tcp.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010032#include <proto/raw_sock.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010033#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010034#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020035#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020036#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010037#include <proto/ssl_sock.h>
38#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010039#include <proto/task.h>
40
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010041/* Lua uses longjmp to perform yield or throwing errors. This
42 * macro is used only for identifying the function that can
43 * not return because a longjmp is executed.
44 * __LJMP marks a prototype of hlua file that can use longjmp.
45 * WILL_LJMP() marks an lua function that will use longjmp.
46 * MAY_LJMP() marks an lua function that may use longjmp.
47 */
48#define __LJMP
49#define WILL_LJMP(func) func
50#define MAY_LJMP(func) func
51
Thierry FOURNIER380d0932015-01-23 14:27:52 +010052/* The main Lua execution context. */
53struct hlua gL;
54
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010055/* This is the memory pool containing all the signal structs. These
56 * struct are used to store each requiered signal between two tasks.
57 */
58struct pool_head *pool2_hlua_com;
59
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010060/* Used for Socket connection. */
61static struct proxy socket_proxy;
62static struct server socket_tcp;
63#ifdef USE_OPENSSL
64static struct server socket_ssl;
65#endif
66
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010067/* List head of the function called at the initialisation time. */
68struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
69
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010070/* The following variables contains the reference of the different
71 * Lua classes. These references are useful for identify metadata
72 * associated with an object.
73 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010074static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010075static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010076static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010077static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010078static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +010079static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +020080static int class_map_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010081
Thierry FOURNIERbd413492015-03-03 16:52:26 +010082/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +020083 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +010084 * short timeout. Lua linked with tasks doesn't have a timeout
85 * because a task may remain alive during all the haproxy execution.
86 */
87static unsigned int hlua_timeout_session = 4000; /* session timeout. */
88static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
89
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010090/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
91 * it is used for preventing infinite loops.
92 *
93 * I test the scheer with an infinite loop containing one incrementation
94 * and one test. I run this loop between 10 seconds, I raise a ceil of
95 * 710M loops from one interrupt each 9000 instructions, so I fix the value
96 * to one interrupt each 10 000 instructions.
97 *
98 * configured | Number of
99 * instructions | loops executed
100 * between two | in milions
101 * forced yields |
102 * ---------------+---------------
103 * 10 | 160
104 * 500 | 670
105 * 1000 | 680
106 * 5000 | 700
107 * 7000 | 700
108 * 8000 | 700
109 * 9000 | 710 <- ceil
110 * 10000 | 710
111 * 100000 | 710
112 * 1000000 | 710
113 *
114 */
115static unsigned int hlua_nb_instruction = 10000;
116
Willy Tarreau32f61e22015-03-18 17:54:59 +0100117/* Descriptor for the memory allocation state. If limit is not null, it will
118 * be enforced on any memory allocation.
119 */
120struct hlua_mem_allocator {
121 size_t allocated;
122 size_t limit;
123};
124
125static struct hlua_mem_allocator hlua_global_allocator;
126
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100127/* These functions converts types between HAProxy internal args or
128 * sample and LUA types. Another function permits to check if the
129 * LUA stack contains arguments according with an required ARG_T
130 * format.
131 */
132static int hlua_arg2lua(lua_State *L, const struct arg *arg);
133static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100134__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
135 unsigned int mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100136static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100137static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100138static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
139
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100140/* Used to check an Lua function type in the stack. It creates and
141 * returns a reference of the function. This function throws an
142 * error if the rgument is not a "function".
143 */
144__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
145{
146 if (!lua_isfunction(L, argno)) {
147 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
148 WILL_LJMP(luaL_argerror(L, argno, msg));
149 }
150 lua_pushvalue(L, argno);
151 return luaL_ref(L, LUA_REGISTRYINDEX);
152}
153
154/* The three following functions are useful for adding entries
155 * in a table. These functions takes a string and respectively an
156 * integer, a string or a function and add it to the table in the
157 * top of the stack.
158 *
159 * These functions throws an error if no more stack size is
160 * available.
161 */
162__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100163 int value)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100164{
165 if (!lua_checkstack(L, 2))
166 WILL_LJMP(luaL_error(L, "full stack"));
167 lua_pushstring(L, name);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100168 lua_pushinteger(L, value);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100169 lua_settable(L, -3);
170}
171__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
172 const char *value)
173{
174 if (!lua_checkstack(L, 2))
175 WILL_LJMP(luaL_error(L, "full stack"));
176 lua_pushstring(L, name);
177 lua_pushstring(L, value);
178 lua_settable(L, -3);
179}
180__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
181 int (*function)(lua_State *L))
182{
183 if (!lua_checkstack(L, 2))
184 WILL_LJMP(luaL_error(L, "full stack"));
185 lua_pushstring(L, name);
186 lua_pushcclosure(L, function, 0);
187 lua_settable(L, -3);
188}
189
190/* This function check the number of arguments available in the
191 * stack. If the number of arguments available is not the same
192 * then <nb> an error is throwed.
193 */
194__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
195{
196 if (lua_gettop(L) == nb)
197 return;
198 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
199}
200
201/* Return true if the data in stack[<ud>] is an object of
202 * type <class_ref>.
203 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100204static int hlua_metaistype(lua_State *L, int ud, int class_ref)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100205{
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100206 if (!lua_getmetatable(L, ud))
207 return 0;
208
209 lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
210 if (!lua_rawequal(L, -1, -2)) {
211 lua_pop(L, 2);
212 return 0;
213 }
214
215 lua_pop(L, 2);
216 return 1;
217}
218
219/* Return an object of the expected type, or throws an error. */
220__LJMP static void *hlua_checkudata(lua_State *L, int ud, int class_ref)
221{
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100222 void *p;
223
224 /* Check if the stack entry is an array. */
225 if (!lua_istable(L, ud))
226 WILL_LJMP(luaL_argerror(L, ud, NULL));
227 /* Check if the metadata have the expected type. */
228 if (!hlua_metaistype(L, ud, class_ref))
229 WILL_LJMP(luaL_argerror(L, ud, NULL));
230 /* Push on the stack at the entry [0] of the table. */
231 lua_rawgeti(L, ud, 0);
232 /* Check if this entry is userdata. */
233 p = lua_touserdata(L, -1);
234 if (!p)
235 WILL_LJMP(luaL_argerror(L, ud, NULL));
236 /* Remove the entry returned by lua_rawgeti(). */
237 lua_pop(L, 1);
238 /* Return the associated struct. */
239 return p;
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100240}
241
242/* This fucntion push an error string prefixed by the file name
243 * and the line number where the error is encountered.
244 */
245static int hlua_pusherror(lua_State *L, const char *fmt, ...)
246{
247 va_list argp;
248 va_start(argp, fmt);
249 luaL_where(L, 1);
250 lua_pushvfstring(L, fmt, argp);
251 va_end(argp);
252 lua_concat(L, 2);
253 return 1;
254}
255
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100256/* This function register a new signal. "lua" is the current lua
257 * execution context. It contains a pointer to the associated task.
258 * "link" is a list head attached to an other task that must be wake
259 * the lua task if an event occurs. This is useful with external
260 * events like TCP I/O or sleep functions. This funcion allocate
261 * memory for the signal.
262 */
263static int hlua_com_new(struct hlua *lua, struct list *link)
264{
265 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
266 if (!com)
267 return 0;
268 LIST_ADDQ(&lua->com, &com->purge_me);
269 LIST_ADDQ(link, &com->wake_me);
270 com->task = lua->task;
271 return 1;
272}
273
274/* This function purge all the pending signals when the LUA execution
275 * is finished. This prevent than a coprocess try to wake a deleted
276 * task. This function remove the memory associated to the signal.
277 */
278static void hlua_com_purge(struct hlua *lua)
279{
280 struct hlua_com *com, *back;
281
282 /* Delete all pending communication signals. */
283 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
284 LIST_DEL(&com->purge_me);
285 LIST_DEL(&com->wake_me);
286 pool_free2(pool2_hlua_com, com);
287 }
288}
289
290/* This function sends signals. It wakes all the tasks attached
291 * to a list head, and remove the signal, and free the used
292 * memory.
293 */
294static void hlua_com_wake(struct list *wake)
295{
296 struct hlua_com *com, *back;
297
298 /* Wake task and delete all pending communication signals. */
299 list_for_each_entry_safe(com, back, wake, wake_me) {
300 LIST_DEL(&com->purge_me);
301 LIST_DEL(&com->wake_me);
302 task_wakeup(com->task, TASK_WOKEN_MSG);
303 pool_free2(pool2_hlua_com, com);
304 }
305}
306
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100307/* This functions is used with sample fetch and converters. It
308 * converts the HAProxy configuration argument in a lua stack
309 * values.
310 *
311 * It takes an array of "arg", and each entry of the array is
312 * converted and pushed in the LUA stack.
313 */
314static int hlua_arg2lua(lua_State *L, const struct arg *arg)
315{
316 switch (arg->type) {
317 case ARGT_SINT:
318 lua_pushinteger(L, arg->data.sint);
319 break;
320
321 case ARGT_UINT:
322 case ARGT_TIME:
323 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100324 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100325 break;
326
327 case ARGT_STR:
328 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
329 break;
330
331 case ARGT_IPV4:
332 case ARGT_IPV6:
333 case ARGT_MSK4:
334 case ARGT_MSK6:
335 case ARGT_FE:
336 case ARGT_BE:
337 case ARGT_TAB:
338 case ARGT_SRV:
339 case ARGT_USR:
340 case ARGT_MAP:
341 default:
342 lua_pushnil(L);
343 break;
344 }
345 return 1;
346}
347
348/* This function take one entrie in an LUA stack at the index "ud",
349 * and try to convert it in an HAProxy argument entry. This is useful
350 * with sample fetch wrappers. The input arguments are gived to the
351 * lua wrapper and converted as arg list by thi function.
352 */
353static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
354{
355 switch (lua_type(L, ud)) {
356
357 case LUA_TNUMBER:
358 case LUA_TBOOLEAN:
359 arg->type = ARGT_SINT;
360 arg->data.sint = lua_tointeger(L, ud);
361 break;
362
363 case LUA_TSTRING:
364 arg->type = ARGT_STR;
365 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
366 break;
367
368 case LUA_TUSERDATA:
369 case LUA_TNIL:
370 case LUA_TTABLE:
371 case LUA_TFUNCTION:
372 case LUA_TTHREAD:
373 case LUA_TLIGHTUSERDATA:
374 arg->type = ARGT_SINT;
375 arg->data.uint = 0;
376 break;
377 }
378 return 1;
379}
380
381/* the following functions are used to convert a struct sample
382 * in Lua type. This useful to convert the return of the
383 * fetchs or converters.
384 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100385static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100386{
387 switch (smp->type) {
388 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100389 case SMP_T_BOOL:
390 case SMP_T_UINT:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100391 lua_pushinteger(L, smp->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100392 break;
393
394 case SMP_T_BIN:
395 case SMP_T_STR:
396 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
397 break;
398
399 case SMP_T_METH:
400 switch (smp->data.meth.meth) {
401 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
402 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
403 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
404 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
405 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
406 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
407 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
408 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
409 case HTTP_METH_OTHER:
410 lua_pushlstring(L, smp->data.meth.str.str, smp->data.meth.str.len);
411 break;
412 default:
413 lua_pushnil(L);
414 break;
415 }
416 break;
417
418 case SMP_T_IPV4:
419 case SMP_T_IPV6:
420 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100421 if (sample_casts[smp->type][SMP_T_STR] &&
422 sample_casts[smp->type][SMP_T_STR](smp))
423 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
424 else
425 lua_pushnil(L);
426 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100427 default:
428 lua_pushnil(L);
429 break;
430 }
431 return 1;
432}
433
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100434/* the following functions are used to convert a struct sample
435 * in Lua strings. This is useful to convert the return of the
436 * fetchs or converters.
437 */
438static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
439{
440 switch (smp->type) {
441
442 case SMP_T_BIN:
443 case SMP_T_STR:
444 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
445 break;
446
447 case SMP_T_METH:
448 switch (smp->data.meth.meth) {
449 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
450 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
451 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
452 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
453 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
454 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
455 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
456 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
457 case HTTP_METH_OTHER:
458 lua_pushlstring(L, smp->data.meth.str.str, smp->data.meth.str.len);
459 break;
460 default:
461 lua_pushstring(L, "");
462 break;
463 }
464 break;
465
466 case SMP_T_SINT:
467 case SMP_T_BOOL:
468 case SMP_T_UINT:
469 case SMP_T_IPV4:
470 case SMP_T_IPV6:
471 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
472 if (sample_casts[smp->type][SMP_T_STR] &&
473 sample_casts[smp->type][SMP_T_STR](smp))
474 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
475 else
476 lua_pushstring(L, "");
477 break;
478 default:
479 lua_pushstring(L, "");
480 break;
481 }
482 return 1;
483}
484
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100485/* the following functions are used to convert an Lua type in a
486 * struct sample. This is useful to provide data from a converter
487 * to the LUA code.
488 */
489static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
490{
491 switch (lua_type(L, ud)) {
492
493 case LUA_TNUMBER:
494 smp->type = SMP_T_SINT;
495 smp->data.sint = lua_tointeger(L, ud);
496 break;
497
498
499 case LUA_TBOOLEAN:
500 smp->type = SMP_T_BOOL;
501 smp->data.uint = lua_toboolean(L, ud);
502 break;
503
504 case LUA_TSTRING:
505 smp->type = SMP_T_STR;
506 smp->flags |= SMP_F_CONST;
507 smp->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.str.len);
508 break;
509
510 case LUA_TUSERDATA:
511 case LUA_TNIL:
512 case LUA_TTABLE:
513 case LUA_TFUNCTION:
514 case LUA_TTHREAD:
515 case LUA_TLIGHTUSERDATA:
516 smp->type = SMP_T_BOOL;
517 smp->data.uint = 0;
518 break;
519 }
520 return 1;
521}
522
523/* This function check the "argp" builded by another conversion function
524 * is in accord with the expected argp defined by the "mask". The fucntion
525 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100526 *
527 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
528 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100529 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100530__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
531 unsigned int mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100532{
533 int min_arg;
534 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100535 struct proxy *px;
536 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100537
538 idx = 0;
539 min_arg = ARGM(mask);
540 mask >>= ARGM_BITS;
541
542 while (1) {
543
544 /* Check oversize. */
545 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100546 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100547 }
548
549 /* Check for mandatory arguments. */
550 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100551 if (idx < min_arg) {
552
553 /* If miss other argument than the first one, we return an error. */
554 if (idx > 0)
555 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
556
557 /* If first argument have a certain type, some default values
558 * may be used. See the function smp_resolve_args().
559 */
560 switch (mask & ARGT_MASK) {
561
562 case ARGT_FE:
563 if (!(p->cap & PR_CAP_FE))
564 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
565 argp[idx].data.prx = p;
566 argp[idx].type = ARGT_FE;
567 argp[idx+1].type = ARGT_STOP;
568 break;
569
570 case ARGT_BE:
571 if (!(p->cap & PR_CAP_BE))
572 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
573 argp[idx].data.prx = p;
574 argp[idx].type = ARGT_BE;
575 argp[idx+1].type = ARGT_STOP;
576 break;
577
578 case ARGT_TAB:
579 argp[idx].data.prx = p;
580 argp[idx].type = ARGT_TAB;
581 argp[idx+1].type = ARGT_STOP;
582 break;
583
584 default:
585 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
586 break;
587 }
588 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100589 return 0;
590 }
591
592 /* Check for exceed the number of requiered argument. */
593 if ((mask & ARGT_MASK) == ARGT_STOP &&
594 argp[idx].type != ARGT_STOP) {
595 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
596 }
597
598 if ((mask & ARGT_MASK) == ARGT_STOP &&
599 argp[idx].type == ARGT_STOP) {
600 return 0;
601 }
602
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100603 /* Convert some argument types. */
604 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100605 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100606 if (argp[idx].type != ARGT_SINT)
607 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
608 argp[idx].type = ARGT_SINT;
609 break;
610
611 case ARGT_UINT:
612 if (argp[idx].type != ARGT_SINT)
613 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
614 argp[idx].type = ARGT_SINT;
615 break;
616
617 case ARGT_TIME:
618 if (argp[idx].type != ARGT_SINT)
619 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
620 argp[idx].type = ARGT_SINT;
621 break;
622
623 case ARGT_SIZE:
624 if (argp[idx].type != ARGT_SINT)
625 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
626 argp[idx].type = ARGT_SINT;
627 break;
628
629 case ARGT_FE:
630 if (argp[idx].type != ARGT_STR)
631 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
632 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
633 trash.str[argp[idx].data.str.len] = 0;
634 argp[idx].data.prx = findproxy(trash.str, PR_CAP_FE);
635 if (!argp[idx].data.prx)
636 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
637 argp[idx].type = ARGT_FE;
638 break;
639
640 case ARGT_BE:
641 if (argp[idx].type != ARGT_STR)
642 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
643 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
644 trash.str[argp[idx].data.str.len] = 0;
645 argp[idx].data.prx = findproxy(trash.str, PR_CAP_BE);
646 if (!argp[idx].data.prx)
647 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
648 argp[idx].type = ARGT_BE;
649 break;
650
651 case ARGT_TAB:
652 if (argp[idx].type != ARGT_STR)
653 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
654 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
655 trash.str[argp[idx].data.str.len] = 0;
656 argp[idx].data.prx = find_stktable(trash.str);
657 if (!argp[idx].data.prx)
658 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
659 argp[idx].type = ARGT_TAB;
660 break;
661
662 case ARGT_SRV:
663 if (argp[idx].type != ARGT_STR)
664 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
665 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
666 trash.str[argp[idx].data.str.len] = 0;
667 sname = strrchr(trash.str, '/');
668 if (sname) {
669 *sname++ = '\0';
670 pname = trash.str;
671 px = findproxy(pname, PR_CAP_BE);
672 if (!px)
673 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
674 }
675 else {
676 sname = trash.str;
677 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100678 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100679 argp[idx].data.srv = findserver(px, sname);
680 if (!argp[idx].data.srv)
681 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
682 argp[idx].type = ARGT_SRV;
683 break;
684
685 case ARGT_IPV4:
686 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
687 trash.str[argp[idx].data.str.len] = 0;
688 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
689 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
690 argp[idx].type = ARGT_IPV4;
691 break;
692
693 case ARGT_MSK4:
694 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
695 trash.str[argp[idx].data.str.len] = 0;
696 if (!str2mask(trash.str, &argp[idx].data.ipv4))
697 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
698 argp[idx].type = ARGT_MSK4;
699 break;
700
701 case ARGT_IPV6:
702 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
703 trash.str[argp[idx].data.str.len] = 0;
704 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
705 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
706 argp[idx].type = ARGT_IPV6;
707 break;
708
709 case ARGT_MSK6:
710 case ARGT_MAP:
711 case ARGT_REG:
712 case ARGT_USR:
713 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100714 break;
715 }
716
717 /* Check for type of argument. */
718 if ((mask & ARGT_MASK) != argp[idx].type) {
719 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
720 arg_type_names[(mask & ARGT_MASK)],
721 arg_type_names[argp[idx].type & ARGT_MASK]);
722 WILL_LJMP(luaL_argerror(L, first + idx, msg));
723 }
724
725 /* Next argument. */
726 mask >>= ARGT_BITS;
727 idx++;
728 }
729}
730
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100731/*
732 * The following functions are used to make correspondance between the the
733 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100734 *
735 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100736 * - hlua_sethlua : create the association between hlua context and lua_state.
737 */
738static inline struct hlua *hlua_gethlua(lua_State *L)
739{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100740 struct hlua **hlua = lua_getextraspace(L);
741 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100742}
743static inline void hlua_sethlua(struct hlua *hlua)
744{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100745 struct hlua **hlua_store = lua_getextraspace(hlua->T);
746 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100747}
748
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100749/* This function is used to send logs. It try to send on screen (stderr)
750 * and on the default syslog server.
751 */
752static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
753{
754 struct tm tm;
755 char *p;
756
757 /* Cleanup the log message. */
758 p = trash.str;
759 for (; *msg != '\0'; msg++, p++) {
760 if (p >= trash.str + trash.size - 1)
761 return;
762 if (isprint(*msg))
763 *p = *msg;
764 else
765 *p = '.';
766 }
767 *p = '\0';
768
769 send_log(px, level, "%s", trash.str);
770 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
771 get_localtime(date.tv_sec, &tm);
772 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
773 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
774 (int)getpid(), trash.str);
775 fflush(stderr);
776 }
777}
778
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100779/* This function just ensure that the yield will be always
780 * returned with a timeout and permit to set some flags
781 */
782__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100783 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100784{
785 struct hlua *hlua = hlua_gethlua(L);
786
787 /* Set the wake timeout. If timeout is required, we set
788 * the expiration time.
789 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100790 hlua->wake_time = tick_first(timeout, hlua->expire);
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100791
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100792 hlua->flags |= flags;
793
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100794 /* Process the yield. */
795 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
796}
797
Willy Tarreau87b09662015-04-03 00:22:06 +0200798/* This function initialises the Lua environment stored in the stream.
799 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100800 * an LUA coroutine. It can not be use to crete the main LUA context.
801 */
802int hlua_ctx_init(struct hlua *lua, struct task *task)
803{
804 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100805 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100806 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100807 lua->T = lua_newthread(gL.T);
808 if (!lua->T) {
809 lua->Tref = LUA_REFNIL;
810 return 0;
811 }
812 hlua_sethlua(lua);
813 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
814 lua->task = task;
815 return 1;
816}
817
Willy Tarreau87b09662015-04-03 00:22:06 +0200818/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100819 * is destroyed. The destroy also the memory context. The struct "lua"
820 * is not freed.
821 */
822void hlua_ctx_destroy(struct hlua *lua)
823{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100824 if (!lua->T)
825 return;
826
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100827 /* Purge all the pending signals. */
828 hlua_com_purge(lua);
829
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100830 /* The thread is garbage collected by Lua. */
831 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
832 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
833}
834
835/* This function is used to restore the Lua context when a coroutine
836 * fails. This function copy the common memory between old coroutine
837 * and the new coroutine. The old coroutine is destroyed, and its
838 * replaced by the new coroutine.
839 * If the flag "keep_msg" is set, the last entry of the old is assumed
840 * as string error message and it is copied in the new stack.
841 */
842static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
843{
844 lua_State *T;
845 int new_ref;
846
847 /* Renew the main LUA stack doesn't have sense. */
848 if (lua == &gL)
849 return 0;
850
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100851 /* New Lua coroutine. */
852 T = lua_newthread(gL.T);
853 if (!T)
854 return 0;
855
856 /* Copy last error message. */
857 if (keep_msg)
858 lua_xmove(lua->T, T, 1);
859
860 /* Copy data between the coroutines. */
861 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
862 lua_xmove(lua->T, T, 1);
863 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
864
865 /* Destroy old data. */
866 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
867
868 /* The thread is garbage collected by Lua. */
869 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
870
871 /* Fill the struct with the new coroutine values. */
872 lua->Mref = new_ref;
873 lua->T = T;
874 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
875
876 /* Set context. */
877 hlua_sethlua(lua);
878
879 return 1;
880}
881
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100882void hlua_hook(lua_State *L, lua_Debug *ar)
883{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100884 struct hlua *hlua = hlua_gethlua(L);
885
886 /* Lua cannot yield when its returning from a function,
887 * so, we can fix the interrupt hook to 1 instruction,
888 * expecting that the function is finnished.
889 */
890 if (lua_gethookmask(L) & LUA_MASKRET) {
891 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
892 return;
893 }
894
895 /* restore the interrupt condition. */
896 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
897
898 /* If we interrupt the Lua processing in yieldable state, we yield.
899 * If the state is not yieldable, trying yield causes an error.
900 */
901 if (lua_isyieldable(L))
902 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
903
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +0100904 /* If we cannot yield, update the clock and check the timeout. */
905 tv_update_date(0, 1);
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100906 if (tick_is_expired(hlua->expire, now_ms)) {
907 lua_pushfstring(L, "execution timeout");
908 WILL_LJMP(lua_error(L));
909 }
910
911 /* Try to interrupt the process at the end of the current
912 * unyieldable function.
913 */
914 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100915}
916
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100917/* This function start or resumes the Lua stack execution. If the flag
918 * "yield_allowed" if no set and the LUA stack execution returns a yield
919 * The function return an error.
920 *
921 * The function can returns 4 values:
922 * - HLUA_E_OK : The execution is terminated without any errors.
923 * - HLUA_E_AGAIN : The execution must continue at the next associated
924 * task wakeup.
925 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
926 * the top of the stack.
927 * - HLUA_E_ERR : An error has occured without error message.
928 *
929 * If an error occured, the stack is renewed and it is ready to run new
930 * LUA code.
931 */
932static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
933{
934 int ret;
935 const char *msg;
936
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100937 HLUA_SET_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100938
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100939 /* If we want to resume the task, then check first the execution timeout.
940 * if it is reached, we can interrupt the Lua processing.
941 */
942 if (tick_is_expired(lua->expire, now_ms))
943 goto timeout_reached;
944
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100945resume_execution:
946
947 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
948 * instructions. it is used for preventing infinite loops.
949 */
950 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
951
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +0100952 /* Remove all flags except the running flags. */
953 lua->flags = HLUA_RUN;
954
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100955 /* Call the function. */
956 ret = lua_resume(lua->T, gL.T, lua->nargs);
957 switch (ret) {
958
959 case LUA_OK:
960 ret = HLUA_E_OK;
961 break;
962
963 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100964 /* Check if the execution timeout is expired. It it is the case, we
965 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100966 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100967 if (tick_is_expired(lua->expire, now_ms)) {
968
969timeout_reached:
970
971 lua_settop(lua->T, 0); /* Empty the stack. */
972 if (!lua_checkstack(lua->T, 1)) {
973 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100974 break;
975 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100976 lua_pushfstring(lua->T, "execution timeout");
977 ret = HLUA_E_ERRMSG;
978 break;
979 }
980 /* Process the forced yield. if the general yield is not allowed or
981 * if no task were associated this the current Lua execution
982 * coroutine, we resume the execution. Else we want to return in the
983 * scheduler and we want to be waked up again, to continue the
984 * current Lua execution. So we schedule our own task.
985 */
986 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100987 if (!yield_allowed || !lua->task)
988 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100989 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100990 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100991 if (!yield_allowed) {
992 lua_settop(lua->T, 0); /* Empty the stack. */
993 if (!lua_checkstack(lua->T, 1)) {
994 ret = HLUA_E_ERR;
995 break;
996 }
997 lua_pushfstring(lua->T, "yield not allowed");
998 ret = HLUA_E_ERRMSG;
999 break;
1000 }
1001 ret = HLUA_E_AGAIN;
1002 break;
1003
1004 case LUA_ERRRUN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001005 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001006 if (!lua_checkstack(lua->T, 1)) {
1007 ret = HLUA_E_ERR;
1008 break;
1009 }
1010 msg = lua_tostring(lua->T, -1);
1011 lua_settop(lua->T, 0); /* Empty the stack. */
1012 lua_pop(lua->T, 1);
1013 if (msg)
1014 lua_pushfstring(lua->T, "runtime error: %s", msg);
1015 else
1016 lua_pushfstring(lua->T, "unknown runtime error");
1017 ret = HLUA_E_ERRMSG;
1018 break;
1019
1020 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001021 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001022 lua_settop(lua->T, 0); /* Empty the stack. */
1023 if (!lua_checkstack(lua->T, 1)) {
1024 ret = HLUA_E_ERR;
1025 break;
1026 }
1027 lua_pushfstring(lua->T, "out of memory error");
1028 ret = HLUA_E_ERRMSG;
1029 break;
1030
1031 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001032 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001033 if (!lua_checkstack(lua->T, 1)) {
1034 ret = HLUA_E_ERR;
1035 break;
1036 }
1037 msg = lua_tostring(lua->T, -1);
1038 lua_settop(lua->T, 0); /* Empty the stack. */
1039 lua_pop(lua->T, 1);
1040 if (msg)
1041 lua_pushfstring(lua->T, "message handler error: %s", msg);
1042 else
1043 lua_pushfstring(lua->T, "message handler error");
1044 ret = HLUA_E_ERRMSG;
1045 break;
1046
1047 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001048 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001049 lua_settop(lua->T, 0); /* Empty the stack. */
1050 if (!lua_checkstack(lua->T, 1)) {
1051 ret = HLUA_E_ERR;
1052 break;
1053 }
1054 lua_pushfstring(lua->T, "unknonwn error");
1055 ret = HLUA_E_ERRMSG;
1056 break;
1057 }
1058
1059 switch (ret) {
1060 case HLUA_E_AGAIN:
1061 break;
1062
1063 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001064 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001065 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001066 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001067 break;
1068
1069 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001070 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001071 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001072 hlua_ctx_renew(lua, 0);
1073 break;
1074
1075 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001076 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001077 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001078 break;
1079 }
1080
1081 return ret;
1082}
1083
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001084/* This function is an LUA binding. It provides a function
1085 * for deleting ACL from a referenced ACL file.
1086 */
1087__LJMP static int hlua_del_acl(lua_State *L)
1088{
1089 const char *name;
1090 const char *key;
1091 struct pat_ref *ref;
1092
1093 MAY_LJMP(check_args(L, 2, "del_acl"));
1094
1095 name = MAY_LJMP(luaL_checkstring(L, 1));
1096 key = MAY_LJMP(luaL_checkstring(L, 2));
1097
1098 ref = pat_ref_lookup(name);
1099 if (!ref)
1100 WILL_LJMP(luaL_error(L, "'del_acl': unkown acl file '%s'", name));
1101
1102 pat_ref_delete(ref, key);
1103 return 0;
1104}
1105
1106/* This function is an LUA binding. It provides a function
1107 * for deleting map entry from a referenced map file.
1108 */
1109static int hlua_del_map(lua_State *L)
1110{
1111 const char *name;
1112 const char *key;
1113 struct pat_ref *ref;
1114
1115 MAY_LJMP(check_args(L, 2, "del_map"));
1116
1117 name = MAY_LJMP(luaL_checkstring(L, 1));
1118 key = MAY_LJMP(luaL_checkstring(L, 2));
1119
1120 ref = pat_ref_lookup(name);
1121 if (!ref)
1122 WILL_LJMP(luaL_error(L, "'del_map': unkown acl file '%s'", name));
1123
1124 pat_ref_delete(ref, key);
1125 return 0;
1126}
1127
1128/* This function is an LUA binding. It provides a function
1129 * for adding ACL pattern from a referenced ACL file.
1130 */
1131static int hlua_add_acl(lua_State *L)
1132{
1133 const char *name;
1134 const char *key;
1135 struct pat_ref *ref;
1136
1137 MAY_LJMP(check_args(L, 2, "add_acl"));
1138
1139 name = MAY_LJMP(luaL_checkstring(L, 1));
1140 key = MAY_LJMP(luaL_checkstring(L, 2));
1141
1142 ref = pat_ref_lookup(name);
1143 if (!ref)
1144 WILL_LJMP(luaL_error(L, "'add_acl': unkown acl file '%s'", name));
1145
1146 if (pat_ref_find_elt(ref, key) == NULL)
1147 pat_ref_add(ref, key, NULL, NULL);
1148 return 0;
1149}
1150
1151/* This function is an LUA binding. It provides a function
1152 * for setting map pattern and sample from a referenced map
1153 * file.
1154 */
1155static int hlua_set_map(lua_State *L)
1156{
1157 const char *name;
1158 const char *key;
1159 const char *value;
1160 struct pat_ref *ref;
1161
1162 MAY_LJMP(check_args(L, 3, "set_map"));
1163
1164 name = MAY_LJMP(luaL_checkstring(L, 1));
1165 key = MAY_LJMP(luaL_checkstring(L, 2));
1166 value = MAY_LJMP(luaL_checkstring(L, 3));
1167
1168 ref = pat_ref_lookup(name);
1169 if (!ref)
1170 WILL_LJMP(luaL_error(L, "'set_map': unkown map file '%s'", name));
1171
1172 if (pat_ref_find_elt(ref, key) != NULL)
1173 pat_ref_set(ref, key, value, NULL);
1174 else
1175 pat_ref_add(ref, key, value, NULL);
1176 return 0;
1177}
1178
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001179/* A class is a lot of memory that contain data. This data can be a table,
1180 * an integer or user data. This data is associated with a metatable. This
1181 * metatable have an original version registred in the global context with
1182 * the name of the object (_G[<name>] = <metable> ).
1183 *
1184 * A metable is a table that modify the standard behavior of a standard
1185 * access to the associated data. The entries of this new metatable are
1186 * defined as is:
1187 *
1188 * http://lua-users.org/wiki/MetatableEvents
1189 *
1190 * __index
1191 *
1192 * we access an absent field in a table, the result is nil. This is
1193 * true, but it is not the whole truth. Actually, such access triggers
1194 * the interpreter to look for an __index metamethod: If there is no
1195 * such method, as usually happens, then the access results in nil;
1196 * otherwise, the metamethod will provide the result.
1197 *
1198 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1199 * the key does not appear in the table, but the metatable has an __index
1200 * property:
1201 *
1202 * - if the value is a function, the function is called, passing in the
1203 * table and the key; the return value of that function is returned as
1204 * the result.
1205 *
1206 * - if the value is another table, the value of the key in that table is
1207 * asked for and returned (and if it doesn't exist in that table, but that
1208 * table's metatable has an __index property, then it continues on up)
1209 *
1210 * - Use "rawget(myTable,key)" to skip this metamethod.
1211 *
1212 * http://www.lua.org/pil/13.4.1.html
1213 *
1214 * __newindex
1215 *
1216 * Like __index, but control property assignment.
1217 *
1218 * __mode - Control weak references. A string value with one or both
1219 * of the characters 'k' and 'v' which specifies that the the
1220 * keys and/or values in the table are weak references.
1221 *
1222 * __call - Treat a table like a function. When a table is followed by
1223 * parenthesis such as "myTable( 'foo' )" and the metatable has
1224 * a __call key pointing to a function, that function is invoked
1225 * (passing any specified arguments) and the return value is
1226 * returned.
1227 *
1228 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1229 * called, if the metatable for myTable has a __metatable
1230 * key, the value of that key is returned instead of the
1231 * actual metatable.
1232 *
1233 * __tostring - Control string representation. When the builtin
1234 * "tostring( myTable )" function is called, if the metatable
1235 * for myTable has a __tostring property set to a function,
1236 * that function is invoked (passing myTable to it) and the
1237 * return value is used as the string representation.
1238 *
1239 * __len - Control table length. When the table length is requested using
1240 * the length operator ( '#' ), if the metatable for myTable has
1241 * a __len key pointing to a function, that function is invoked
1242 * (passing myTable to it) and the return value used as the value
1243 * of "#myTable".
1244 *
1245 * __gc - Userdata finalizer code. When userdata is set to be garbage
1246 * collected, if the metatable has a __gc field pointing to a
1247 * function, that function is first invoked, passing the userdata
1248 * to it. The __gc metamethod is not called for tables.
1249 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1250 *
1251 * Special metamethods for redefining standard operators:
1252 * http://www.lua.org/pil/13.1.html
1253 *
1254 * __add "+"
1255 * __sub "-"
1256 * __mul "*"
1257 * __div "/"
1258 * __unm "!"
1259 * __pow "^"
1260 * __concat ".."
1261 *
1262 * Special methods for redfining standar relations
1263 * http://www.lua.org/pil/13.2.html
1264 *
1265 * __eq "=="
1266 * __lt "<"
1267 * __le "<="
1268 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001269
1270/*
1271 *
1272 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001273 * Class Map
1274 *
1275 *
1276 */
1277
1278/* Returns a struct hlua_map if the stack entry "ud" is
1279 * a class session, otherwise it throws an error.
1280 */
1281__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1282{
1283 return (struct map_descriptor *)MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
1284}
1285
1286/* This function is the map constructor. It don't need
1287 * the class Map object. It creates and return a new Map
1288 * object. It must be called only during "body" or "init"
1289 * context because it process some filesystem accesses.
1290 */
1291__LJMP static int hlua_map_new(struct lua_State *L)
1292{
1293 const char *fn;
1294 int match = PAT_MATCH_STR;
1295 struct sample_conv conv;
1296 const char *file = "";
1297 int line = 0;
1298 lua_Debug ar;
1299 char *err = NULL;
1300 struct arg args[2];
1301
1302 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1303 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1304
1305 fn = MAY_LJMP(luaL_checkstring(L, 1));
1306
1307 if (lua_gettop(L) >= 2) {
1308 match = MAY_LJMP(luaL_checkinteger(L, 2));
1309 if (match < 0 || match >= PAT_MATCH_NUM)
1310 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1311 }
1312
1313 /* Get Lua filename and line number. */
1314 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1315 lua_getinfo(L, "Sl", &ar); /* get info about it */
1316 if (ar.currentline > 0) { /* is there info? */
1317 file = ar.short_src;
1318 line = ar.currentline;
1319 }
1320 }
1321
1322 /* fill fake sample_conv struct. */
1323 conv.kw = ""; /* unused. */
1324 conv.process = NULL; /* unused. */
1325 conv.arg_mask = 0; /* unused. */
1326 conv.val_args = NULL; /* unused. */
1327 conv.out_type = SMP_T_STR;
1328 conv.private = (void *)(long)match;
1329 switch (match) {
1330 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1331 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1332 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1333 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1334 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1335 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1336 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
1337 case PAT_MATCH_INT: conv.in_type = SMP_T_UINT; break;
1338 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1339 default:
1340 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1341 }
1342
1343 /* fill fake args. */
1344 args[0].type = ARGT_STR;
1345 args[0].data.str.str = (char *)fn;
1346 args[1].type = ARGT_STOP;
1347
1348 /* load the map. */
1349 if (!sample_load_map(args, &conv, file, line, &err)) {
1350 /* error case: we cant use luaL_error because we must
1351 * free the err variable.
1352 */
1353 luaL_where(L, 1);
1354 lua_pushfstring(L, "'new': %s.", err);
1355 lua_concat(L, 2);
1356 free(err);
1357 WILL_LJMP(lua_error(L));
1358 }
1359
1360 /* create the lua object. */
1361 lua_newtable(L);
1362 lua_pushlightuserdata(L, args[0].data.map);
1363 lua_rawseti(L, -2, 0);
1364
1365 /* Pop a class Map metatable and affect it to the userdata. */
1366 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1367 lua_setmetatable(L, -2);
1368
1369
1370 return 1;
1371}
1372
1373__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1374{
1375 struct map_descriptor *desc;
1376 struct pattern *pat;
1377 struct sample smp;
1378
1379 MAY_LJMP(check_args(L, 2, "lookup"));
1380 desc = MAY_LJMP(hlua_checkmap(L, 1));
1381 if (desc->pat.expect_type == SMP_T_UINT) {
1382 smp.type = SMP_T_UINT;
1383 smp.data.uint = MAY_LJMP(luaL_checkinteger(L, 2));
1384 }
1385 else {
1386 smp.type = SMP_T_STR;
1387 smp.flags = SMP_F_CONST;
1388 smp.data.str.str = (char *)MAY_LJMP(luaL_checklstring(L, 2, (size_t *)&smp.data.str.len));
1389 }
1390
1391 pat = pattern_exec_match(&desc->pat, &smp, 1);
1392 if (!pat || !pat->smp) {
1393 if (str)
1394 lua_pushstring(L, "");
1395 else
1396 lua_pushnil(L);
1397 return 1;
1398 }
1399
1400 /* The Lua pattern must return a string, so we can't check the returned type */
1401 lua_pushlstring(L, pat->smp->data.str.str, pat->smp->data.str.len);
1402 return 1;
1403}
1404
1405__LJMP static int hlua_map_lookup(struct lua_State *L)
1406{
1407 return _hlua_map_lookup(L, 0);
1408}
1409
1410__LJMP static int hlua_map_slookup(struct lua_State *L)
1411{
1412 return _hlua_map_lookup(L, 1);
1413}
1414
1415/*
1416 *
1417 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001418 * Class Socket
1419 *
1420 *
1421 */
1422
1423__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1424{
1425 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1426}
1427
1428/* This function is the handler called for each I/O on the established
1429 * connection. It is used for notify space avalaible to send or data
1430 * received.
1431 */
1432static void hlua_socket_handler(struct stream_interface *si)
1433{
1434 struct appctx *appctx = objt_appctx(si->end);
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001435 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001436
Willy Tarreau87b09662015-04-03 00:22:06 +02001437 /* Wakeup the main stream if the client connection is closed. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001438 if (!c || channel_output_closed(si_ic(si)) || channel_input_closed(si_oc(si))) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001439 if (appctx->ctx.hlua.socket) {
1440 appctx->ctx.hlua.socket->s = NULL;
1441 appctx->ctx.hlua.socket = NULL;
1442 }
1443 si_shutw(si);
1444 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001445 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001446 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1447 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1448 return;
1449 }
1450
1451 if (!(c->flags & CO_FL_CONNECTED))
1452 return;
1453
1454 /* This function is called after the connect. */
1455 appctx->ctx.hlua.connected = 1;
1456
1457 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001458 if (channel_may_recv(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001459 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1460
1461 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001462 if (channel_is_empty(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001463 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1464}
1465
Willy Tarreau87b09662015-04-03 00:22:06 +02001466/* This function is called when the "struct stream" is destroyed.
1467 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001468 * Wake all the pending signals.
1469 */
1470static void hlua_socket_release(struct stream_interface *si)
1471{
1472 struct appctx *appctx = objt_appctx(si->end);
1473
1474 /* Remove my link in the original object. */
1475 if (appctx->ctx.hlua.socket)
1476 appctx->ctx.hlua.socket->s = NULL;
1477
1478 /* Wake all the task waiting for me. */
1479 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1480 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1481}
1482
1483/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001484 * uses this object. If the stream does not exists, just quit.
1485 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001486 * pending signal can rest in the read and write lists. destroy
1487 * it.
1488 */
1489__LJMP static int hlua_socket_gc(lua_State *L)
1490{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001491 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001492 struct appctx *appctx;
1493
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001494 MAY_LJMP(check_args(L, 1, "__gc"));
1495
1496 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001497 if (!socket->s)
1498 return 0;
1499
Willy Tarreau87b09662015-04-03 00:22:06 +02001500 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001501 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaue7dff022015-04-03 01:14:29 +02001502 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001503 socket->s = NULL;
1504 appctx->ctx.hlua.socket = NULL;
1505
1506 return 0;
1507}
1508
1509/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001510 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001511 */
1512__LJMP static int hlua_socket_close(lua_State *L)
1513{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001514 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001515 struct appctx *appctx;
1516
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001517 MAY_LJMP(check_args(L, 1, "close"));
1518
1519 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001520 if (!socket->s)
1521 return 0;
1522
Willy Tarreau87b09662015-04-03 00:22:06 +02001523 /* Close the stream and remove the associated stop task. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02001524 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001525 appctx = objt_appctx(socket->s->si[0].end);
1526 appctx->ctx.hlua.socket = NULL;
1527 socket->s = NULL;
1528
1529 return 0;
1530}
1531
1532/* This Lua function assumes that the stack contain three parameters.
1533 * 1 - USERDATA containing a struct socket
1534 * 2 - INTEGER with values of the macro defined below
1535 * If the integer is -1, we must read at most one line.
1536 * If the integer is -2, we ust read all the data until the
1537 * end of the stream.
1538 * If the integer is positive value, we must read a number of
1539 * bytes corresponding to this value.
1540 */
1541#define HLSR_READ_LINE (-1)
1542#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001543__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001544{
1545 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1546 int wanted = lua_tointeger(L, 2);
1547 struct hlua *hlua = hlua_gethlua(L);
1548 struct appctx *appctx;
1549 int len;
1550 int nblk;
1551 char *blk1;
1552 int len1;
1553 char *blk2;
1554 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001555 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001556 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001557
1558 /* Check if this lua stack is schedulable. */
1559 if (!hlua || !hlua->task)
1560 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1561 "'frontend', 'backend' or 'task'"));
1562
1563 /* check for connection closed. If some data where read, return it. */
1564 if (!socket->s)
1565 goto connection_closed;
1566
Willy Tarreau94aa6172015-03-13 14:19:06 +01001567 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001568 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001569 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001570 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001571 if (nblk < 0) /* Connection close. */
1572 goto connection_closed;
1573 if (nblk == 0) /* No data avalaible. */
1574 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001575
1576 /* remove final \r\n. */
1577 if (nblk == 1) {
1578 if (blk1[len1-1] == '\n') {
1579 len1--;
1580 skip_at_end++;
1581 if (blk1[len1-1] == '\r') {
1582 len1--;
1583 skip_at_end++;
1584 }
1585 }
1586 }
1587 else {
1588 if (blk2[len2-1] == '\n') {
1589 len2--;
1590 skip_at_end++;
1591 if (blk2[len2-1] == '\r') {
1592 len2--;
1593 skip_at_end++;
1594 }
1595 }
1596 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001597 }
1598
1599 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001600 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001601 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001602 if (nblk < 0) /* Connection close. */
1603 goto connection_closed;
1604 if (nblk == 0) /* No data avalaible. */
1605 goto connection_empty;
1606 }
1607
1608 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001609 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001610 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001611 if (nblk < 0) /* Connection close. */
1612 goto connection_closed;
1613 if (nblk == 0) /* No data avalaible. */
1614 goto connection_empty;
1615
1616 if (len1 > wanted) {
1617 nblk = 1;
1618 len1 = wanted;
1619 } if (nblk == 2 && len1 + len2 > wanted)
1620 len2 = wanted - len1;
1621 }
1622
1623 len = len1;
1624
1625 luaL_addlstring(&socket->b, blk1, len1);
1626 if (nblk == 2) {
1627 len += len2;
1628 luaL_addlstring(&socket->b, blk2, len2);
1629 }
1630
1631 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001632 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001633
1634 /* Don't wait anything. */
1635 si_update(&socket->s->si[0]);
1636
1637 /* If the pattern reclaim to read all the data
1638 * in the connection, got out.
1639 */
1640 if (wanted == HLSR_READ_ALL)
1641 goto connection_empty;
1642 else if (wanted >= 0 && len < wanted)
1643 goto connection_empty;
1644
1645 /* Return result. */
1646 luaL_pushresult(&socket->b);
1647 return 1;
1648
1649connection_closed:
1650
1651 /* If the buffer containds data. */
1652 if (socket->b.n > 0) {
1653 luaL_pushresult(&socket->b);
1654 return 1;
1655 }
1656 lua_pushnil(L);
1657 lua_pushstring(L, "connection closed.");
1658 return 2;
1659
1660connection_empty:
1661
1662 appctx = objt_appctx(socket->s->si[0].end);
1663 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1664 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001665 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001666 return 0;
1667}
1668
1669/* This Lus function gets two parameters. The first one can be string
1670 * or a number. If the string is "*l", the user require one line. If
1671 * the string is "*a", the user require all the content of the stream.
1672 * If the value is a number, the user require a number of bytes equal
1673 * to the value. The default value is "*l" (a line).
1674 *
1675 * This paraeter with a variable type is converted in integer. This
1676 * integer takes this values:
1677 * -1 : read a line
1678 * -2 : read all the stream
1679 * >0 : amount if bytes.
1680 *
1681 * The second parameter is optinal. It contains a string that must be
1682 * concatenated with the read data.
1683 */
1684__LJMP static int hlua_socket_receive(struct lua_State *L)
1685{
1686 int wanted = HLSR_READ_LINE;
1687 const char *pattern;
1688 int type;
1689 char *error;
1690 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001691 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001692
1693 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1694 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1695
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001696 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001697
1698 /* check for pattern. */
1699 if (lua_gettop(L) >= 2) {
1700 type = lua_type(L, 2);
1701 if (type == LUA_TSTRING) {
1702 pattern = lua_tostring(L, 2);
1703 if (strcmp(pattern, "*a") == 0)
1704 wanted = HLSR_READ_ALL;
1705 else if (strcmp(pattern, "*l") == 0)
1706 wanted = HLSR_READ_LINE;
1707 else {
1708 wanted = strtoll(pattern, &error, 10);
1709 if (*error != '\0')
1710 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1711 }
1712 }
1713 else if (type == LUA_TNUMBER) {
1714 wanted = lua_tointeger(L, 2);
1715 if (wanted < 0)
1716 WILL_LJMP(luaL_error(L, "Unsupported size."));
1717 }
1718 }
1719
1720 /* Set pattern. */
1721 lua_pushinteger(L, wanted);
1722 lua_replace(L, 2);
1723
1724 /* init bufffer, and fiil it wih prefix. */
1725 luaL_buffinit(L, &socket->b);
1726
1727 /* Check prefix. */
1728 if (lua_gettop(L) >= 3) {
1729 if (lua_type(L, 3) != LUA_TSTRING)
1730 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1731 pattern = lua_tolstring(L, 3, &len);
1732 luaL_addlstring(&socket->b, pattern, len);
1733 }
1734
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001735 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001736}
1737
1738/* Write the Lua input string in the output buffer.
1739 * This fucntion returns a yield if no space are available.
1740 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001741static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001742{
1743 struct hlua_socket *socket;
1744 struct hlua *hlua = hlua_gethlua(L);
1745 struct appctx *appctx;
1746 size_t buf_len;
1747 const char *buf;
1748 int len;
1749 int send_len;
1750 int sent;
1751
1752 /* Check if this lua stack is schedulable. */
1753 if (!hlua || !hlua->task)
1754 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1755 "'frontend', 'backend' or 'task'"));
1756
1757 /* Get object */
1758 socket = MAY_LJMP(hlua_checksocket(L, 1));
1759 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001760 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001761
1762 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001763 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001764 lua_pushinteger(L, -1);
1765 return 1;
1766 }
1767
1768 /* Update the input buffer data. */
1769 buf += sent;
1770 send_len = buf_len - sent;
1771
1772 /* All the data are sent. */
1773 if (sent >= buf_len)
1774 return 1; /* Implicitly return the length sent. */
1775
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001776 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1777 * the request buffer if its not required.
1778 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001779 if (socket->s->req.buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02001780 if (!stream_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001781 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001782 goto hlua_socket_write_yield_return;
1783 }
1784 }
1785
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001786 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001787 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001788 if (len <= 0)
1789 goto hlua_socket_write_yield_return;
1790
1791 /* send data */
1792 if (len < send_len)
1793 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001794 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001795
1796 /* "Not enough space" (-1), "Buffer too little to contain
1797 * the data" (-2) are not expected because the available length
1798 * is tested.
1799 * Other unknown error are also not expected.
1800 */
1801 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001802 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001803 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001804
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001805 MAY_LJMP(hlua_socket_close(L));
1806 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001807 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001808 return 1;
1809 }
1810
1811 /* update buffers. */
1812 si_update(&socket->s->si[0]);
Willy Tarreau94aa6172015-03-13 14:19:06 +01001813 socket->s->req.rex = TICK_ETERNITY;
1814 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001815
1816 /* Update length sent. */
1817 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001818 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001819
1820 /* All the data buffer is sent ? */
1821 if (sent + len >= buf_len)
1822 return 1;
1823
1824hlua_socket_write_yield_return:
1825 appctx = objt_appctx(socket->s->si[0].end);
1826 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1827 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001828 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001829 return 0;
1830}
1831
1832/* This function initiate the send of data. It just check the input
1833 * parameters and push an integer in the Lua stack that contain the
1834 * amount of data writed in the buffer. This is used by the function
1835 * "hlua_socket_write_yield" that can yield.
1836 *
1837 * The Lua function gets between 3 and 4 parameters. The first one is
1838 * the associated object. The second is a string buffer. The third is
1839 * a facultative integer that represents where is the buffer position
1840 * of the start of the data that can send. The first byte is the
1841 * position "1". The default value is "1". The fourth argument is a
1842 * facultative integer that represents where is the buffer position
1843 * of the end of the data that can send. The default is the last byte.
1844 */
1845static int hlua_socket_send(struct lua_State *L)
1846{
1847 int i;
1848 int j;
1849 const char *buf;
1850 size_t buf_len;
1851
1852 /* Check number of arguments. */
1853 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1854 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1855
1856 /* Get the string. */
1857 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1858
1859 /* Get and check j. */
1860 if (lua_gettop(L) == 4) {
1861 j = MAY_LJMP(luaL_checkinteger(L, 4));
1862 if (j < 0)
1863 j = buf_len + j + 1;
1864 if (j > buf_len)
1865 j = buf_len + 1;
1866 lua_pop(L, 1);
1867 }
1868 else
1869 j = buf_len;
1870
1871 /* Get and check i. */
1872 if (lua_gettop(L) == 3) {
1873 i = MAY_LJMP(luaL_checkinteger(L, 3));
1874 if (i < 0)
1875 i = buf_len + i + 1;
1876 if (i > buf_len)
1877 i = buf_len + 1;
1878 lua_pop(L, 1);
1879 } else
1880 i = 1;
1881
1882 /* Check bth i and j. */
1883 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001884 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001885 return 1;
1886 }
1887 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001888 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001889 return 1;
1890 }
1891 if (i == 0)
1892 i = 1;
1893 if (j == 0)
1894 j = 1;
1895
1896 /* Pop the string. */
1897 lua_pop(L, 1);
1898
1899 /* Update the buffer length. */
1900 buf += i - 1;
1901 buf_len = j - i + 1;
1902 lua_pushlstring(L, buf, buf_len);
1903
1904 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001905 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001906
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001907 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001908}
1909
1910#define SOCKET_INFO_EXPANDED_FORM "[0000:0000:0000:0000:0000:0000:0000:0000]:12345"
1911static char _socket_info_expanded_form[] = SOCKET_INFO_EXPANDED_FORM;
1912#define SOCKET_INFO_MAX_LEN (sizeof(_socket_info_expanded_form))
1913__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
1914{
1915 static char buffer[SOCKET_INFO_MAX_LEN];
1916 int ret;
1917 int len;
1918 char *p;
1919
1920 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
1921 if (ret <= 0) {
1922 lua_pushnil(L);
1923 return 1;
1924 }
1925
1926 if (ret == AF_UNIX) {
1927 lua_pushstring(L, buffer+1);
1928 return 1;
1929 }
1930 else if (ret == AF_INET6) {
1931 buffer[0] = '[';
1932 len = strlen(buffer);
1933 buffer[len] = ']';
1934 len++;
1935 buffer[len] = ':';
1936 len++;
1937 p = buffer;
1938 }
1939 else if (ret == AF_INET) {
1940 p = buffer + 1;
1941 len = strlen(p);
1942 p[len] = ':';
1943 len++;
1944 }
1945 else {
1946 lua_pushnil(L);
1947 return 1;
1948 }
1949
1950 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
1951 lua_pushnil(L);
1952 return 1;
1953 }
1954
1955 lua_pushstring(L, p);
1956 return 1;
1957}
1958
1959/* Returns information about the peer of the connection. */
1960__LJMP static int hlua_socket_getpeername(struct lua_State *L)
1961{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001962 struct hlua_socket *socket;
1963 struct connection *conn;
1964
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001965 MAY_LJMP(check_args(L, 1, "getpeername"));
1966
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001967 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001968
1969 /* Check if the tcp object is avalaible. */
1970 if (!socket->s) {
1971 lua_pushnil(L);
1972 return 1;
1973 }
1974
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001975 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001976 if (!conn) {
1977 lua_pushnil(L);
1978 return 1;
1979 }
1980
1981 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
1982 unsigned int salen = sizeof(conn->addr.to);
1983 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
1984 lua_pushnil(L);
1985 return 1;
1986 }
1987 conn->flags |= CO_FL_ADDR_TO_SET;
1988 }
1989
1990 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
1991}
1992
1993/* Returns information about my connection side. */
1994static int hlua_socket_getsockname(struct lua_State *L)
1995{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001996 struct hlua_socket *socket;
1997 struct connection *conn;
1998
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001999 MAY_LJMP(check_args(L, 1, "getsockname"));
2000
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002001 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002002
2003 /* Check if the tcp object is avalaible. */
2004 if (!socket->s) {
2005 lua_pushnil(L);
2006 return 1;
2007 }
2008
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002009 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002010 if (!conn) {
2011 lua_pushnil(L);
2012 return 1;
2013 }
2014
2015 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
2016 unsigned int salen = sizeof(conn->addr.from);
2017 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
2018 lua_pushnil(L);
2019 return 1;
2020 }
2021 conn->flags |= CO_FL_ADDR_FROM_SET;
2022 }
2023
2024 return hlua_socket_info(L, &conn->addr.from);
2025}
2026
2027/* This struct define the applet. */
2028static struct si_applet update_applet = {
2029 .obj_type = OBJ_TYPE_APPLET,
2030 .name = "<LUA_TCP>",
2031 .fct = hlua_socket_handler,
2032 .release = hlua_socket_release,
2033};
2034
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002035__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002036{
2037 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2038 struct hlua *hlua = hlua_gethlua(L);
2039 struct appctx *appctx;
2040
2041 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002042 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002043 lua_pushnil(L);
2044 lua_pushstring(L, "Can't connect");
2045 return 2;
2046 }
2047
2048 appctx = objt_appctx(socket->s->si[0].end);
2049
2050 /* Check for connection established. */
2051 if (appctx->ctx.hlua.connected) {
2052 lua_pushinteger(L, 1);
2053 return 1;
2054 }
2055
2056 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2057 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002058 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002059 return 0;
2060}
2061
2062/* This function fail or initite the connection. */
2063__LJMP static int hlua_socket_connect(struct lua_State *L)
2064{
2065 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002066 int port;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002067 const char *ip;
2068 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002069 struct hlua *hlua;
2070 struct appctx *appctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002071
2072 MAY_LJMP(check_args(L, 3, "connect"));
2073
2074 /* Get args. */
2075 socket = MAY_LJMP(hlua_checksocket(L, 1));
2076 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002077 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002078
Willy Tarreau350f4872014-11-28 14:42:25 +01002079 conn = si_alloc_conn(&socket->s->si[1], 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002080 if (!conn)
2081 WILL_LJMP(luaL_error(L, "connect: internal error"));
2082
2083 /* Parse ip address. */
2084 conn->addr.to.ss_family = AF_UNSPEC;
2085 if (!str2ip2(ip, &conn->addr.to, 0))
2086 WILL_LJMP(luaL_error(L, "connect: cannot parse ip address '%s'", ip));
2087
2088 /* Set port. */
2089 if (conn->addr.to.ss_family == AF_INET)
2090 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2091 else if (conn->addr.to.ss_family == AF_INET6)
2092 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2093
2094 /* it is important not to call the wakeup function directly but to
2095 * pass through task_wakeup(), because this one knows how to apply
2096 * priorities to tasks.
2097 */
2098 task_wakeup(socket->s->task, TASK_WOKEN_INIT);
2099
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002100 hlua = hlua_gethlua(L);
2101 appctx = objt_appctx(socket->s->si[0].end);
2102 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2103 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002104 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002105
2106 return 0;
2107}
2108
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002109#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002110__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2111{
2112 struct hlua_socket *socket;
2113
2114 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2115 socket = MAY_LJMP(hlua_checksocket(L, 1));
2116 socket->s->target = &socket_ssl.obj_type;
2117 return MAY_LJMP(hlua_socket_connect(L));
2118}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002119#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002120
2121__LJMP static int hlua_socket_setoption(struct lua_State *L)
2122{
2123 return 0;
2124}
2125
2126__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2127{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002128 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002129 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002130
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002131 MAY_LJMP(check_args(L, 2, "settimeout"));
2132
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002133 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002134 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002135
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002136 socket->s->req.rto = tmout;
2137 socket->s->req.wto = tmout;
2138 socket->s->res.rto = tmout;
2139 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002140
2141 return 0;
2142}
2143
2144__LJMP static int hlua_socket_new(lua_State *L)
2145{
2146 struct hlua_socket *socket;
2147 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002148 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002149 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002150 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002151
2152 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002153 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002154 hlua_pusherror(L, "socket: full stack");
2155 goto out_fail_conf;
2156 }
2157
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002158 /* Create the object: obj[0] = userdata. */
2159 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002160 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002161 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002162 memset(socket, 0, sizeof(*socket));
2163
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002164 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002165 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002166 hlua_pusherror(L, "socket: uninitialized pools.");
2167 goto out_fail_conf;
2168 }
2169
Willy Tarreau87b09662015-04-03 00:22:06 +02002170 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002171 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2172 lua_setmetatable(L, -2);
2173
Willy Tarreaud420a972015-04-06 00:39:18 +02002174 /* Create the applet context */
2175 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002176 if (!appctx) {
2177 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002178 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002179 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002180
Willy Tarreaud420a972015-04-06 00:39:18 +02002181 appctx->ctx.hlua.socket = socket;
2182 appctx->ctx.hlua.connected = 0;
2183 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2184 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002185
Willy Tarreaud420a972015-04-06 00:39:18 +02002186 /* Now create a session, task and stream for this applet */
2187 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2188 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002189 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002190 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002191 }
2192
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002193 task = task_new();
2194 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002195 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002196 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002197 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002198 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002199
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002200 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002201 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002202 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002203 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002204 }
2205
Willy Tarreaud420a972015-04-06 00:39:18 +02002206 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002207 socket->s = strm;
2208 strm->hlua.T = NULL;
2209 strm->hlua.Tref = LUA_REFNIL;
2210 strm->hlua.Mref = LUA_REFNIL;
2211 strm->hlua.nargs = 0;
2212 strm->hlua.flags = 0;
2213 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002214
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002215 /* Configure "right" stream interface. this "si" is used to connect
2216 * and retrieve data from the server. The connection is initialized
2217 * with the "struct server".
2218 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002219 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002220
2221 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002222 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2223 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002224
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002225 /* Update statistics counters. */
2226 socket_proxy.feconn++; /* beconn will be increased later */
2227 jobs++;
2228 totalconn++;
2229
2230 /* Return yield waiting for connection. */
2231 return 1;
2232
Willy Tarreaud420a972015-04-06 00:39:18 +02002233 out_fail_stream:
2234 task_free(task);
2235 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002236 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002237 out_fail_sess:
2238 appctx_free(appctx);
2239 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002240 WILL_LJMP(lua_error(L));
2241 return 0;
2242}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002243
2244/*
2245 *
2246 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002247 * Class Channel
2248 *
2249 *
2250 */
2251
2252/* Returns the struct hlua_channel join to the class channel in the
2253 * stack entry "ud" or throws an argument error.
2254 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002255__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002256{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002257 return (struct channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002258}
2259
Willy Tarreau47860ed2015-03-10 14:07:50 +01002260/* Pushes the channel onto the top of the stack. If the stask does not have a
2261 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002262 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002263static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002264{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002265 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002266 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002267 return 0;
2268
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002269 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002270 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002271 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002272
2273 /* Pop a class sesison metatable and affect it to the userdata. */
2274 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2275 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002276 return 1;
2277}
2278
2279/* Duplicate all the data present in the input channel and put it
2280 * in a string LUA variables. Returns -1 and push a nil value in
2281 * the stack if the channel is closed and all the data are consumed,
2282 * returns 0 if no data are available, otherwise it returns the length
2283 * of the builded string.
2284 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002285static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002286{
2287 char *blk1;
2288 char *blk2;
2289 int len1;
2290 int len2;
2291 int ret;
2292 luaL_Buffer b;
2293
Willy Tarreau47860ed2015-03-10 14:07:50 +01002294 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002295 if (unlikely(ret == 0))
2296 return 0;
2297
2298 if (unlikely(ret < 0)) {
2299 lua_pushnil(L);
2300 return -1;
2301 }
2302
2303 luaL_buffinit(L, &b);
2304 luaL_addlstring(&b, blk1, len1);
2305 if (unlikely(ret == 2))
2306 luaL_addlstring(&b, blk2, len2);
2307 luaL_pushresult(&b);
2308
2309 if (unlikely(ret == 2))
2310 return len1 + len2;
2311 return len1;
2312}
2313
2314/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2315 * a yield. This function keep the data in the buffer.
2316 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002317__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002318{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002319 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002320
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002321 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2322
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002323 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002324 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002325 return 1;
2326}
2327
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002328/* Check arguments for the function "hlua_channel_dup_yield". */
2329__LJMP static int hlua_channel_dup(lua_State *L)
2330{
2331 MAY_LJMP(check_args(L, 1, "dup"));
2332 MAY_LJMP(hlua_checkchannel(L, 1));
2333 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2334}
2335
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002336/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2337 * a yield. This function consumes the data in the buffer. It returns
2338 * a string containing the data or a nil pointer if no data are available
2339 * and the channel is closed.
2340 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002341__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002342{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002343 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002344 int ret;
2345
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002346 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002347
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002348 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002349 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002350 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002351
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002352 if (unlikely(ret == -1))
2353 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002354
Willy Tarreau47860ed2015-03-10 14:07:50 +01002355 chn->buf->i -= ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002356 return 1;
2357}
2358
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002359/* Check arguments for the fucntion "hlua_channel_get_yield". */
2360__LJMP static int hlua_channel_get(lua_State *L)
2361{
2362 MAY_LJMP(check_args(L, 1, "get"));
2363 MAY_LJMP(hlua_checkchannel(L, 1));
2364 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2365}
2366
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002367/* This functions consumes and returns one line. If the channel is closed,
2368 * and the last data does not contains a final '\n', the data are returned
2369 * without the final '\n'. When no more data are avalaible, it returns nil
2370 * value.
2371 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002372__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002373{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002374 char *blk1;
2375 char *blk2;
2376 int len1;
2377 int len2;
2378 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002379 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002380 int ret;
2381 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002382
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002383 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2384
Willy Tarreau47860ed2015-03-10 14:07:50 +01002385 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002386 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002387 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002388
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002389 if (ret == -1) {
2390 lua_pushnil(L);
2391 return 1;
2392 }
2393
2394 luaL_buffinit(L, &b);
2395 luaL_addlstring(&b, blk1, len1);
2396 len = len1;
2397 if (unlikely(ret == 2)) {
2398 luaL_addlstring(&b, blk2, len2);
2399 len += len2;
2400 }
2401 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002402 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002403 return 1;
2404}
2405
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002406/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2407__LJMP static int hlua_channel_getline(lua_State *L)
2408{
2409 MAY_LJMP(check_args(L, 1, "getline"));
2410 MAY_LJMP(hlua_checkchannel(L, 1));
2411 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2412}
2413
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002414/* This function takes a string as input, and append it at the
2415 * input side of channel. If the data is too big, but a space
2416 * is probably available after sending some data, the function
2417 * yield. If the data is bigger than the buffer, or if the
2418 * channel is closed, it returns -1. otherwise, it returns the
2419 * amount of data writed.
2420 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002421__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002422{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002423 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002424 size_t len;
2425 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2426 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2427 int ret;
2428 int max;
2429
Willy Tarreau47860ed2015-03-10 14:07:50 +01002430 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002431 if (max > len - l)
2432 max = len - l;
2433
Willy Tarreau47860ed2015-03-10 14:07:50 +01002434 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002435 if (ret == -2 || ret == -3) {
2436 lua_pushinteger(L, -1);
2437 return 1;
2438 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002439 if (ret == -1) {
2440 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002441 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002442 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002443 l += ret;
2444 lua_pop(L, 1);
2445 lua_pushinteger(L, l);
2446
Willy Tarreau47860ed2015-03-10 14:07:50 +01002447 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2448 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002449 /* There are no space avalaible, and the output buffer is empty.
2450 * in this case, we cannot add more data, so we cannot yield,
2451 * we return the amount of copyied data.
2452 */
2453 return 1;
2454 }
2455 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002456 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002457 return 1;
2458}
2459
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002460/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002461 * of the writed string, or -1 if the channel is closed or if the
2462 * buffer size is too little for the data.
2463 */
2464__LJMP static int hlua_channel_append(lua_State *L)
2465{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002466 size_t len;
2467
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002468 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002469 MAY_LJMP(hlua_checkchannel(L, 1));
2470 MAY_LJMP(luaL_checklstring(L, 2, &len));
2471 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002472 lua_pushinteger(L, 0);
2473
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002474 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002475}
2476
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002477/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002478 * his process by cleaning the buffer. The result is a replacement
2479 * of the current data. It returns the length of the writed string,
2480 * or -1 if the channel is closed or if the buffer size is too
2481 * little for the data.
2482 */
2483__LJMP static int hlua_channel_set(lua_State *L)
2484{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002485 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002486
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002487 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002488 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002489 lua_pushinteger(L, 0);
2490
Willy Tarreau47860ed2015-03-10 14:07:50 +01002491 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002492
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002493 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002494}
2495
2496/* Append data in the output side of the buffer. This data is immediatly
2497 * sent. The fcuntion returns the ammount of data writed. If the buffer
2498 * cannot contains the data, the function yield. The function returns -1
2499 * if the channel is closed.
2500 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002501__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002502{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002503 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002504 size_t len;
2505 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2506 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2507 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002508 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002509
Willy Tarreau47860ed2015-03-10 14:07:50 +01002510 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002511 lua_pushinteger(L, -1);
2512 return 1;
2513 }
2514
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002515 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2516 * the request buffer if its not required.
2517 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002518 if (chn->buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02002519 if (!stream_alloc_recv_buffer(chn)) {
Willy Tarreau47860ed2015-03-10 14:07:50 +01002520 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002521 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002522 }
2523 }
2524
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002525 /* the writed data will be immediatly sent, so we can check
2526 * the avalaible space without taking in account the reserve.
2527 * The reserve is guaranted for the processing of incoming
2528 * data, because the buffer will be flushed.
2529 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002530 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002531
2532 /* If there are no space avalaible, and the output buffer is empty.
2533 * in this case, we cannot add more data, so we cannot yield,
2534 * we return the amount of copyied data.
2535 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002536 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002537 return 1;
2538
2539 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002540 if (max > len - l)
2541 max = len - l;
2542
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002543 /* The buffer avalaible size may be not contiguous. This test
2544 * detects a non contiguous buffer and realign it.
2545 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002546 if (bi_space_for_replace(chn->buf) < max)
2547 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002548
2549 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002550 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002551
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002552 /* buffer replace considers that the input part is filled.
2553 * so, I must forward these new data in the output part.
2554 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002555 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002556
2557 l += max;
2558 lua_pop(L, 1);
2559 lua_pushinteger(L, l);
2560
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002561 /* If there are no space avalaible, and the output buffer is empty.
2562 * in this case, we cannot add more data, so we cannot yield,
2563 * we return the amount of copyied data.
2564 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002565 max = chn->buf->size - buffer_len(chn->buf);
2566 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002567 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002568
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002569 if (l < len) {
2570 /* If we are waiting for space in the response buffer, we
2571 * must set the flag WAKERESWR. This flag required the task
2572 * wake up if any activity is detected on the response buffer.
2573 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002574 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002575 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002576 else
2577 HLUA_SET_WAKEREQWR(hlua);
2578 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002579 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002580
2581 return 1;
2582}
2583
2584/* Just a wraper of "_hlua_channel_send". This wrapper permits
2585 * yield the LUA process, and resume it without checking the
2586 * input arguments.
2587 */
2588__LJMP static int hlua_channel_send(lua_State *L)
2589{
2590 MAY_LJMP(check_args(L, 2, "send"));
2591 lua_pushinteger(L, 0);
2592
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002593 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002594}
2595
2596/* This function forward and amount of butes. The data pass from
2597 * the input side of the buffer to the output side, and can be
2598 * forwarded. This function never fails.
2599 *
2600 * The Lua function takes an amount of bytes to be forwarded in
2601 * imput. It returns the number of bytes forwarded.
2602 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002603__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002604{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002605 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002606 int len;
2607 int l;
2608 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002609 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002610
2611 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2612 len = MAY_LJMP(luaL_checkinteger(L, 2));
2613 l = MAY_LJMP(luaL_checkinteger(L, -1));
2614
2615 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002616 if (max > chn->buf->i)
2617 max = chn->buf->i;
2618 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002619 l += max;
2620
2621 lua_pop(L, 1);
2622 lua_pushinteger(L, l);
2623
2624 /* Check if it miss bytes to forward. */
2625 if (l < len) {
2626 /* The the input channel or the output channel are closed, we
2627 * must return the amount of data forwarded.
2628 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002629 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002630 return 1;
2631
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002632 /* If we are waiting for space data in the response buffer, we
2633 * must set the flag WAKERESWR. This flag required the task
2634 * wake up if any activity is detected on the response buffer.
2635 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002636 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002637 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002638 else
2639 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002640
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002641 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002642 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002643 }
2644
2645 return 1;
2646}
2647
2648/* Just check the input and prepare the stack for the previous
2649 * function "hlua_channel_forward_yield"
2650 */
2651__LJMP static int hlua_channel_forward(lua_State *L)
2652{
2653 MAY_LJMP(check_args(L, 2, "forward"));
2654 MAY_LJMP(hlua_checkchannel(L, 1));
2655 MAY_LJMP(luaL_checkinteger(L, 2));
2656
2657 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002658 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002659}
2660
2661/* Just returns the number of bytes available in the input
2662 * side of the buffer. This function never fails.
2663 */
2664__LJMP static int hlua_channel_get_in_len(lua_State *L)
2665{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002666 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002667
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002668 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002669 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002670 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002671 return 1;
2672}
2673
2674/* Just returns the number of bytes available in the output
2675 * side of the buffer. This function never fails.
2676 */
2677__LJMP static int hlua_channel_get_out_len(lua_State *L)
2678{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002679 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002680
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002681 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002682 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002683 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002684 return 1;
2685}
2686
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002687/*
2688 *
2689 *
2690 * Class Fetches
2691 *
2692 *
2693 */
2694
2695/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002696 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002697 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002698__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002699{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002700 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002701}
2702
2703/* This function creates and push in the stack a fetch object according
2704 * with a current TXN.
2705 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002706static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002707{
Willy Tarreau7073c472015-04-06 11:15:40 +02002708 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002709
2710 /* Check stack size. */
2711 if (!lua_checkstack(L, 3))
2712 return 0;
2713
2714 /* Create the object: obj[0] = userdata.
2715 * Note that the base of the Fetches object is the
2716 * transaction object.
2717 */
2718 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002719 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002720 lua_rawseti(L, -2, 0);
2721
Willy Tarreau7073c472015-04-06 11:15:40 +02002722 hsmp->s = txn->s;
2723 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002724 hsmp->stringsafe = stringsafe;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002725
2726 /* Pop a class sesison metatable and affect it to the userdata. */
2727 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2728 lua_setmetatable(L, -2);
2729
2730 return 1;
2731}
2732
2733/* This function is an LUA binding. It is called with each sample-fetch.
2734 * It uses closure argument to store the associated sample-fetch. It
2735 * returns only one argument or throws an error. An error is thrown
2736 * only if an error is encountered during the argument parsing. If
2737 * the "sample-fetch" function fails, nil is returned.
2738 */
2739__LJMP static int hlua_run_sample_fetch(lua_State *L)
2740{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002741 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002742 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002743 struct arg args[ARGM_NBARGS + 1];
2744 int i;
2745 struct sample smp;
2746
2747 /* Get closure arguments. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002748 f = (struct sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002749
2750 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002751 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002752
2753 /* Get extra arguments. */
2754 for (i = 0; i < lua_gettop(L) - 1; i++) {
2755 if (i >= ARGM_NBARGS)
2756 break;
2757 hlua_lua2arg(L, i + 2, &args[i]);
2758 }
2759 args[i].type = ARGT_STOP;
2760
2761 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002762 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002763
2764 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002765 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002766 lua_pushfstring(L, "error in arguments");
2767 WILL_LJMP(lua_error(L));
2768 }
2769
2770 /* Initialise the sample. */
2771 memset(&smp, 0, sizeof(smp));
2772
2773 /* Run the sample fetch process. */
Willy Tarreau192252e2015-04-04 01:47:55 +02002774 if (!f->process(hsmp->p, hsmp->s->sess, hsmp->s, 0, args, &smp, f->kw, f->private)) {
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002775 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002776 lua_pushstring(L, "");
2777 else
2778 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002779 return 1;
2780 }
2781
2782 /* Convert the returned sample in lua value. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002783 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002784 hlua_smp2lua_str(L, &smp);
2785 else
2786 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002787 return 1;
2788}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002789
2790/*
2791 *
2792 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002793 * Class Converters
2794 *
2795 *
2796 */
2797
2798/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002799 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002800 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002801__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002802{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002803 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002804}
2805
2806/* This function creates and push in the stack a Converters object
2807 * according with a current TXN.
2808 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002809static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002810{
Willy Tarreau7073c472015-04-06 11:15:40 +02002811 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002812
2813 /* Check stack size. */
2814 if (!lua_checkstack(L, 3))
2815 return 0;
2816
2817 /* Create the object: obj[0] = userdata.
2818 * Note that the base of the Converters object is the
2819 * same than the TXN object.
2820 */
2821 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002822 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002823 lua_rawseti(L, -2, 0);
2824
Willy Tarreau7073c472015-04-06 11:15:40 +02002825 hsmp->s = txn->s;
2826 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002827 hsmp->stringsafe = stringsafe;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002828
Willy Tarreau87b09662015-04-03 00:22:06 +02002829 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002830 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
2831 lua_setmetatable(L, -2);
2832
2833 return 1;
2834}
2835
2836/* This function is an LUA binding. It is called with each converter.
2837 * It uses closure argument to store the associated converter. It
2838 * returns only one argument or throws an error. An error is thrown
2839 * only if an error is encountered during the argument parsing. If
2840 * the converter function function fails, nil is returned.
2841 */
2842__LJMP static int hlua_run_sample_conv(lua_State *L)
2843{
Willy Tarreauda5f1082015-04-06 11:17:13 +02002844 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002845 struct sample_conv *conv;
2846 struct arg args[ARGM_NBARGS + 1];
2847 int i;
2848 struct sample smp;
2849
2850 /* Get closure arguments. */
2851 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
2852
2853 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002854 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002855
2856 /* Get extra arguments. */
2857 for (i = 0; i < lua_gettop(L) - 2; i++) {
2858 if (i >= ARGM_NBARGS)
2859 break;
2860 hlua_lua2arg(L, i + 3, &args[i]);
2861 }
2862 args[i].type = ARGT_STOP;
2863
2864 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002865 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002866
2867 /* Run the special args checker. */
2868 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
2869 hlua_pusherror(L, "error in arguments");
2870 WILL_LJMP(lua_error(L));
2871 }
2872
2873 /* Initialise the sample. */
2874 if (!hlua_lua2smp(L, 2, &smp)) {
2875 hlua_pusherror(L, "error in the input argument");
2876 WILL_LJMP(lua_error(L));
2877 }
2878
2879 /* Apply expected cast. */
2880 if (!sample_casts[smp.type][conv->in_type]) {
2881 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
2882 smp_to_type[smp.type], smp_to_type[conv->in_type]);
2883 WILL_LJMP(lua_error(L));
2884 }
2885 if (sample_casts[smp.type][conv->in_type] != c_none &&
2886 !sample_casts[smp.type][conv->in_type](&smp)) {
2887 hlua_pusherror(L, "error during the input argument casting");
2888 WILL_LJMP(lua_error(L));
2889 }
2890
2891 /* Run the sample conversion process. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002892 if (!conv->process(hsmp->s, args, &smp, conv->private)) {
2893 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002894 lua_pushstring(L, "");
2895 else
2896 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002897 return 1;
2898 }
2899
2900 /* Convert the returned sample in lua value. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002901 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002902 hlua_smp2lua_str(L, &smp);
2903 else
2904 hlua_smp2lua(L, &smp);
2905 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002906}
2907
2908/*
2909 *
2910 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002911 * Class HTTP
2912 *
2913 *
2914 */
2915
2916/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002917 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002918 */
2919__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
2920{
2921 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
2922}
2923
2924/* This function creates and push in the stack a HTTP object
2925 * according with a current TXN.
2926 */
2927static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
2928{
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002929 struct hlua_txn *htxn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002930
2931 /* Check stack size. */
2932 if (!lua_checkstack(L, 3))
2933 return 0;
2934
2935 /* Create the object: obj[0] = userdata.
2936 * Note that the base of the Converters object is the
2937 * same than the TXN object.
2938 */
2939 lua_newtable(L);
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002940 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002941 lua_rawseti(L, -2, 0);
2942
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002943 htxn->s = txn->s;
2944 htxn->p = txn->p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002945
Willy Tarreau87b09662015-04-03 00:22:06 +02002946 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002947 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
2948 lua_setmetatable(L, -2);
2949
2950 return 1;
2951}
2952
2953/* This function creates ans returns an array of HTTP headers.
2954 * This function does not fails. It is used as wrapper with the
2955 * 2 following functions.
2956 */
2957__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
2958{
2959 const char *cur_ptr, *cur_next, *p;
2960 int old_idx, cur_idx;
2961 struct hdr_idx_elem *cur_hdr;
2962 const char *hn, *hv;
2963 int hnl, hvl;
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01002964 int type;
2965 const char *in;
2966 char *out;
2967 int len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002968
2969 /* Create the table. */
2970 lua_newtable(L);
2971
Willy Tarreaueee5b512015-04-03 23:46:31 +02002972 if (!htxn->s->txn)
2973 return 1;
2974
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002975 /* Build array of headers. */
2976 old_idx = 0;
Willy Tarreaueee5b512015-04-03 23:46:31 +02002977 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002978
2979 while (1) {
Willy Tarreaueee5b512015-04-03 23:46:31 +02002980 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002981 if (!cur_idx)
2982 break;
2983 old_idx = cur_idx;
2984
Willy Tarreaueee5b512015-04-03 23:46:31 +02002985 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002986 cur_ptr = cur_next;
2987 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
2988
2989 /* Now we have one full header at cur_ptr of len cur_hdr->len,
2990 * and the next header starts at cur_next. We'll check
2991 * this header in the list as well as against the default
2992 * rule.
2993 */
2994
2995 /* look for ': *'. */
2996 hn = cur_ptr;
2997 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
2998 if (p >= cur_ptr+cur_hdr->len)
2999 continue;
3000 hnl = p - hn;
3001 p++;
3002 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
3003 p++;
3004 if (p >= cur_ptr+cur_hdr->len)
3005 continue;
3006 hv = p;
3007 hvl = cur_ptr+cur_hdr->len-p;
3008
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003009 /* Lowercase the key. Don't check the size of trash, it have
3010 * the size of one buffer and the input data contains in one
3011 * buffer.
3012 */
3013 out = trash.str;
3014 for (in=hn; in<hn+hnl; in++, out++)
3015 *out = tolower(*in);
3016 *out = '\0';
3017
3018 /* Check for existing entry:
3019 * assume that the table is on the top of the stack, and
3020 * push the key in the stack, the function lua_gettable()
3021 * perform the lookup.
3022 */
3023 lua_pushlstring(L, trash.str, hnl);
3024 lua_gettable(L, -2);
3025 type = lua_type(L, -1);
3026
3027 switch (type) {
3028 case LUA_TNIL:
3029 /* Table not found, create it. */
3030 lua_pop(L, 1); /* remove the nil value. */
3031 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
3032 lua_newtable(L); /* create and push empty table. */
3033 lua_pushlstring(L, hv, hvl); /* push header value. */
3034 lua_rawseti(L, -2, 0); /* index header value (pop it). */
3035 lua_rawset(L, -3); /* index new table with header name (pop the values). */
3036 break;
3037
3038 case LUA_TTABLE:
3039 /* Entry found: push the value in the table. */
3040 len = lua_rawlen(L, -1);
3041 lua_pushlstring(L, hv, hvl); /* push header value. */
3042 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
3043 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
3044 break;
3045
3046 default:
3047 /* Other cases are errors. */
3048 hlua_pusherror(L, "internal error during the parsing of headers.");
3049 WILL_LJMP(lua_error(L));
3050 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003051 }
3052
3053 return 1;
3054}
3055
3056__LJMP static int hlua_http_req_get_headers(lua_State *L)
3057{
3058 struct hlua_txn *htxn;
3059
3060 MAY_LJMP(check_args(L, 1, "req_get_headers"));
3061 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3062
Willy Tarreaueee5b512015-04-03 23:46:31 +02003063 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003064}
3065
3066__LJMP static int hlua_http_res_get_headers(lua_State *L)
3067{
3068 struct hlua_txn *htxn;
3069
3070 MAY_LJMP(check_args(L, 1, "res_get_headers"));
3071 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3072
Willy Tarreaueee5b512015-04-03 23:46:31 +02003073 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003074}
3075
3076/* This function replace full header, or just a value in
3077 * the request or in the response. It is a wrapper fir the
3078 * 4 following functions.
3079 */
3080__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
3081 struct http_msg *msg, int action)
3082{
3083 size_t name_len;
3084 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3085 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
3086 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
3087 struct my_regex re;
3088
3089 if (!regex_comp(reg, &re, 1, 1, NULL))
3090 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
3091
3092 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
3093 regex_free(&re);
3094 return 0;
3095}
3096
3097__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
3098{
3099 struct hlua_txn *htxn;
3100
3101 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3102 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3103
Willy Tarreaueee5b512015-04-03 23:46:31 +02003104 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, HTTP_REQ_ACT_REPLACE_HDR));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003105}
3106
3107__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
3108{
3109 struct hlua_txn *htxn;
3110
3111 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
3112 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3113
Willy Tarreaueee5b512015-04-03 23:46:31 +02003114 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, HTTP_RES_ACT_REPLACE_HDR));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003115}
3116
3117__LJMP static int hlua_http_req_rep_val(lua_State *L)
3118{
3119 struct hlua_txn *htxn;
3120
3121 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3122 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3123
Willy Tarreaueee5b512015-04-03 23:46:31 +02003124 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, HTTP_REQ_ACT_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003125}
3126
3127__LJMP static int hlua_http_res_rep_val(lua_State *L)
3128{
3129 struct hlua_txn *htxn;
3130
3131 MAY_LJMP(check_args(L, 4, "res_rep_val"));
3132 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3133
Willy Tarreaueee5b512015-04-03 23:46:31 +02003134 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, HTTP_RES_ACT_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003135}
3136
3137/* This function deletes all the occurences of an header.
3138 * It is a wrapper for the 2 following functions.
3139 */
3140__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3141{
3142 size_t len;
3143 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3144 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02003145 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003146
3147 ctx.idx = 0;
3148 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
3149 http_remove_header2(msg, &txn->hdr_idx, &ctx);
3150 return 0;
3151}
3152
3153__LJMP static int hlua_http_req_del_hdr(lua_State *L)
3154{
3155 struct hlua_txn *htxn;
3156
3157 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3158 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3159
Willy Tarreaueee5b512015-04-03 23:46:31 +02003160 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003161}
3162
3163__LJMP static int hlua_http_res_del_hdr(lua_State *L)
3164{
3165 struct hlua_txn *htxn;
3166
3167 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3168 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3169
Willy Tarreaueee5b512015-04-03 23:46:31 +02003170 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003171}
3172
3173/* This function adds an header. It is a wrapper used by
3174 * the 2 following functions.
3175 */
3176__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3177{
3178 size_t name_len;
3179 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3180 size_t value_len;
3181 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
3182 char *p;
3183
3184 /* Check length. */
3185 trash.len = value_len + name_len + 2;
3186 if (trash.len > trash.size)
3187 return 0;
3188
3189 /* Creates the header string. */
3190 p = trash.str;
3191 memcpy(p, name, name_len);
3192 p += name_len;
3193 *p = ':';
3194 p++;
3195 *p = ' ';
3196 p++;
3197 memcpy(p, value, value_len);
3198
Willy Tarreaueee5b512015-04-03 23:46:31 +02003199 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003200 trash.str, trash.len) != 0);
3201
3202 return 0;
3203}
3204
3205__LJMP static int hlua_http_req_add_hdr(lua_State *L)
3206{
3207 struct hlua_txn *htxn;
3208
3209 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
3210 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3211
Willy Tarreaueee5b512015-04-03 23:46:31 +02003212 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003213}
3214
3215__LJMP static int hlua_http_res_add_hdr(lua_State *L)
3216{
3217 struct hlua_txn *htxn;
3218
3219 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
3220 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3221
Willy Tarreaueee5b512015-04-03 23:46:31 +02003222 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003223}
3224
3225static int hlua_http_req_set_hdr(lua_State *L)
3226{
3227 struct hlua_txn *htxn;
3228
3229 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
3230 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3231
Willy Tarreaueee5b512015-04-03 23:46:31 +02003232 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
3233 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003234}
3235
3236static int hlua_http_res_set_hdr(lua_State *L)
3237{
3238 struct hlua_txn *htxn;
3239
3240 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
3241 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3242
Willy Tarreaueee5b512015-04-03 23:46:31 +02003243 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
3244 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003245}
3246
3247/* This function set the method. */
3248static int hlua_http_req_set_meth(lua_State *L)
3249{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003250 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003251 size_t name_len;
3252 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003253
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003254 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003255 return 1;
3256}
3257
3258/* This function set the method. */
3259static int hlua_http_req_set_path(lua_State *L)
3260{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003261 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003262 size_t name_len;
3263 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003264 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003265 return 1;
3266}
3267
3268/* This function set the query-string. */
3269static int hlua_http_req_set_query(lua_State *L)
3270{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003271 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003272 size_t name_len;
3273 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003274
3275 /* Check length. */
3276 if (name_len > trash.size - 1) {
3277 lua_pushboolean(L, 0);
3278 return 1;
3279 }
3280
3281 /* Add the mark question as prefix. */
3282 chunk_reset(&trash);
3283 trash.str[trash.len++] = '?';
3284 memcpy(trash.str + trash.len, name, name_len);
3285 trash.len += name_len;
3286
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003287 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003288 return 1;
3289}
3290
3291/* This function set the uri. */
3292static int hlua_http_req_set_uri(lua_State *L)
3293{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003294 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003295 size_t name_len;
3296 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003297
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003298 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003299 return 1;
3300}
3301
3302/*
3303 *
3304 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003305 * Class TXN
3306 *
3307 *
3308 */
3309
3310/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003311 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003312 */
3313__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
3314{
3315 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
3316}
3317
Willy Tarreau59551662015-03-10 14:23:13 +01003318__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003319{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003320 struct hlua *hlua;
3321
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003322 MAY_LJMP(check_args(L, 2, "set_priv"));
3323
Willy Tarreau87b09662015-04-03 00:22:06 +02003324 /* It is useles to retrieve the stream, but this function
3325 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003326 */
3327 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003328 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003329
3330 /* Remove previous value. */
3331 if (hlua->Mref != -1)
3332 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3333
3334 /* Get and store new value. */
3335 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3336 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3337
3338 return 0;
3339}
3340
Willy Tarreau59551662015-03-10 14:23:13 +01003341__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003342{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003343 struct hlua *hlua;
3344
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003345 MAY_LJMP(check_args(L, 1, "get_priv"));
3346
Willy Tarreau87b09662015-04-03 00:22:06 +02003347 /* It is useles to retrieve the stream, but this function
3348 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003349 */
3350 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003351 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003352
3353 /* Push configuration index in the stack. */
3354 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3355
3356 return 1;
3357}
3358
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003359/* Create stack entry containing a class TXN. This function
3360 * return 0 if the stack does not contains free slots,
3361 * otherwise it returns 1.
3362 */
Willy Tarreau15e91e12015-04-04 00:52:09 +02003363static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003364{
Willy Tarreaude491382015-04-06 11:04:28 +02003365 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003366
3367 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003368 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003369 return 0;
3370
3371 /* NOTE: The allocation never fails. The failure
3372 * throw an error, and the function never returns.
3373 * if the throw is not avalaible, the process is aborted.
3374 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003375 /* Create the object: obj[0] = userdata. */
3376 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02003377 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003378 lua_rawseti(L, -2, 0);
3379
Willy Tarreaude491382015-04-06 11:04:28 +02003380 htxn->s = s;
3381 htxn->p = p;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003382
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003383 /* Create the "f" field that contains a list of fetches. */
3384 lua_pushstring(L, "f");
Willy Tarreaude491382015-04-06 11:04:28 +02003385 if (!hlua_fetches_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003386 return 0;
3387 lua_settable(L, -3);
3388
3389 /* Create the "sf" field that contains a list of stringsafe fetches. */
3390 lua_pushstring(L, "sf");
Willy Tarreaude491382015-04-06 11:04:28 +02003391 if (!hlua_fetches_new(L, htxn, 1))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003392 return 0;
3393 lua_settable(L, -3);
3394
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003395 /* Create the "c" field that contains a list of converters. */
3396 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02003397 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003398 return 0;
3399 lua_settable(L, -3);
3400
3401 /* Create the "sc" field that contains a list of stringsafe converters. */
3402 lua_pushstring(L, "sc");
Willy Tarreaude491382015-04-06 11:04:28 +02003403 if (!hlua_converters_new(L, htxn, 1))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003404 return 0;
3405 lua_settable(L, -3);
3406
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003407 /* Create the "req" field that contains the request channel object. */
3408 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003409 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003410 return 0;
3411 lua_settable(L, -3);
3412
3413 /* Create the "res" field that contains the response channel object. */
3414 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003415 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003416 return 0;
3417 lua_settable(L, -3);
3418
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003419 /* Creates the HTTP object is the current proxy allows http. */
3420 lua_pushstring(L, "http");
3421 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02003422 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003423 return 0;
3424 }
3425 else
3426 lua_pushnil(L);
3427 lua_settable(L, -3);
3428
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003429 /* Pop a class sesison metatable and affect it to the userdata. */
3430 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
3431 lua_setmetatable(L, -2);
3432
3433 return 1;
3434}
3435
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003436__LJMP static int hlua_txn_deflog(lua_State *L)
3437{
3438 const char *msg;
3439 struct hlua_txn *htxn;
3440
3441 MAY_LJMP(check_args(L, 2, "deflog"));
3442 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3443 msg = MAY_LJMP(luaL_checkstring(L, 2));
3444
3445 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
3446 return 0;
3447}
3448
3449__LJMP static int hlua_txn_log(lua_State *L)
3450{
3451 int level;
3452 const char *msg;
3453 struct hlua_txn *htxn;
3454
3455 MAY_LJMP(check_args(L, 3, "log"));
3456 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3457 level = MAY_LJMP(luaL_checkinteger(L, 2));
3458 msg = MAY_LJMP(luaL_checkstring(L, 3));
3459
3460 if (level < 0 || level >= NB_LOG_LEVELS)
3461 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3462
3463 hlua_sendlog(htxn->s->be, level, msg);
3464 return 0;
3465}
3466
3467__LJMP static int hlua_txn_log_debug(lua_State *L)
3468{
3469 const char *msg;
3470 struct hlua_txn *htxn;
3471
3472 MAY_LJMP(check_args(L, 2, "Debug"));
3473 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3474 msg = MAY_LJMP(luaL_checkstring(L, 2));
3475 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
3476 return 0;
3477}
3478
3479__LJMP static int hlua_txn_log_info(lua_State *L)
3480{
3481 const char *msg;
3482 struct hlua_txn *htxn;
3483
3484 MAY_LJMP(check_args(L, 2, "Info"));
3485 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3486 msg = MAY_LJMP(luaL_checkstring(L, 2));
3487 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
3488 return 0;
3489}
3490
3491__LJMP static int hlua_txn_log_warning(lua_State *L)
3492{
3493 const char *msg;
3494 struct hlua_txn *htxn;
3495
3496 MAY_LJMP(check_args(L, 2, "Warning"));
3497 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3498 msg = MAY_LJMP(luaL_checkstring(L, 2));
3499 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
3500 return 0;
3501}
3502
3503__LJMP static int hlua_txn_log_alert(lua_State *L)
3504{
3505 const char *msg;
3506 struct hlua_txn *htxn;
3507
3508 MAY_LJMP(check_args(L, 2, "Alert"));
3509 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3510 msg = MAY_LJMP(luaL_checkstring(L, 2));
3511 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
3512 return 0;
3513}
3514
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003515__LJMP static int hlua_txn_set_loglevel(lua_State *L)
3516{
3517 struct hlua_txn *htxn;
3518 int ll;
3519
3520 MAY_LJMP(check_args(L, 2, "set_loglevel"));
3521 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3522 ll = MAY_LJMP(luaL_checkinteger(L, 2));
3523
3524 if (ll < 0 || ll > 7)
3525 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
3526
3527 htxn->s->logs.level = ll;
3528 return 0;
3529}
3530
3531__LJMP static int hlua_txn_set_tos(lua_State *L)
3532{
3533 struct hlua_txn *htxn;
3534 struct connection *cli_conn;
3535 int tos;
3536
3537 MAY_LJMP(check_args(L, 2, "set_tos"));
3538 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3539 tos = MAY_LJMP(luaL_checkinteger(L, 2));
3540
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003541 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003542 inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, tos);
3543
3544 return 0;
3545}
3546
3547__LJMP static int hlua_txn_set_mark(lua_State *L)
3548{
3549#ifdef SO_MARK
3550 struct hlua_txn *htxn;
3551 struct connection *cli_conn;
3552 int mark;
3553
3554 MAY_LJMP(check_args(L, 2, "set_mark"));
3555 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3556 mark = MAY_LJMP(luaL_checkinteger(L, 2));
3557
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003558 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02003559 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003560#endif
3561 return 0;
3562}
3563
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003564/* This function is an Lua binding that send pending data
3565 * to the client, and close the stream interface.
3566 */
3567__LJMP static int hlua_txn_close(lua_State *L)
3568{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003569 struct hlua_txn *htxn;
Willy Tarreau81389672015-03-10 12:03:52 +01003570 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003571
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003572 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003573 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003574
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003575 ic = &htxn->s->req;
3576 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01003577
3578 channel_abort(ic);
3579 channel_auto_close(ic);
3580 channel_erase(ic);
3581 channel_auto_read(oc);
3582 channel_auto_close(oc);
3583 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003584
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003585 return 0;
3586}
3587
3588__LJMP static int hlua_log(lua_State *L)
3589{
3590 int level;
3591 const char *msg;
3592
3593 MAY_LJMP(check_args(L, 2, "log"));
3594 level = MAY_LJMP(luaL_checkinteger(L, 1));
3595 msg = MAY_LJMP(luaL_checkstring(L, 2));
3596
3597 if (level < 0 || level >= NB_LOG_LEVELS)
3598 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3599
3600 hlua_sendlog(NULL, level, msg);
3601 return 0;
3602}
3603
3604__LJMP static int hlua_log_debug(lua_State *L)
3605{
3606 const char *msg;
3607
3608 MAY_LJMP(check_args(L, 1, "debug"));
3609 msg = MAY_LJMP(luaL_checkstring(L, 1));
3610 hlua_sendlog(NULL, LOG_DEBUG, msg);
3611 return 0;
3612}
3613
3614__LJMP static int hlua_log_info(lua_State *L)
3615{
3616 const char *msg;
3617
3618 MAY_LJMP(check_args(L, 1, "info"));
3619 msg = MAY_LJMP(luaL_checkstring(L, 1));
3620 hlua_sendlog(NULL, LOG_INFO, msg);
3621 return 0;
3622}
3623
3624__LJMP static int hlua_log_warning(lua_State *L)
3625{
3626 const char *msg;
3627
3628 MAY_LJMP(check_args(L, 1, "warning"));
3629 msg = MAY_LJMP(luaL_checkstring(L, 1));
3630 hlua_sendlog(NULL, LOG_WARNING, msg);
3631 return 0;
3632}
3633
3634__LJMP static int hlua_log_alert(lua_State *L)
3635{
3636 const char *msg;
3637
3638 MAY_LJMP(check_args(L, 1, "alert"));
3639 msg = MAY_LJMP(luaL_checkstring(L, 1));
3640 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003641 return 0;
3642}
3643
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003644__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003645{
3646 int wakeup_ms = lua_tointeger(L, -1);
3647 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003648 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003649 return 0;
3650}
3651
3652__LJMP static int hlua_sleep(lua_State *L)
3653{
3654 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003655 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003656
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003657 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003658
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003659 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003660 wakeup_ms = tick_add(now_ms, delay);
3661 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003662
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003663 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3664 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003665}
3666
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003667__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003668{
3669 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003670 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003671
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003672 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003673
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003674 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003675 wakeup_ms = tick_add(now_ms, delay);
3676 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003677
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003678 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3679 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003680}
3681
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003682/* This functionis an LUA binding. it permits to give back
3683 * the hand at the HAProxy scheduler. It is used when the
3684 * LUA processing consumes a lot of time.
3685 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003686__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003687{
3688 return 0;
3689}
3690
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003691__LJMP static int hlua_yield(lua_State *L)
3692{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003693 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
3694 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003695}
3696
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003697/* This function change the nice of the currently executed
3698 * task. It is used set low or high priority at the current
3699 * task.
3700 */
Willy Tarreau59551662015-03-10 14:23:13 +01003701__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003702{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003703 struct hlua *hlua;
3704 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003705
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003706 MAY_LJMP(check_args(L, 1, "set_nice"));
3707 hlua = hlua_gethlua(L);
3708 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003709
3710 /* If he task is not set, I'm in a start mode. */
3711 if (!hlua || !hlua->task)
3712 return 0;
3713
3714 if (nice < -1024)
3715 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003716 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003717 nice = 1024;
3718
3719 hlua->task->nice = nice;
3720 return 0;
3721}
3722
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003723/* This function is used as a calback of a task. It is called by the
3724 * HAProxy task subsystem when the task is awaked. The LUA runtime can
3725 * return an E_AGAIN signal, the emmiter of this signal must set a
3726 * signal to wake the task.
3727 */
3728static struct task *hlua_process_task(struct task *task)
3729{
3730 struct hlua *hlua = task->context;
3731 enum hlua_exec status;
3732
3733 /* We need to remove the task from the wait queue before executing
3734 * the Lua code because we don't know if it needs to wait for
3735 * another timer or not in the case of E_AGAIN.
3736 */
3737 task_delete(task);
3738
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003739 /* If it is the first call to the task, we must initialize the
3740 * execution timeouts.
3741 */
3742 if (!HLUA_IS_RUNNING(hlua))
3743 hlua->expire = tick_add(now_ms, hlua_timeout_task);
3744
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003745 /* Execute the Lua code. */
3746 status = hlua_ctx_resume(hlua, 1);
3747
3748 switch (status) {
3749 /* finished or yield */
3750 case HLUA_E_OK:
3751 hlua_ctx_destroy(hlua);
3752 task_delete(task);
3753 task_free(task);
3754 break;
3755
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003756 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
3757 if (hlua->wake_time != TICK_ETERNITY)
3758 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003759 break;
3760
3761 /* finished with error. */
3762 case HLUA_E_ERRMSG:
3763 send_log(NULL, LOG_ERR, "Lua task: %s.", lua_tostring(hlua->T, -1));
3764 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3765 Alert("Lua task: %s.\n", lua_tostring(hlua->T, -1));
3766 hlua_ctx_destroy(hlua);
3767 task_delete(task);
3768 task_free(task);
3769 break;
3770
3771 case HLUA_E_ERR:
3772 default:
3773 send_log(NULL, LOG_ERR, "Lua task: unknown error.");
3774 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3775 Alert("Lua task: unknown error.\n");
3776 hlua_ctx_destroy(hlua);
3777 task_delete(task);
3778 task_free(task);
3779 break;
3780 }
3781 return NULL;
3782}
3783
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003784/* This function is an LUA binding that register LUA function to be
3785 * executed after the HAProxy configuration parsing and before the
3786 * HAProxy scheduler starts. This function expect only one LUA
3787 * argument that is a function. This function returns nothing, but
3788 * throws if an error is encountered.
3789 */
3790__LJMP static int hlua_register_init(lua_State *L)
3791{
3792 struct hlua_init_function *init;
3793 int ref;
3794
3795 MAY_LJMP(check_args(L, 1, "register_init"));
3796
3797 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3798
3799 init = malloc(sizeof(*init));
3800 if (!init)
3801 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3802
3803 init->function_ref = ref;
3804 LIST_ADDQ(&hlua_init_functions, &init->l);
3805 return 0;
3806}
3807
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003808/* This functio is an LUA binding. It permits to register a task
3809 * executed in parallel of the main HAroxy activity. The task is
3810 * created and it is set in the HAProxy scheduler. It can be called
3811 * from the "init" section, "post init" or during the runtime.
3812 *
3813 * Lua prototype:
3814 *
3815 * <none> core.register_task(<function>)
3816 */
3817static int hlua_register_task(lua_State *L)
3818{
3819 struct hlua *hlua;
3820 struct task *task;
3821 int ref;
3822
3823 MAY_LJMP(check_args(L, 1, "register_task"));
3824
3825 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3826
3827 hlua = malloc(sizeof(*hlua));
3828 if (!hlua)
3829 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3830
3831 task = task_new();
3832 task->context = hlua;
3833 task->process = hlua_process_task;
3834
3835 if (!hlua_ctx_init(hlua, task))
3836 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3837
3838 /* Restore the function in the stack. */
3839 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
3840 hlua->nargs = 0;
3841
3842 /* Schedule task. */
3843 task_schedule(task, now_ms);
3844
3845 return 0;
3846}
3847
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003848/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
3849 * doesn't allow "yield" functions because the HAProxy engine cannot
3850 * resume converters.
3851 */
Willy Tarreau87b09662015-04-03 00:22:06 +02003852static int hlua_sample_conv_wrapper(struct stream *stream, const struct arg *arg_p,
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003853 struct sample *smp, void *private)
3854{
3855 struct hlua_function *fcn = (struct hlua_function *)private;
3856
Willy Tarreau87b09662015-04-03 00:22:06 +02003857 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003858 * Lua context can be not initialized. This behavior
3859 * permits to save performances because a systematic
3860 * Lua initialization cause 5% performances loss.
3861 */
Willy Tarreau87b09662015-04-03 00:22:06 +02003862 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
3863 send_log(stream->be, LOG_ERR, "Lua converter '%s': can't initialize Lua context.", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003864 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3865 Alert("Lua converter '%s': can't initialize Lua context.\n", fcn->name);
3866 return 0;
3867 }
3868
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003869 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003870 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003871 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003872 if (!lua_checkstack(stream->hlua.T, 1)) {
3873 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003874 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3875 Alert("Lua converter '%s': full stack.\n", fcn->name);
3876 return 0;
3877 }
3878
3879 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003880 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003881
3882 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003883 if (!lua_checkstack(stream->hlua.T, 1)) {
3884 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003885 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3886 Alert("Lua converter '%s': full stack.\n", fcn->name);
3887 return 0;
3888 }
Willy Tarreau87b09662015-04-03 00:22:06 +02003889 hlua_smp2lua(stream->hlua.T, smp);
3890 stream->hlua.nargs = 2;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003891
3892 /* push keywords in the stack. */
3893 if (arg_p) {
3894 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02003895 if (!lua_checkstack(stream->hlua.T, 1)) {
3896 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003897 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3898 Alert("Lua converter '%s': full stack.\n", fcn->name);
3899 return 0;
3900 }
Willy Tarreau87b09662015-04-03 00:22:06 +02003901 hlua_arg2lua(stream->hlua.T, arg_p);
3902 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003903 }
3904 }
3905
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003906 /* We must initialize the execution timeouts. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003907 stream->hlua.expire = tick_add(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003908
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003909 /* Set the currently running flag. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003910 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003911 }
3912
3913 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003914 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003915 /* finished. */
3916 case HLUA_E_OK:
3917 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003918 hlua_lua2smp(stream->hlua.T, -1, smp);
3919 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003920 return 1;
3921
3922 /* yield. */
3923 case HLUA_E_AGAIN:
Willy Tarreau87b09662015-04-03 00:22:06 +02003924 send_log(stream->be, LOG_ERR, "Lua converter '%s': cannot use yielded functions.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003925 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3926 Alert("Lua converter '%s': cannot use yielded functions.\n", fcn->name);
3927 return 0;
3928
3929 /* finished with error. */
3930 case HLUA_E_ERRMSG:
3931 /* Display log. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003932 send_log(stream->be, LOG_ERR, "Lua converter '%s': %s.", fcn->name, lua_tostring(stream->hlua.T, -1));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003933 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Willy Tarreau87b09662015-04-03 00:22:06 +02003934 Alert("Lua converter '%s': %s.\n", fcn->name, lua_tostring(stream->hlua.T, -1));
3935 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003936 return 0;
3937
3938 case HLUA_E_ERR:
3939 /* Display log. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003940 send_log(stream->be, LOG_ERR, "Lua converter '%s' returns an unknown error.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003941 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3942 Alert("Lua converter '%s' returns an unknown error.\n", fcn->name);
3943
3944 default:
3945 return 0;
3946 }
3947}
3948
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003949/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
3950 * doesn't allow "yield" functions because the HAProxy engine cannot
3951 * resume sample-fetches.
3952 */
Willy Tarreau192252e2015-04-04 01:47:55 +02003953static int hlua_sample_fetch_wrapper(struct proxy *px, struct session *sess,
3954 struct stream *s, unsigned int opt,
3955 const struct arg *arg_p,
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003956 struct sample *smp, const char *kw, void *private)
3957{
3958 struct hlua_function *fcn = (struct hlua_function *)private;
3959
Willy Tarreau87b09662015-04-03 00:22:06 +02003960 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003961 * Lua context can be not initialized. This behavior
3962 * permits to save performances because a systematic
3963 * Lua initialization cause 5% performances loss.
3964 */
3965 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
3966 send_log(s->be, LOG_ERR, "Lua sample-fetch '%s': can't initialize Lua context.", fcn->name);
3967 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3968 Alert("Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
3969 return 0;
3970 }
3971
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003972 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003973 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003974 /* Check stack available size. */
3975 if (!lua_checkstack(s->hlua.T, 2)) {
3976 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3977 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3978 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3979 return 0;
3980 }
3981
3982 /* Restore the function in the stack. */
3983 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
3984
3985 /* push arguments in the stack. */
Willy Tarreau15e91e12015-04-04 00:52:09 +02003986 if (!hlua_txn_new(s->hlua.T, s, px)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003987 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3988 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3989 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3990 return 0;
3991 }
3992 s->hlua.nargs = 1;
3993
3994 /* push keywords in the stack. */
3995 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
3996 /* Check stack available size. */
3997 if (!lua_checkstack(s->hlua.T, 1)) {
3998 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3999 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4000 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4001 return 0;
4002 }
4003 if (!lua_checkstack(s->hlua.T, 1)) {
4004 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
4005 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4006 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4007 return 0;
4008 }
4009 hlua_arg2lua(s->hlua.T, arg_p);
4010 s->hlua.nargs++;
4011 }
4012
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004013 /* We must initialize the execution timeouts. */
4014 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
4015
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004016 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004017 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004018 }
4019
4020 /* Execute the function. */
4021 switch (hlua_ctx_resume(&s->hlua, 0)) {
4022 /* finished. */
4023 case HLUA_E_OK:
4024 /* Convert the returned value in sample. */
4025 hlua_lua2smp(s->hlua.T, -1, smp);
4026 lua_pop(s->hlua.T, 1);
4027
4028 /* Set the end of execution flag. */
4029 smp->flags &= ~SMP_F_MAY_CHANGE;
4030 return 1;
4031
4032 /* yield. */
4033 case HLUA_E_AGAIN:
4034 send_log(px, LOG_ERR, "Lua sample-fetch '%s': cannot use yielded functions.", fcn->name);
4035 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4036 Alert("Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
4037 return 0;
4038
4039 /* finished with error. */
4040 case HLUA_E_ERRMSG:
4041 /* Display log. */
4042 send_log(px, LOG_ERR, "Lua sample-fetch '%s': %s.", fcn->name, lua_tostring(s->hlua.T, -1));
4043 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4044 Alert("Lua sample-fetch '%s': %s.\n", fcn->name, lua_tostring(s->hlua.T, -1));
4045 lua_pop(s->hlua.T, 1);
4046 return 0;
4047
4048 case HLUA_E_ERR:
4049 /* Display log. */
4050 send_log(px, LOG_ERR, "Lua sample-fetch '%s' returns an unknown error.", fcn->name);
4051 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4052 Alert("Lua sample-fetch '%s': returns an unknown error.\n", fcn->name);
4053
4054 default:
4055 return 0;
4056 }
4057}
4058
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004059/* This function is an LUA binding used for registering
4060 * "sample-conv" functions. It expects a converter name used
4061 * in the haproxy configuration file, and an LUA function.
4062 */
4063__LJMP static int hlua_register_converters(lua_State *L)
4064{
4065 struct sample_conv_kw_list *sck;
4066 const char *name;
4067 int ref;
4068 int len;
4069 struct hlua_function *fcn;
4070
4071 MAY_LJMP(check_args(L, 2, "register_converters"));
4072
4073 /* First argument : converter name. */
4074 name = MAY_LJMP(luaL_checkstring(L, 1));
4075
4076 /* Second argument : lua function. */
4077 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4078
4079 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004080 sck = malloc(sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004081 if (!sck)
4082 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4083 fcn = malloc(sizeof(*fcn));
4084 if (!fcn)
4085 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4086
4087 /* Fill fcn. */
4088 fcn->name = strdup(name);
4089 if (!fcn->name)
4090 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4091 fcn->function_ref = ref;
4092
4093 /* List head */
4094 sck->list.n = sck->list.p = NULL;
4095
4096 /* converter keyword. */
4097 len = strlen("lua.") + strlen(name) + 1;
4098 sck->kw[0].kw = malloc(len);
4099 if (!sck->kw[0].kw)
4100 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4101
4102 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
4103 sck->kw[0].process = hlua_sample_conv_wrapper;
4104 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4105 sck->kw[0].val_args = NULL;
4106 sck->kw[0].in_type = SMP_T_STR;
4107 sck->kw[0].out_type = SMP_T_STR;
4108 sck->kw[0].private = fcn;
4109
4110 /* End of array. */
4111 memset(&sck->kw[1], 0, sizeof(struct sample_conv));
4112
4113 /* Register this new converter */
4114 sample_register_convs(sck);
4115
4116 return 0;
4117}
4118
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004119/* This fucntion is an LUA binding used for registering
4120 * "sample-fetch" functions. It expects a converter name used
4121 * in the haproxy configuration file, and an LUA function.
4122 */
4123__LJMP static int hlua_register_fetches(lua_State *L)
4124{
4125 const char *name;
4126 int ref;
4127 int len;
4128 struct sample_fetch_kw_list *sfk;
4129 struct hlua_function *fcn;
4130
4131 MAY_LJMP(check_args(L, 2, "register_fetches"));
4132
4133 /* First argument : sample-fetch name. */
4134 name = MAY_LJMP(luaL_checkstring(L, 1));
4135
4136 /* Second argument : lua function. */
4137 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4138
4139 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004140 sfk = malloc(sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004141 if (!sfk)
4142 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4143 fcn = malloc(sizeof(*fcn));
4144 if (!fcn)
4145 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4146
4147 /* Fill fcn. */
4148 fcn->name = strdup(name);
4149 if (!fcn->name)
4150 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4151 fcn->function_ref = ref;
4152
4153 /* List head */
4154 sfk->list.n = sfk->list.p = NULL;
4155
4156 /* sample-fetch keyword. */
4157 len = strlen("lua.") + strlen(name) + 1;
4158 sfk->kw[0].kw = malloc(len);
4159 if (!sfk->kw[0].kw)
4160 return luaL_error(L, "lua out of memory error.");
4161
4162 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
4163 sfk->kw[0].process = hlua_sample_fetch_wrapper;
4164 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4165 sfk->kw[0].val_args = NULL;
4166 sfk->kw[0].out_type = SMP_T_STR;
4167 sfk->kw[0].use = SMP_USE_HTTP_ANY;
4168 sfk->kw[0].val = 0;
4169 sfk->kw[0].private = fcn;
4170
4171 /* End of array. */
4172 memset(&sfk->kw[1], 0, sizeof(struct sample_fetch));
4173
4174 /* Register this new fetch. */
4175 sample_register_fetches(sfk);
4176
4177 return 0;
4178}
4179
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004180/* global {tcp|http}-request parser. Return 1 in succes case, else return 0. */
4181static int hlua_parse_rule(const char **args, int *cur_arg, struct proxy *px,
4182 struct hlua_rule **rule_p, char **err)
4183{
4184 struct hlua_rule *rule;
4185
4186 /* Memory for the rule. */
4187 rule = malloc(sizeof(*rule));
4188 if (!rule) {
4189 memprintf(err, "out of memory error");
4190 return 0;
4191 }
4192 *rule_p = rule;
4193
4194 /* The requiered arg is a function name. */
4195 if (!args[*cur_arg]) {
4196 memprintf(err, "expect Lua function name");
4197 return 0;
4198 }
4199
4200 /* Lookup for the symbol, and check if it is a function. */
4201 lua_getglobal(gL.T, args[*cur_arg]);
4202 if (lua_isnil(gL.T, -1)) {
4203 lua_pop(gL.T, 1);
4204 memprintf(err, "Lua function '%s' not found", args[*cur_arg]);
4205 return 0;
4206 }
4207 if (!lua_isfunction(gL.T, -1)) {
4208 lua_pop(gL.T, 1);
4209 memprintf(err, "'%s' is not a function", args[*cur_arg]);
4210 return 0;
4211 }
4212
4213 /* Reference the Lua function and store the reference. */
4214 rule->fcn.function_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
4215 rule->fcn.name = strdup(args[*cur_arg]);
4216 if (!rule->fcn.name) {
4217 memprintf(err, "out of memory error.");
4218 return 0;
4219 }
4220 (*cur_arg)++;
4221
4222 /* TODO: later accept arguments. */
4223 rule->args = NULL;
4224
4225 return 1;
4226}
4227
4228/* This function is a wrapper to execute each LUA function declared
4229 * as an action wrapper during the initialisation period. This function
4230 * return 1 if the processing is finished (with oe without error) and
4231 * return 0 if the function must be called again because the LUA
4232 * returns a yield.
4233 */
4234static int hlua_request_act_wrapper(struct hlua_rule *rule, struct proxy *px,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004235 struct stream *s, unsigned int analyzer)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004236{
4237 char **arg;
4238
Willy Tarreau87b09662015-04-03 00:22:06 +02004239 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004240 * Lua context can be not initialized. This behavior
4241 * permits to save performances because a systematic
4242 * Lua initialization cause 5% performances loss.
4243 */
4244 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
4245 send_log(px, LOG_ERR, "Lua action '%s': can't initialize Lua context.", rule->fcn.name);
4246 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4247 Alert("Lua action '%s': can't initialize Lua context.\n", rule->fcn.name);
4248 return 0;
4249 }
4250
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004251 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004252 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004253 /* Check stack available size. */
4254 if (!lua_checkstack(s->hlua.T, 1)) {
4255 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
4256 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4257 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
4258 return 0;
4259 }
4260
4261 /* Restore the function in the stack. */
4262 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->fcn.function_ref);
4263
Willy Tarreau87b09662015-04-03 00:22:06 +02004264 /* Create and and push object stream in the stack. */
Willy Tarreau15e91e12015-04-04 00:52:09 +02004265 if (!hlua_txn_new(s->hlua.T, s, px)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004266 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
4267 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4268 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
4269 return 0;
4270 }
4271 s->hlua.nargs = 1;
4272
4273 /* push keywords in the stack. */
4274 for (arg = rule->args; arg && *arg; arg++) {
4275 if (!lua_checkstack(s->hlua.T, 1)) {
4276 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
4277 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4278 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
4279 return 0;
4280 }
4281 lua_pushstring(s->hlua.T, *arg);
4282 s->hlua.nargs++;
4283 }
4284
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004285 /* We must initialize the execution timeouts. */
4286 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
4287
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004288 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004289 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004290 }
4291
4292 /* Execute the function. */
4293 switch (hlua_ctx_resume(&s->hlua, 1)) {
4294 /* finished. */
4295 case HLUA_E_OK:
4296 return 1;
4297
4298 /* yield. */
4299 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004300 /* Set timeout in the required channel. */
4301 if (s->hlua.wake_time != TICK_ETERNITY) {
4302 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004303 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004304 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004305 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004306 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004307 /* Some actions can be wake up when a "write" event
4308 * is detected on a response channel. This is useful
4309 * only for actions targetted on the requests.
4310 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004311 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004312 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01004313 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004314 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004315 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004316 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004317 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004318 return 0;
4319
4320 /* finished with error. */
4321 case HLUA_E_ERRMSG:
4322 /* Display log. */
4323 send_log(px, LOG_ERR, "Lua function '%s': %s.", rule->fcn.name, lua_tostring(s->hlua.T, -1));
4324 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4325 Alert("Lua function '%s': %s.\n", rule->fcn.name, lua_tostring(s->hlua.T, -1));
4326 lua_pop(s->hlua.T, 1);
4327 return 1;
4328
4329 case HLUA_E_ERR:
4330 /* Display log. */
4331 send_log(px, LOG_ERR, "Lua function '%s' return an unknown error.", rule->fcn.name);
4332 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4333 Alert("Lua function '%s' return an unknown error.\n", rule->fcn.name);
4334
4335 default:
4336 return 1;
4337 }
4338}
4339
4340/* Lua execution wrapper for "tcp-request". This function uses
4341 * "hlua_request_act_wrapper" for executing the LUA code.
4342 */
4343int hlua_tcp_req_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
Willy Tarreau87b09662015-04-03 00:22:06 +02004344 struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004345{
4346 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004347 px, s, AN_REQ_INSPECT_FE);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004348}
4349
4350/* Lua execution wrapper for "tcp-response". This function uses
4351 * "hlua_request_act_wrapper" for executing the LUA code.
4352 */
4353int hlua_tcp_res_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
Willy Tarreau87b09662015-04-03 00:22:06 +02004354 struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004355{
4356 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004357 px, s, AN_RES_INSPECT);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004358}
4359
4360/* Lua execution wrapper for http-request.
4361 * This function uses "hlua_request_act_wrapper" for executing
4362 * the LUA code.
4363 */
4364int hlua_http_req_act_wrapper(struct http_req_rule *rule, struct proxy *px,
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004365 struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004366{
4367 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004368 s, AN_REQ_HTTP_PROCESS_FE);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004369}
4370
4371/* Lua execution wrapper for http-response.
4372 * This function uses "hlua_request_act_wrapper" for executing
4373 * the LUA code.
4374 */
4375int hlua_http_res_act_wrapper(struct http_res_rule *rule, struct proxy *px,
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004376 struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004377{
4378 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004379 s, AN_RES_HTTP_PROCESS_BE);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004380}
4381
4382/* tcp-request <*> configuration wrapper. */
4383static int tcp_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4384 struct tcp_rule *rule, char **err)
4385{
4386 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004387 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004388 rule->action = TCP_ACT_CUSTOM;
4389 rule->action_ptr = hlua_tcp_req_act_wrapper;
4390 return 1;
4391}
4392
4393/* tcp-response <*> configuration wrapper. */
4394static int tcp_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4395 struct tcp_rule *rule, char **err)
4396{
4397 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004398 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004399 rule->action = TCP_ACT_CUSTOM;
4400 rule->action_ptr = hlua_tcp_res_act_wrapper;
4401 return 1;
4402}
4403
4404/* http-request <*> configuration wrapper. */
4405static int http_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4406 struct http_req_rule *rule, char **err)
4407{
4408 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
4409 return -1;
4410 rule->action = HTTP_REQ_ACT_CUSTOM_CONT;
4411 rule->action_ptr = hlua_http_req_act_wrapper;
4412 return 1;
4413}
4414
4415/* http-response <*> configuration wrapper. */
4416static int http_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4417 struct http_res_rule *rule, char **err)
4418{
4419 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
4420 return -1;
4421 rule->action = HTTP_RES_ACT_CUSTOM_CONT;
4422 rule->action_ptr = hlua_http_res_act_wrapper;
4423 return 1;
4424}
4425
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004426static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
4427 struct proxy *defpx, const char *file, int line,
4428 char **err, unsigned int *timeout)
4429{
4430 const char *error;
4431
4432 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
4433 if (error && *error != '\0') {
4434 memprintf(err, "%s: invalid timeout", args[0]);
4435 return -1;
4436 }
4437 return 0;
4438}
4439
4440static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
4441 struct proxy *defpx, const char *file, int line,
4442 char **err)
4443{
4444 return hlua_read_timeout(args, section_type, curpx, defpx,
4445 file, line, err, &hlua_timeout_session);
4446}
4447
4448static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
4449 struct proxy *defpx, const char *file, int line,
4450 char **err)
4451{
4452 return hlua_read_timeout(args, section_type, curpx, defpx,
4453 file, line, err, &hlua_timeout_task);
4454}
4455
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004456static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
4457 struct proxy *defpx, const char *file, int line,
4458 char **err)
4459{
4460 char *error;
4461
4462 hlua_nb_instruction = strtoll(args[1], &error, 10);
4463 if (*error != '\0') {
4464 memprintf(err, "%s: invalid number", args[0]);
4465 return -1;
4466 }
4467 return 0;
4468}
4469
Willy Tarreau32f61e22015-03-18 17:54:59 +01004470static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
4471 struct proxy *defpx, const char *file, int line,
4472 char **err)
4473{
4474 char *error;
4475
4476 if (*(args[1]) == 0) {
4477 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
4478 return -1;
4479 }
4480 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
4481 if (*error != '\0') {
4482 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
4483 return -1;
4484 }
4485 return 0;
4486}
4487
4488
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004489/* This function is called by the main configuration key "lua-load". It loads and
4490 * execute an lua file during the parsing of the HAProxy configuration file. It is
4491 * the main lua entry point.
4492 *
4493 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
4494 * occured, otherwise it returns 0.
4495 *
4496 * In some error case, LUA set an error message in top of the stack. This function
4497 * returns this error message in the HAProxy logs and pop it from the stack.
4498 */
4499static int hlua_load(char **args, int section_type, struct proxy *curpx,
4500 struct proxy *defpx, const char *file, int line,
4501 char **err)
4502{
4503 int error;
4504
4505 /* Just load and compile the file. */
4506 error = luaL_loadfile(gL.T, args[1]);
4507 if (error) {
4508 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
4509 lua_pop(gL.T, 1);
4510 return -1;
4511 }
4512
4513 /* If no syntax error where detected, execute the code. */
4514 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
4515 switch (error) {
4516 case LUA_OK:
4517 break;
4518 case LUA_ERRRUN:
4519 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
4520 lua_pop(gL.T, 1);
4521 return -1;
4522 case LUA_ERRMEM:
4523 memprintf(err, "lua out of memory error\n");
4524 return -1;
4525 case LUA_ERRERR:
4526 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
4527 lua_pop(gL.T, 1);
4528 return -1;
4529 case LUA_ERRGCMM:
4530 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
4531 lua_pop(gL.T, 1);
4532 return -1;
4533 default:
4534 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
4535 lua_pop(gL.T, 1);
4536 return -1;
4537 }
4538
4539 return 0;
4540}
4541
4542/* configuration keywords declaration */
4543static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004544 { CFG_GLOBAL, "lua-load", hlua_load },
4545 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
4546 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004547 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01004548 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004549 { 0, NULL, NULL },
4550}};
4551
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004552static struct http_req_action_kw_list http_req_kws = {"lua", { }, {
4553 { "lua", http_req_action_register_lua },
4554 { NULL, NULL }
4555}};
4556
4557static struct http_res_action_kw_list http_res_kws = {"lua", { }, {
4558 { "lua", http_res_action_register_lua },
4559 { NULL, NULL }
4560}};
4561
4562static struct tcp_action_kw_list tcp_req_cont_kws = {"lua", { }, {
4563 { "lua", tcp_req_action_register_lua },
4564 { NULL, NULL }
4565}};
4566
4567static struct tcp_action_kw_list tcp_res_cont_kws = {"lua", { }, {
4568 { "lua", tcp_res_action_register_lua },
4569 { NULL, NULL }
4570}};
4571
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004572int hlua_post_init()
4573{
4574 struct hlua_init_function *init;
4575 const char *msg;
4576 enum hlua_exec ret;
4577
4578 list_for_each_entry(init, &hlua_init_functions, l) {
4579 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
4580 ret = hlua_ctx_resume(&gL, 0);
4581 switch (ret) {
4582 case HLUA_E_OK:
4583 lua_pop(gL.T, -1);
4584 return 1;
4585 case HLUA_E_AGAIN:
4586 Alert("lua init: yield not allowed.\n");
4587 return 0;
4588 case HLUA_E_ERRMSG:
4589 msg = lua_tostring(gL.T, -1);
4590 Alert("lua init: %s.\n", msg);
4591 return 0;
4592 case HLUA_E_ERR:
4593 default:
4594 Alert("lua init: unknown runtime error.\n");
4595 return 0;
4596 }
4597 }
4598 return 1;
4599}
4600
Willy Tarreau32f61e22015-03-18 17:54:59 +01004601/* The memory allocator used by the Lua stack. <ud> is a pointer to the
4602 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
4603 * is the previously allocated size or the kind of object in case of a new
4604 * allocation. <nsize> is the requested new size.
4605 */
4606static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
4607{
4608 struct hlua_mem_allocator *zone = ud;
4609
4610 if (nsize == 0) {
4611 /* it's a free */
4612 if (ptr)
4613 zone->allocated -= osize;
4614 free(ptr);
4615 return NULL;
4616 }
4617
4618 if (!ptr) {
4619 /* it's a new allocation */
4620 if (zone->limit && zone->allocated + nsize > zone->limit)
4621 return NULL;
4622
4623 ptr = malloc(nsize);
4624 if (ptr)
4625 zone->allocated += nsize;
4626 return ptr;
4627 }
4628
4629 /* it's a realloc */
4630 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
4631 return NULL;
4632
4633 ptr = realloc(ptr, nsize);
4634 if (ptr)
4635 zone->allocated += nsize - osize;
4636 return ptr;
4637}
4638
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01004639void hlua_init(void)
4640{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004641 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004642 int idx;
4643 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004644 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004645 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004646#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004647 struct srv_kw *kw;
4648 int tmp_error;
4649 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01004650 char *args[] = { /* SSL client configuration. */
4651 "ssl",
4652 "verify",
4653 "none",
4654 "force-sslv3",
4655 NULL
4656 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004657#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004658
Willy Tarreau87b09662015-04-03 00:22:06 +02004659 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004660 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
4661
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004662 /* Register configuration keywords. */
4663 cfg_register_keywords(&cfg_kws);
4664
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004665 /* Register custom HTTP rules. */
4666 http_req_keywords_register(&http_req_kws);
4667 http_res_keywords_register(&http_res_kws);
4668 tcp_req_cont_keywords_register(&tcp_req_cont_kws);
4669 tcp_res_cont_keywords_register(&tcp_res_cont_kws);
4670
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004671 /* Init main lua stack. */
4672 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004673 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004674 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004675 gL.T = luaL_newstate();
4676 hlua_sethlua(&gL);
4677 gL.Tref = LUA_REFNIL;
4678 gL.task = NULL;
4679
Willy Tarreau32f61e22015-03-18 17:54:59 +01004680 /* change the memory allocators to track memory usage */
4681 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
4682
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004683 /* Initialise lua. */
4684 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004685
4686 /*
4687 *
4688 * Create "core" object.
4689 *
4690 */
4691
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01004692 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004693 lua_newtable(gL.T);
4694
4695 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004696 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004697 hlua_class_const_int(gL.T, log_levels[i], i);
4698
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004699 /* Register special functions. */
4700 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004701 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004702 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004703 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004704 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01004705 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004706 hlua_class_function(gL.T, "sleep", hlua_sleep);
4707 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01004708 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
4709 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
4710 hlua_class_function(gL.T, "set_map", hlua_set_map);
4711 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004712 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004713 hlua_class_function(gL.T, "log", hlua_log);
4714 hlua_class_function(gL.T, "Debug", hlua_log_debug);
4715 hlua_class_function(gL.T, "Info", hlua_log_info);
4716 hlua_class_function(gL.T, "Warning", hlua_log_warning);
4717 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004718
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004719 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004720
4721 /*
4722 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02004723 * Register class Map
4724 *
4725 */
4726
4727 /* This table entry is the object "Map" base. */
4728 lua_newtable(gL.T);
4729
4730 /* register pattern types. */
4731 for (i=0; i<PAT_MATCH_NUM; i++)
4732 hlua_class_const_int(gL.T, pat_match_names[i], i);
4733
4734 /* register constructor. */
4735 hlua_class_function(gL.T, "new", hlua_map_new);
4736
4737 /* Create and fill the metatable. */
4738 lua_newtable(gL.T);
4739
4740 /* Create and fille the __index entry. */
4741 lua_pushstring(gL.T, "__index");
4742 lua_newtable(gL.T);
4743
4744 /* Register . */
4745 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
4746 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
4747
4748 lua_settable(gL.T, -3);
4749
4750 /* Register previous table in the registry with reference and named entry. */
4751 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4752 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4753 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_MAP); /* register class session. */
4754 class_map_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4755
4756 /* Assign the metatable to the mai Map object. */
4757 lua_setmetatable(gL.T, -2);
4758
4759 /* Set a name to the table. */
4760 lua_setglobal(gL.T, "Map");
4761
4762 /*
4763 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004764 * Register class Channel
4765 *
4766 */
4767
4768 /* Create and fill the metatable. */
4769 lua_newtable(gL.T);
4770
4771 /* Create and fille the __index entry. */
4772 lua_pushstring(gL.T, "__index");
4773 lua_newtable(gL.T);
4774
4775 /* Register . */
4776 hlua_class_function(gL.T, "get", hlua_channel_get);
4777 hlua_class_function(gL.T, "dup", hlua_channel_dup);
4778 hlua_class_function(gL.T, "getline", hlua_channel_getline);
4779 hlua_class_function(gL.T, "set", hlua_channel_set);
4780 hlua_class_function(gL.T, "append", hlua_channel_append);
4781 hlua_class_function(gL.T, "send", hlua_channel_send);
4782 hlua_class_function(gL.T, "forward", hlua_channel_forward);
4783 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
4784 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
4785
4786 lua_settable(gL.T, -3);
4787
4788 /* Register previous table in the registry with reference and named entry. */
4789 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4790 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
4791 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4792
4793 /*
4794 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004795 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004796 *
4797 */
4798
4799 /* Create and fill the metatable. */
4800 lua_newtable(gL.T);
4801
4802 /* Create and fille the __index entry. */
4803 lua_pushstring(gL.T, "__index");
4804 lua_newtable(gL.T);
4805
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004806 /* Browse existing fetches and create the associated
4807 * object method.
4808 */
4809 sf = NULL;
4810 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
4811
4812 /* Dont register the keywork if the arguments check function are
4813 * not safe during the runtime.
4814 */
4815 if ((sf->val_args != NULL) &&
4816 (sf->val_args != val_payload_lv) &&
4817 (sf->val_args != val_hdr))
4818 continue;
4819
4820 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4821 * by an underscore.
4822 */
4823 strncpy(trash.str, sf->kw, trash.size);
4824 trash.str[trash.size - 1] = '\0';
4825 for (p = trash.str; *p; p++)
4826 if (*p == '.' || *p == '-' || *p == '+')
4827 *p = '_';
4828
4829 /* Register the function. */
4830 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01004831 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004832 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
4833 lua_settable(gL.T, -3);
4834 }
4835
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004836 lua_settable(gL.T, -3);
4837
4838 /* Register previous table in the registry with reference and named entry. */
4839 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4840 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
4841 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4842
4843 /*
4844 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004845 * Register class Converters
4846 *
4847 */
4848
4849 /* Create and fill the metatable. */
4850 lua_newtable(gL.T);
4851
4852 /* Create and fill the __index entry. */
4853 lua_pushstring(gL.T, "__index");
4854 lua_newtable(gL.T);
4855
4856 /* Browse existing converters and create the associated
4857 * object method.
4858 */
4859 sc = NULL;
4860 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
4861 /* Dont register the keywork if the arguments check function are
4862 * not safe during the runtime.
4863 */
4864 if (sc->val_args != NULL)
4865 continue;
4866
4867 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4868 * by an underscore.
4869 */
4870 strncpy(trash.str, sc->kw, trash.size);
4871 trash.str[trash.size - 1] = '\0';
4872 for (p = trash.str; *p; p++)
4873 if (*p == '.' || *p == '-' || *p == '+')
4874 *p = '_';
4875
4876 /* Register the function. */
4877 lua_pushstring(gL.T, trash.str);
4878 lua_pushlightuserdata(gL.T, sc);
4879 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
4880 lua_settable(gL.T, -3);
4881 }
4882
4883 lua_settable(gL.T, -3);
4884
4885 /* Register previous table in the registry with reference and named entry. */
4886 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4887 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
4888 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4889
4890 /*
4891 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004892 * Register class HTTP
4893 *
4894 */
4895
4896 /* Create and fill the metatable. */
4897 lua_newtable(gL.T);
4898
4899 /* Create and fille the __index entry. */
4900 lua_pushstring(gL.T, "__index");
4901 lua_newtable(gL.T);
4902
4903 /* Register Lua functions. */
4904 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
4905 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
4906 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
4907 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
4908 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
4909 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
4910 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
4911 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
4912 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
4913 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
4914
4915 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
4916 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
4917 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
4918 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
4919 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
4920 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
4921
4922 lua_settable(gL.T, -3);
4923
4924 /* Register previous table in the registry with reference and named entry. */
4925 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4926 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_HTTP); /* register class session. */
4927 class_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4928
4929 /*
4930 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004931 * Register class TXN
4932 *
4933 */
4934
4935 /* Create and fill the metatable. */
4936 lua_newtable(gL.T);
4937
4938 /* Create and fille the __index entry. */
4939 lua_pushstring(gL.T, "__index");
4940 lua_newtable(gL.T);
4941
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004942 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01004943 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
4944 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004945 hlua_class_function(gL.T, "close", hlua_txn_close);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004946 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
4947 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
4948 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004949 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
4950 hlua_class_function(gL.T, "log", hlua_txn_log);
4951 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
4952 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
4953 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
4954 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004955
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004956 lua_settable(gL.T, -3);
4957
4958 /* Register previous table in the registry with reference and named entry. */
4959 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4960 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
4961 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004962
4963 /*
4964 *
4965 * Register class Socket
4966 *
4967 */
4968
4969 /* Create and fill the metatable. */
4970 lua_newtable(gL.T);
4971
4972 /* Create and fille the __index entry. */
4973 lua_pushstring(gL.T, "__index");
4974 lua_newtable(gL.T);
4975
Baptiste Assmann84bb4932015-03-02 21:40:06 +01004976#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004977 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01004978#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004979 hlua_class_function(gL.T, "connect", hlua_socket_connect);
4980 hlua_class_function(gL.T, "send", hlua_socket_send);
4981 hlua_class_function(gL.T, "receive", hlua_socket_receive);
4982 hlua_class_function(gL.T, "close", hlua_socket_close);
4983 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
4984 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
4985 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
4986 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
4987
4988 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
4989
4990 /* Register the garbage collector entry. */
4991 lua_pushstring(gL.T, "__gc");
4992 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
4993 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
4994
4995 /* Register previous table in the registry with reference and named entry. */
4996 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4997 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4998 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
4999 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
5000
5001 /* Proxy and server configuration initialisation. */
5002 memset(&socket_proxy, 0, sizeof(socket_proxy));
5003 init_new_proxy(&socket_proxy);
5004 socket_proxy.parent = NULL;
5005 socket_proxy.last_change = now.tv_sec;
5006 socket_proxy.id = "LUA-SOCKET";
5007 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
5008 socket_proxy.maxconn = 0;
5009 socket_proxy.accept = NULL;
5010 socket_proxy.options2 |= PR_O2_INDEPSTR;
5011 socket_proxy.srv = NULL;
5012 socket_proxy.conn_retries = 0;
5013 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
5014
5015 /* Init TCP server: unchanged parameters */
5016 memset(&socket_tcp, 0, sizeof(socket_tcp));
5017 socket_tcp.next = NULL;
5018 socket_tcp.proxy = &socket_proxy;
5019 socket_tcp.obj_type = OBJ_TYPE_SERVER;
5020 LIST_INIT(&socket_tcp.actconns);
5021 LIST_INIT(&socket_tcp.pendconns);
5022 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
5023 socket_tcp.last_change = 0;
5024 socket_tcp.id = "LUA-TCP-CONN";
5025 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5026 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5027 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
5028
5029 /* XXX: Copy default parameter from default server,
5030 * but the default server is not initialized.
5031 */
5032 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
5033 socket_tcp.minconn = socket_proxy.defsrv.minconn;
5034 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
5035 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
5036 socket_tcp.onerror = socket_proxy.defsrv.onerror;
5037 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5038 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
5039 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5040 socket_tcp.uweight = socket_proxy.defsrv.iweight;
5041 socket_tcp.iweight = socket_proxy.defsrv.iweight;
5042
5043 socket_tcp.check.status = HCHK_STATUS_INI;
5044 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
5045 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
5046 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
5047 socket_tcp.check.server = &socket_tcp;
5048
5049 socket_tcp.agent.status = HCHK_STATUS_INI;
5050 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
5051 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
5052 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
5053 socket_tcp.agent.server = &socket_tcp;
5054
5055 socket_tcp.xprt = &raw_sock;
5056
5057#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005058 /* Init TCP server: unchanged parameters */
5059 memset(&socket_ssl, 0, sizeof(socket_ssl));
5060 socket_ssl.next = NULL;
5061 socket_ssl.proxy = &socket_proxy;
5062 socket_ssl.obj_type = OBJ_TYPE_SERVER;
5063 LIST_INIT(&socket_ssl.actconns);
5064 LIST_INIT(&socket_ssl.pendconns);
5065 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
5066 socket_ssl.last_change = 0;
5067 socket_ssl.id = "LUA-SSL-CONN";
5068 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5069 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5070 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
5071
5072 /* XXX: Copy default parameter from default server,
5073 * but the default server is not initialized.
5074 */
5075 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
5076 socket_ssl.minconn = socket_proxy.defsrv.minconn;
5077 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
5078 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
5079 socket_ssl.onerror = socket_proxy.defsrv.onerror;
5080 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5081 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
5082 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5083 socket_ssl.uweight = socket_proxy.defsrv.iweight;
5084 socket_ssl.iweight = socket_proxy.defsrv.iweight;
5085
5086 socket_ssl.check.status = HCHK_STATUS_INI;
5087 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
5088 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
5089 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
5090 socket_ssl.check.server = &socket_ssl;
5091
5092 socket_ssl.agent.status = HCHK_STATUS_INI;
5093 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
5094 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
5095 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
5096 socket_ssl.agent.server = &socket_ssl;
5097
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005098 socket_ssl.use_ssl = 1;
5099 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005100
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005101 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005102 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
5103 /*
5104 *
5105 * If the keyword is not known, we can search in the registered
5106 * server keywords. This is usefull to configure special SSL
5107 * features like client certificates and ssl_verify.
5108 *
5109 */
5110 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
5111 if (tmp_error != 0) {
5112 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
5113 abort(); /* This must be never arrives because the command line
5114 not editable by the user. */
5115 }
5116 idx += kw->skip;
5117 }
5118 }
5119
5120 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005121 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005122#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01005123}