blob: 37fce89edfeac8b8e5a7f9de0b6c0e86b43209a5 [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>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020023#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010024#include <proto/channel.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010025#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010026#include <proto/hlua.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020027#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010028#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010029#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010030#include <proto/payload.h>
31#include <proto/proto_http.h>
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010032#include <proto/proto_tcp.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010033#include <proto/raw_sock.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010034#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010035#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020036#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020037#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010038#include <proto/ssl_sock.h>
39#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010040#include <proto/task.h>
41
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010042/* Lua uses longjmp to perform yield or throwing errors. This
43 * macro is used only for identifying the function that can
44 * not return because a longjmp is executed.
45 * __LJMP marks a prototype of hlua file that can use longjmp.
46 * WILL_LJMP() marks an lua function that will use longjmp.
47 * MAY_LJMP() marks an lua function that may use longjmp.
48 */
49#define __LJMP
50#define WILL_LJMP(func) func
51#define MAY_LJMP(func) func
52
Thierry FOURNIER380d0932015-01-23 14:27:52 +010053/* The main Lua execution context. */
54struct hlua gL;
55
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010056/* This is the memory pool containing all the signal structs. These
57 * struct are used to store each requiered signal between two tasks.
58 */
59struct pool_head *pool2_hlua_com;
60
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010061/* Used for Socket connection. */
62static struct proxy socket_proxy;
63static struct server socket_tcp;
64#ifdef USE_OPENSSL
65static struct server socket_ssl;
66#endif
67
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010068/* List head of the function called at the initialisation time. */
69struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
70
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010071/* The following variables contains the reference of the different
72 * Lua classes. These references are useful for identify metadata
73 * associated with an object.
74 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010075static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010076static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010077static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010078static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010079static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +010080static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +020081static int class_map_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010082
Thierry FOURNIERbd413492015-03-03 16:52:26 +010083/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +020084 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +010085 * short timeout. Lua linked with tasks doesn't have a timeout
86 * because a task may remain alive during all the haproxy execution.
87 */
88static unsigned int hlua_timeout_session = 4000; /* session timeout. */
89static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
90
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010091/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
92 * it is used for preventing infinite loops.
93 *
94 * I test the scheer with an infinite loop containing one incrementation
95 * and one test. I run this loop between 10 seconds, I raise a ceil of
96 * 710M loops from one interrupt each 9000 instructions, so I fix the value
97 * to one interrupt each 10 000 instructions.
98 *
99 * configured | Number of
100 * instructions | loops executed
101 * between two | in milions
102 * forced yields |
103 * ---------------+---------------
104 * 10 | 160
105 * 500 | 670
106 * 1000 | 680
107 * 5000 | 700
108 * 7000 | 700
109 * 8000 | 700
110 * 9000 | 710 <- ceil
111 * 10000 | 710
112 * 100000 | 710
113 * 1000000 | 710
114 *
115 */
116static unsigned int hlua_nb_instruction = 10000;
117
Willy Tarreau32f61e22015-03-18 17:54:59 +0100118/* Descriptor for the memory allocation state. If limit is not null, it will
119 * be enforced on any memory allocation.
120 */
121struct hlua_mem_allocator {
122 size_t allocated;
123 size_t limit;
124};
125
126static struct hlua_mem_allocator hlua_global_allocator;
127
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100128/* These functions converts types between HAProxy internal args or
129 * sample and LUA types. Another function permits to check if the
130 * LUA stack contains arguments according with an required ARG_T
131 * format.
132 */
133static int hlua_arg2lua(lua_State *L, const struct arg *arg);
134static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100135__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
136 unsigned int mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100137static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100138static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100139static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
140
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100141/* Used to check an Lua function type in the stack. It creates and
142 * returns a reference of the function. This function throws an
143 * error if the rgument is not a "function".
144 */
145__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
146{
147 if (!lua_isfunction(L, argno)) {
148 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
149 WILL_LJMP(luaL_argerror(L, argno, msg));
150 }
151 lua_pushvalue(L, argno);
152 return luaL_ref(L, LUA_REGISTRYINDEX);
153}
154
155/* The three following functions are useful for adding entries
156 * in a table. These functions takes a string and respectively an
157 * integer, a string or a function and add it to the table in the
158 * top of the stack.
159 *
160 * These functions throws an error if no more stack size is
161 * available.
162 */
163__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100164 int value)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100165{
166 if (!lua_checkstack(L, 2))
167 WILL_LJMP(luaL_error(L, "full stack"));
168 lua_pushstring(L, name);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100169 lua_pushinteger(L, value);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100170 lua_settable(L, -3);
171}
172__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
173 const char *value)
174{
175 if (!lua_checkstack(L, 2))
176 WILL_LJMP(luaL_error(L, "full stack"));
177 lua_pushstring(L, name);
178 lua_pushstring(L, value);
179 lua_settable(L, -3);
180}
181__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
182 int (*function)(lua_State *L))
183{
184 if (!lua_checkstack(L, 2))
185 WILL_LJMP(luaL_error(L, "full stack"));
186 lua_pushstring(L, name);
187 lua_pushcclosure(L, function, 0);
188 lua_settable(L, -3);
189}
190
191/* This function check the number of arguments available in the
192 * stack. If the number of arguments available is not the same
193 * then <nb> an error is throwed.
194 */
195__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
196{
197 if (lua_gettop(L) == nb)
198 return;
199 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
200}
201
202/* Return true if the data in stack[<ud>] is an object of
203 * type <class_ref>.
204 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100205static int hlua_metaistype(lua_State *L, int ud, int class_ref)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100206{
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100207 if (!lua_getmetatable(L, ud))
208 return 0;
209
210 lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
211 if (!lua_rawequal(L, -1, -2)) {
212 lua_pop(L, 2);
213 return 0;
214 }
215
216 lua_pop(L, 2);
217 return 1;
218}
219
220/* Return an object of the expected type, or throws an error. */
221__LJMP static void *hlua_checkudata(lua_State *L, int ud, int class_ref)
222{
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100223 void *p;
224
225 /* Check if the stack entry is an array. */
226 if (!lua_istable(L, ud))
227 WILL_LJMP(luaL_argerror(L, ud, NULL));
228 /* Check if the metadata have the expected type. */
229 if (!hlua_metaistype(L, ud, class_ref))
230 WILL_LJMP(luaL_argerror(L, ud, NULL));
231 /* Push on the stack at the entry [0] of the table. */
232 lua_rawgeti(L, ud, 0);
233 /* Check if this entry is userdata. */
234 p = lua_touserdata(L, -1);
235 if (!p)
236 WILL_LJMP(luaL_argerror(L, ud, NULL));
237 /* Remove the entry returned by lua_rawgeti(). */
238 lua_pop(L, 1);
239 /* Return the associated struct. */
240 return p;
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100241}
242
243/* This fucntion push an error string prefixed by the file name
244 * and the line number where the error is encountered.
245 */
246static int hlua_pusherror(lua_State *L, const char *fmt, ...)
247{
248 va_list argp;
249 va_start(argp, fmt);
250 luaL_where(L, 1);
251 lua_pushvfstring(L, fmt, argp);
252 va_end(argp);
253 lua_concat(L, 2);
254 return 1;
255}
256
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100257/* This function register a new signal. "lua" is the current lua
258 * execution context. It contains a pointer to the associated task.
259 * "link" is a list head attached to an other task that must be wake
260 * the lua task if an event occurs. This is useful with external
261 * events like TCP I/O or sleep functions. This funcion allocate
262 * memory for the signal.
263 */
264static int hlua_com_new(struct hlua *lua, struct list *link)
265{
266 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
267 if (!com)
268 return 0;
269 LIST_ADDQ(&lua->com, &com->purge_me);
270 LIST_ADDQ(link, &com->wake_me);
271 com->task = lua->task;
272 return 1;
273}
274
275/* This function purge all the pending signals when the LUA execution
276 * is finished. This prevent than a coprocess try to wake a deleted
277 * task. This function remove the memory associated to the signal.
278 */
279static void hlua_com_purge(struct hlua *lua)
280{
281 struct hlua_com *com, *back;
282
283 /* Delete all pending communication signals. */
284 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
285 LIST_DEL(&com->purge_me);
286 LIST_DEL(&com->wake_me);
287 pool_free2(pool2_hlua_com, com);
288 }
289}
290
291/* This function sends signals. It wakes all the tasks attached
292 * to a list head, and remove the signal, and free the used
293 * memory.
294 */
295static void hlua_com_wake(struct list *wake)
296{
297 struct hlua_com *com, *back;
298
299 /* Wake task and delete all pending communication signals. */
300 list_for_each_entry_safe(com, back, wake, wake_me) {
301 LIST_DEL(&com->purge_me);
302 LIST_DEL(&com->wake_me);
303 task_wakeup(com->task, TASK_WOKEN_MSG);
304 pool_free2(pool2_hlua_com, com);
305 }
306}
307
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100308/* This functions is used with sample fetch and converters. It
309 * converts the HAProxy configuration argument in a lua stack
310 * values.
311 *
312 * It takes an array of "arg", and each entry of the array is
313 * converted and pushed in the LUA stack.
314 */
315static int hlua_arg2lua(lua_State *L, const struct arg *arg)
316{
317 switch (arg->type) {
318 case ARGT_SINT:
319 lua_pushinteger(L, arg->data.sint);
320 break;
321
322 case ARGT_UINT:
323 case ARGT_TIME:
324 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100325 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100326 break;
327
328 case ARGT_STR:
329 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
330 break;
331
332 case ARGT_IPV4:
333 case ARGT_IPV6:
334 case ARGT_MSK4:
335 case ARGT_MSK6:
336 case ARGT_FE:
337 case ARGT_BE:
338 case ARGT_TAB:
339 case ARGT_SRV:
340 case ARGT_USR:
341 case ARGT_MAP:
342 default:
343 lua_pushnil(L);
344 break;
345 }
346 return 1;
347}
348
349/* This function take one entrie in an LUA stack at the index "ud",
350 * and try to convert it in an HAProxy argument entry. This is useful
351 * with sample fetch wrappers. The input arguments are gived to the
352 * lua wrapper and converted as arg list by thi function.
353 */
354static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
355{
356 switch (lua_type(L, ud)) {
357
358 case LUA_TNUMBER:
359 case LUA_TBOOLEAN:
360 arg->type = ARGT_SINT;
361 arg->data.sint = lua_tointeger(L, ud);
362 break;
363
364 case LUA_TSTRING:
365 arg->type = ARGT_STR;
366 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
367 break;
368
369 case LUA_TUSERDATA:
370 case LUA_TNIL:
371 case LUA_TTABLE:
372 case LUA_TFUNCTION:
373 case LUA_TTHREAD:
374 case LUA_TLIGHTUSERDATA:
375 arg->type = ARGT_SINT;
376 arg->data.uint = 0;
377 break;
378 }
379 return 1;
380}
381
382/* the following functions are used to convert a struct sample
383 * in Lua type. This useful to convert the return of the
384 * fetchs or converters.
385 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100386static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100387{
388 switch (smp->type) {
389 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100390 case SMP_T_BOOL:
391 case SMP_T_UINT:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100392 lua_pushinteger(L, smp->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100393 break;
394
395 case SMP_T_BIN:
396 case SMP_T_STR:
397 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
398 break;
399
400 case SMP_T_METH:
401 switch (smp->data.meth.meth) {
402 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
403 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
404 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
405 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
406 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
407 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
408 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
409 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
410 case HTTP_METH_OTHER:
411 lua_pushlstring(L, smp->data.meth.str.str, smp->data.meth.str.len);
412 break;
413 default:
414 lua_pushnil(L);
415 break;
416 }
417 break;
418
419 case SMP_T_IPV4:
420 case SMP_T_IPV6:
421 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100422 if (sample_casts[smp->type][SMP_T_STR] &&
423 sample_casts[smp->type][SMP_T_STR](smp))
424 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
425 else
426 lua_pushnil(L);
427 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100428 default:
429 lua_pushnil(L);
430 break;
431 }
432 return 1;
433}
434
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100435/* the following functions are used to convert a struct sample
436 * in Lua strings. This is useful to convert the return of the
437 * fetchs or converters.
438 */
439static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
440{
441 switch (smp->type) {
442
443 case SMP_T_BIN:
444 case SMP_T_STR:
445 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
446 break;
447
448 case SMP_T_METH:
449 switch (smp->data.meth.meth) {
450 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
451 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
452 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
453 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
454 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
455 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
456 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
457 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
458 case HTTP_METH_OTHER:
459 lua_pushlstring(L, smp->data.meth.str.str, smp->data.meth.str.len);
460 break;
461 default:
462 lua_pushstring(L, "");
463 break;
464 }
465 break;
466
467 case SMP_T_SINT:
468 case SMP_T_BOOL:
469 case SMP_T_UINT:
470 case SMP_T_IPV4:
471 case SMP_T_IPV6:
472 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
473 if (sample_casts[smp->type][SMP_T_STR] &&
474 sample_casts[smp->type][SMP_T_STR](smp))
475 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
476 else
477 lua_pushstring(L, "");
478 break;
479 default:
480 lua_pushstring(L, "");
481 break;
482 }
483 return 1;
484}
485
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100486/* the following functions are used to convert an Lua type in a
487 * struct sample. This is useful to provide data from a converter
488 * to the LUA code.
489 */
490static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
491{
492 switch (lua_type(L, ud)) {
493
494 case LUA_TNUMBER:
495 smp->type = SMP_T_SINT;
496 smp->data.sint = lua_tointeger(L, ud);
497 break;
498
499
500 case LUA_TBOOLEAN:
501 smp->type = SMP_T_BOOL;
502 smp->data.uint = lua_toboolean(L, ud);
503 break;
504
505 case LUA_TSTRING:
506 smp->type = SMP_T_STR;
507 smp->flags |= SMP_F_CONST;
508 smp->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.str.len);
509 break;
510
511 case LUA_TUSERDATA:
512 case LUA_TNIL:
513 case LUA_TTABLE:
514 case LUA_TFUNCTION:
515 case LUA_TTHREAD:
516 case LUA_TLIGHTUSERDATA:
517 smp->type = SMP_T_BOOL;
518 smp->data.uint = 0;
519 break;
520 }
521 return 1;
522}
523
524/* This function check the "argp" builded by another conversion function
525 * is in accord with the expected argp defined by the "mask". The fucntion
526 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100527 *
528 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
529 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100530 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100531__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
532 unsigned int mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100533{
534 int min_arg;
535 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100536 struct proxy *px;
537 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100538
539 idx = 0;
540 min_arg = ARGM(mask);
541 mask >>= ARGM_BITS;
542
543 while (1) {
544
545 /* Check oversize. */
546 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100547 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100548 }
549
550 /* Check for mandatory arguments. */
551 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100552 if (idx < min_arg) {
553
554 /* If miss other argument than the first one, we return an error. */
555 if (idx > 0)
556 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
557
558 /* If first argument have a certain type, some default values
559 * may be used. See the function smp_resolve_args().
560 */
561 switch (mask & ARGT_MASK) {
562
563 case ARGT_FE:
564 if (!(p->cap & PR_CAP_FE))
565 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
566 argp[idx].data.prx = p;
567 argp[idx].type = ARGT_FE;
568 argp[idx+1].type = ARGT_STOP;
569 break;
570
571 case ARGT_BE:
572 if (!(p->cap & PR_CAP_BE))
573 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
574 argp[idx].data.prx = p;
575 argp[idx].type = ARGT_BE;
576 argp[idx+1].type = ARGT_STOP;
577 break;
578
579 case ARGT_TAB:
580 argp[idx].data.prx = p;
581 argp[idx].type = ARGT_TAB;
582 argp[idx+1].type = ARGT_STOP;
583 break;
584
585 default:
586 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
587 break;
588 }
589 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100590 return 0;
591 }
592
593 /* Check for exceed the number of requiered argument. */
594 if ((mask & ARGT_MASK) == ARGT_STOP &&
595 argp[idx].type != ARGT_STOP) {
596 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
597 }
598
599 if ((mask & ARGT_MASK) == ARGT_STOP &&
600 argp[idx].type == ARGT_STOP) {
601 return 0;
602 }
603
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100604 /* Convert some argument types. */
605 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100606 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100607 if (argp[idx].type != ARGT_SINT)
608 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
609 argp[idx].type = ARGT_SINT;
610 break;
611
612 case ARGT_UINT:
613 if (argp[idx].type != ARGT_SINT)
614 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
615 argp[idx].type = ARGT_SINT;
616 break;
617
618 case ARGT_TIME:
619 if (argp[idx].type != ARGT_SINT)
620 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
621 argp[idx].type = ARGT_SINT;
622 break;
623
624 case ARGT_SIZE:
625 if (argp[idx].type != ARGT_SINT)
626 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
627 argp[idx].type = ARGT_SINT;
628 break;
629
630 case ARGT_FE:
631 if (argp[idx].type != ARGT_STR)
632 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
633 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
634 trash.str[argp[idx].data.str.len] = 0;
635 argp[idx].data.prx = findproxy(trash.str, PR_CAP_FE);
636 if (!argp[idx].data.prx)
637 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
638 argp[idx].type = ARGT_FE;
639 break;
640
641 case ARGT_BE:
642 if (argp[idx].type != ARGT_STR)
643 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
644 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
645 trash.str[argp[idx].data.str.len] = 0;
646 argp[idx].data.prx = findproxy(trash.str, PR_CAP_BE);
647 if (!argp[idx].data.prx)
648 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
649 argp[idx].type = ARGT_BE;
650 break;
651
652 case ARGT_TAB:
653 if (argp[idx].type != ARGT_STR)
654 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
655 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
656 trash.str[argp[idx].data.str.len] = 0;
657 argp[idx].data.prx = find_stktable(trash.str);
658 if (!argp[idx].data.prx)
659 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
660 argp[idx].type = ARGT_TAB;
661 break;
662
663 case ARGT_SRV:
664 if (argp[idx].type != ARGT_STR)
665 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
666 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
667 trash.str[argp[idx].data.str.len] = 0;
668 sname = strrchr(trash.str, '/');
669 if (sname) {
670 *sname++ = '\0';
671 pname = trash.str;
672 px = findproxy(pname, PR_CAP_BE);
673 if (!px)
674 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
675 }
676 else {
677 sname = trash.str;
678 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100679 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100680 argp[idx].data.srv = findserver(px, sname);
681 if (!argp[idx].data.srv)
682 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
683 argp[idx].type = ARGT_SRV;
684 break;
685
686 case ARGT_IPV4:
687 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
688 trash.str[argp[idx].data.str.len] = 0;
689 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
690 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
691 argp[idx].type = ARGT_IPV4;
692 break;
693
694 case ARGT_MSK4:
695 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
696 trash.str[argp[idx].data.str.len] = 0;
697 if (!str2mask(trash.str, &argp[idx].data.ipv4))
698 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
699 argp[idx].type = ARGT_MSK4;
700 break;
701
702 case ARGT_IPV6:
703 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
704 trash.str[argp[idx].data.str.len] = 0;
705 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
706 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
707 argp[idx].type = ARGT_IPV6;
708 break;
709
710 case ARGT_MSK6:
711 case ARGT_MAP:
712 case ARGT_REG:
713 case ARGT_USR:
714 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100715 break;
716 }
717
718 /* Check for type of argument. */
719 if ((mask & ARGT_MASK) != argp[idx].type) {
720 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
721 arg_type_names[(mask & ARGT_MASK)],
722 arg_type_names[argp[idx].type & ARGT_MASK]);
723 WILL_LJMP(luaL_argerror(L, first + idx, msg));
724 }
725
726 /* Next argument. */
727 mask >>= ARGT_BITS;
728 idx++;
729 }
730}
731
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100732/*
733 * The following functions are used to make correspondance between the the
734 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100735 *
736 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100737 * - hlua_sethlua : create the association between hlua context and lua_state.
738 */
739static inline struct hlua *hlua_gethlua(lua_State *L)
740{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100741 struct hlua **hlua = lua_getextraspace(L);
742 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100743}
744static inline void hlua_sethlua(struct hlua *hlua)
745{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100746 struct hlua **hlua_store = lua_getextraspace(hlua->T);
747 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100748}
749
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100750/* This function is used to send logs. It try to send on screen (stderr)
751 * and on the default syslog server.
752 */
753static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
754{
755 struct tm tm;
756 char *p;
757
758 /* Cleanup the log message. */
759 p = trash.str;
760 for (; *msg != '\0'; msg++, p++) {
761 if (p >= trash.str + trash.size - 1)
762 return;
763 if (isprint(*msg))
764 *p = *msg;
765 else
766 *p = '.';
767 }
768 *p = '\0';
769
770 send_log(px, level, "%s", trash.str);
771 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
772 get_localtime(date.tv_sec, &tm);
773 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
774 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
775 (int)getpid(), trash.str);
776 fflush(stderr);
777 }
778}
779
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100780/* This function just ensure that the yield will be always
781 * returned with a timeout and permit to set some flags
782 */
783__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100784 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100785{
786 struct hlua *hlua = hlua_gethlua(L);
787
788 /* Set the wake timeout. If timeout is required, we set
789 * the expiration time.
790 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100791 hlua->wake_time = tick_first(timeout, hlua->expire);
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100792
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100793 hlua->flags |= flags;
794
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100795 /* Process the yield. */
796 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
797}
798
Willy Tarreau87b09662015-04-03 00:22:06 +0200799/* This function initialises the Lua environment stored in the stream.
800 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100801 * an LUA coroutine. It can not be use to crete the main LUA context.
802 */
803int hlua_ctx_init(struct hlua *lua, struct task *task)
804{
805 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100806 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100807 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100808 lua->T = lua_newthread(gL.T);
809 if (!lua->T) {
810 lua->Tref = LUA_REFNIL;
811 return 0;
812 }
813 hlua_sethlua(lua);
814 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
815 lua->task = task;
816 return 1;
817}
818
Willy Tarreau87b09662015-04-03 00:22:06 +0200819/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100820 * is destroyed. The destroy also the memory context. The struct "lua"
821 * is not freed.
822 */
823void hlua_ctx_destroy(struct hlua *lua)
824{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100825 if (!lua->T)
826 return;
827
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100828 /* Purge all the pending signals. */
829 hlua_com_purge(lua);
830
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100831 /* The thread is garbage collected by Lua. */
832 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
833 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
834}
835
836/* This function is used to restore the Lua context when a coroutine
837 * fails. This function copy the common memory between old coroutine
838 * and the new coroutine. The old coroutine is destroyed, and its
839 * replaced by the new coroutine.
840 * If the flag "keep_msg" is set, the last entry of the old is assumed
841 * as string error message and it is copied in the new stack.
842 */
843static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
844{
845 lua_State *T;
846 int new_ref;
847
848 /* Renew the main LUA stack doesn't have sense. */
849 if (lua == &gL)
850 return 0;
851
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100852 /* New Lua coroutine. */
853 T = lua_newthread(gL.T);
854 if (!T)
855 return 0;
856
857 /* Copy last error message. */
858 if (keep_msg)
859 lua_xmove(lua->T, T, 1);
860
861 /* Copy data between the coroutines. */
862 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
863 lua_xmove(lua->T, T, 1);
864 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
865
866 /* Destroy old data. */
867 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
868
869 /* The thread is garbage collected by Lua. */
870 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
871
872 /* Fill the struct with the new coroutine values. */
873 lua->Mref = new_ref;
874 lua->T = T;
875 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
876
877 /* Set context. */
878 hlua_sethlua(lua);
879
880 return 1;
881}
882
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100883void hlua_hook(lua_State *L, lua_Debug *ar)
884{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100885 struct hlua *hlua = hlua_gethlua(L);
886
887 /* Lua cannot yield when its returning from a function,
888 * so, we can fix the interrupt hook to 1 instruction,
889 * expecting that the function is finnished.
890 */
891 if (lua_gethookmask(L) & LUA_MASKRET) {
892 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
893 return;
894 }
895
896 /* restore the interrupt condition. */
897 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
898
899 /* If we interrupt the Lua processing in yieldable state, we yield.
900 * If the state is not yieldable, trying yield causes an error.
901 */
902 if (lua_isyieldable(L))
903 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
904
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +0100905 /* If we cannot yield, update the clock and check the timeout. */
906 tv_update_date(0, 1);
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100907 if (tick_is_expired(hlua->expire, now_ms)) {
908 lua_pushfstring(L, "execution timeout");
909 WILL_LJMP(lua_error(L));
910 }
911
912 /* Try to interrupt the process at the end of the current
913 * unyieldable function.
914 */
915 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100916}
917
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100918/* This function start or resumes the Lua stack execution. If the flag
919 * "yield_allowed" if no set and the LUA stack execution returns a yield
920 * The function return an error.
921 *
922 * The function can returns 4 values:
923 * - HLUA_E_OK : The execution is terminated without any errors.
924 * - HLUA_E_AGAIN : The execution must continue at the next associated
925 * task wakeup.
926 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
927 * the top of the stack.
928 * - HLUA_E_ERR : An error has occured without error message.
929 *
930 * If an error occured, the stack is renewed and it is ready to run new
931 * LUA code.
932 */
933static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
934{
935 int ret;
936 const char *msg;
937
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100938 HLUA_SET_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100939
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100940 /* If we want to resume the task, then check first the execution timeout.
941 * if it is reached, we can interrupt the Lua processing.
942 */
943 if (tick_is_expired(lua->expire, now_ms))
944 goto timeout_reached;
945
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100946resume_execution:
947
948 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
949 * instructions. it is used for preventing infinite loops.
950 */
951 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
952
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +0100953 /* Remove all flags except the running flags. */
954 lua->flags = HLUA_RUN;
955
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100956 /* Call the function. */
957 ret = lua_resume(lua->T, gL.T, lua->nargs);
958 switch (ret) {
959
960 case LUA_OK:
961 ret = HLUA_E_OK;
962 break;
963
964 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100965 /* Check if the execution timeout is expired. It it is the case, we
966 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100967 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100968 if (tick_is_expired(lua->expire, now_ms)) {
969
970timeout_reached:
971
972 lua_settop(lua->T, 0); /* Empty the stack. */
973 if (!lua_checkstack(lua->T, 1)) {
974 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100975 break;
976 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100977 lua_pushfstring(lua->T, "execution timeout");
978 ret = HLUA_E_ERRMSG;
979 break;
980 }
981 /* Process the forced yield. if the general yield is not allowed or
982 * if no task were associated this the current Lua execution
983 * coroutine, we resume the execution. Else we want to return in the
984 * scheduler and we want to be waked up again, to continue the
985 * current Lua execution. So we schedule our own task.
986 */
987 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100988 if (!yield_allowed || !lua->task)
989 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100990 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100991 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100992 if (!yield_allowed) {
993 lua_settop(lua->T, 0); /* Empty the stack. */
994 if (!lua_checkstack(lua->T, 1)) {
995 ret = HLUA_E_ERR;
996 break;
997 }
998 lua_pushfstring(lua->T, "yield not allowed");
999 ret = HLUA_E_ERRMSG;
1000 break;
1001 }
1002 ret = HLUA_E_AGAIN;
1003 break;
1004
1005 case LUA_ERRRUN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001006 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001007 if (!lua_checkstack(lua->T, 1)) {
1008 ret = HLUA_E_ERR;
1009 break;
1010 }
1011 msg = lua_tostring(lua->T, -1);
1012 lua_settop(lua->T, 0); /* Empty the stack. */
1013 lua_pop(lua->T, 1);
1014 if (msg)
1015 lua_pushfstring(lua->T, "runtime error: %s", msg);
1016 else
1017 lua_pushfstring(lua->T, "unknown runtime error");
1018 ret = HLUA_E_ERRMSG;
1019 break;
1020
1021 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001022 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001023 lua_settop(lua->T, 0); /* Empty the stack. */
1024 if (!lua_checkstack(lua->T, 1)) {
1025 ret = HLUA_E_ERR;
1026 break;
1027 }
1028 lua_pushfstring(lua->T, "out of memory error");
1029 ret = HLUA_E_ERRMSG;
1030 break;
1031
1032 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001033 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001034 if (!lua_checkstack(lua->T, 1)) {
1035 ret = HLUA_E_ERR;
1036 break;
1037 }
1038 msg = lua_tostring(lua->T, -1);
1039 lua_settop(lua->T, 0); /* Empty the stack. */
1040 lua_pop(lua->T, 1);
1041 if (msg)
1042 lua_pushfstring(lua->T, "message handler error: %s", msg);
1043 else
1044 lua_pushfstring(lua->T, "message handler error");
1045 ret = HLUA_E_ERRMSG;
1046 break;
1047
1048 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001049 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001050 lua_settop(lua->T, 0); /* Empty the stack. */
1051 if (!lua_checkstack(lua->T, 1)) {
1052 ret = HLUA_E_ERR;
1053 break;
1054 }
1055 lua_pushfstring(lua->T, "unknonwn error");
1056 ret = HLUA_E_ERRMSG;
1057 break;
1058 }
1059
1060 switch (ret) {
1061 case HLUA_E_AGAIN:
1062 break;
1063
1064 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001065 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001066 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001067 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001068 break;
1069
1070 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001071 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001072 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001073 hlua_ctx_renew(lua, 0);
1074 break;
1075
1076 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001077 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001078 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001079 break;
1080 }
1081
1082 return ret;
1083}
1084
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001085/* This function is an LUA binding. It provides a function
1086 * for deleting ACL from a referenced ACL file.
1087 */
1088__LJMP static int hlua_del_acl(lua_State *L)
1089{
1090 const char *name;
1091 const char *key;
1092 struct pat_ref *ref;
1093
1094 MAY_LJMP(check_args(L, 2, "del_acl"));
1095
1096 name = MAY_LJMP(luaL_checkstring(L, 1));
1097 key = MAY_LJMP(luaL_checkstring(L, 2));
1098
1099 ref = pat_ref_lookup(name);
1100 if (!ref)
1101 WILL_LJMP(luaL_error(L, "'del_acl': unkown acl file '%s'", name));
1102
1103 pat_ref_delete(ref, key);
1104 return 0;
1105}
1106
1107/* This function is an LUA binding. It provides a function
1108 * for deleting map entry from a referenced map file.
1109 */
1110static int hlua_del_map(lua_State *L)
1111{
1112 const char *name;
1113 const char *key;
1114 struct pat_ref *ref;
1115
1116 MAY_LJMP(check_args(L, 2, "del_map"));
1117
1118 name = MAY_LJMP(luaL_checkstring(L, 1));
1119 key = MAY_LJMP(luaL_checkstring(L, 2));
1120
1121 ref = pat_ref_lookup(name);
1122 if (!ref)
1123 WILL_LJMP(luaL_error(L, "'del_map': unkown acl file '%s'", name));
1124
1125 pat_ref_delete(ref, key);
1126 return 0;
1127}
1128
1129/* This function is an LUA binding. It provides a function
1130 * for adding ACL pattern from a referenced ACL file.
1131 */
1132static int hlua_add_acl(lua_State *L)
1133{
1134 const char *name;
1135 const char *key;
1136 struct pat_ref *ref;
1137
1138 MAY_LJMP(check_args(L, 2, "add_acl"));
1139
1140 name = MAY_LJMP(luaL_checkstring(L, 1));
1141 key = MAY_LJMP(luaL_checkstring(L, 2));
1142
1143 ref = pat_ref_lookup(name);
1144 if (!ref)
1145 WILL_LJMP(luaL_error(L, "'add_acl': unkown acl file '%s'", name));
1146
1147 if (pat_ref_find_elt(ref, key) == NULL)
1148 pat_ref_add(ref, key, NULL, NULL);
1149 return 0;
1150}
1151
1152/* This function is an LUA binding. It provides a function
1153 * for setting map pattern and sample from a referenced map
1154 * file.
1155 */
1156static int hlua_set_map(lua_State *L)
1157{
1158 const char *name;
1159 const char *key;
1160 const char *value;
1161 struct pat_ref *ref;
1162
1163 MAY_LJMP(check_args(L, 3, "set_map"));
1164
1165 name = MAY_LJMP(luaL_checkstring(L, 1));
1166 key = MAY_LJMP(luaL_checkstring(L, 2));
1167 value = MAY_LJMP(luaL_checkstring(L, 3));
1168
1169 ref = pat_ref_lookup(name);
1170 if (!ref)
1171 WILL_LJMP(luaL_error(L, "'set_map': unkown map file '%s'", name));
1172
1173 if (pat_ref_find_elt(ref, key) != NULL)
1174 pat_ref_set(ref, key, value, NULL);
1175 else
1176 pat_ref_add(ref, key, value, NULL);
1177 return 0;
1178}
1179
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001180/* A class is a lot of memory that contain data. This data can be a table,
1181 * an integer or user data. This data is associated with a metatable. This
1182 * metatable have an original version registred in the global context with
1183 * the name of the object (_G[<name>] = <metable> ).
1184 *
1185 * A metable is a table that modify the standard behavior of a standard
1186 * access to the associated data. The entries of this new metatable are
1187 * defined as is:
1188 *
1189 * http://lua-users.org/wiki/MetatableEvents
1190 *
1191 * __index
1192 *
1193 * we access an absent field in a table, the result is nil. This is
1194 * true, but it is not the whole truth. Actually, such access triggers
1195 * the interpreter to look for an __index metamethod: If there is no
1196 * such method, as usually happens, then the access results in nil;
1197 * otherwise, the metamethod will provide the result.
1198 *
1199 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1200 * the key does not appear in the table, but the metatable has an __index
1201 * property:
1202 *
1203 * - if the value is a function, the function is called, passing in the
1204 * table and the key; the return value of that function is returned as
1205 * the result.
1206 *
1207 * - if the value is another table, the value of the key in that table is
1208 * asked for and returned (and if it doesn't exist in that table, but that
1209 * table's metatable has an __index property, then it continues on up)
1210 *
1211 * - Use "rawget(myTable,key)" to skip this metamethod.
1212 *
1213 * http://www.lua.org/pil/13.4.1.html
1214 *
1215 * __newindex
1216 *
1217 * Like __index, but control property assignment.
1218 *
1219 * __mode - Control weak references. A string value with one or both
1220 * of the characters 'k' and 'v' which specifies that the the
1221 * keys and/or values in the table are weak references.
1222 *
1223 * __call - Treat a table like a function. When a table is followed by
1224 * parenthesis such as "myTable( 'foo' )" and the metatable has
1225 * a __call key pointing to a function, that function is invoked
1226 * (passing any specified arguments) and the return value is
1227 * returned.
1228 *
1229 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1230 * called, if the metatable for myTable has a __metatable
1231 * key, the value of that key is returned instead of the
1232 * actual metatable.
1233 *
1234 * __tostring - Control string representation. When the builtin
1235 * "tostring( myTable )" function is called, if the metatable
1236 * for myTable has a __tostring property set to a function,
1237 * that function is invoked (passing myTable to it) and the
1238 * return value is used as the string representation.
1239 *
1240 * __len - Control table length. When the table length is requested using
1241 * the length operator ( '#' ), if the metatable for myTable has
1242 * a __len key pointing to a function, that function is invoked
1243 * (passing myTable to it) and the return value used as the value
1244 * of "#myTable".
1245 *
1246 * __gc - Userdata finalizer code. When userdata is set to be garbage
1247 * collected, if the metatable has a __gc field pointing to a
1248 * function, that function is first invoked, passing the userdata
1249 * to it. The __gc metamethod is not called for tables.
1250 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1251 *
1252 * Special metamethods for redefining standard operators:
1253 * http://www.lua.org/pil/13.1.html
1254 *
1255 * __add "+"
1256 * __sub "-"
1257 * __mul "*"
1258 * __div "/"
1259 * __unm "!"
1260 * __pow "^"
1261 * __concat ".."
1262 *
1263 * Special methods for redfining standar relations
1264 * http://www.lua.org/pil/13.2.html
1265 *
1266 * __eq "=="
1267 * __lt "<"
1268 * __le "<="
1269 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001270
1271/*
1272 *
1273 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001274 * Class Map
1275 *
1276 *
1277 */
1278
1279/* Returns a struct hlua_map if the stack entry "ud" is
1280 * a class session, otherwise it throws an error.
1281 */
1282__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1283{
1284 return (struct map_descriptor *)MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
1285}
1286
1287/* This function is the map constructor. It don't need
1288 * the class Map object. It creates and return a new Map
1289 * object. It must be called only during "body" or "init"
1290 * context because it process some filesystem accesses.
1291 */
1292__LJMP static int hlua_map_new(struct lua_State *L)
1293{
1294 const char *fn;
1295 int match = PAT_MATCH_STR;
1296 struct sample_conv conv;
1297 const char *file = "";
1298 int line = 0;
1299 lua_Debug ar;
1300 char *err = NULL;
1301 struct arg args[2];
1302
1303 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1304 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1305
1306 fn = MAY_LJMP(luaL_checkstring(L, 1));
1307
1308 if (lua_gettop(L) >= 2) {
1309 match = MAY_LJMP(luaL_checkinteger(L, 2));
1310 if (match < 0 || match >= PAT_MATCH_NUM)
1311 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1312 }
1313
1314 /* Get Lua filename and line number. */
1315 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1316 lua_getinfo(L, "Sl", &ar); /* get info about it */
1317 if (ar.currentline > 0) { /* is there info? */
1318 file = ar.short_src;
1319 line = ar.currentline;
1320 }
1321 }
1322
1323 /* fill fake sample_conv struct. */
1324 conv.kw = ""; /* unused. */
1325 conv.process = NULL; /* unused. */
1326 conv.arg_mask = 0; /* unused. */
1327 conv.val_args = NULL; /* unused. */
1328 conv.out_type = SMP_T_STR;
1329 conv.private = (void *)(long)match;
1330 switch (match) {
1331 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1332 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1333 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1334 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1335 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1336 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1337 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
1338 case PAT_MATCH_INT: conv.in_type = SMP_T_UINT; break;
1339 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1340 default:
1341 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1342 }
1343
1344 /* fill fake args. */
1345 args[0].type = ARGT_STR;
1346 args[0].data.str.str = (char *)fn;
1347 args[1].type = ARGT_STOP;
1348
1349 /* load the map. */
1350 if (!sample_load_map(args, &conv, file, line, &err)) {
1351 /* error case: we cant use luaL_error because we must
1352 * free the err variable.
1353 */
1354 luaL_where(L, 1);
1355 lua_pushfstring(L, "'new': %s.", err);
1356 lua_concat(L, 2);
1357 free(err);
1358 WILL_LJMP(lua_error(L));
1359 }
1360
1361 /* create the lua object. */
1362 lua_newtable(L);
1363 lua_pushlightuserdata(L, args[0].data.map);
1364 lua_rawseti(L, -2, 0);
1365
1366 /* Pop a class Map metatable and affect it to the userdata. */
1367 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1368 lua_setmetatable(L, -2);
1369
1370
1371 return 1;
1372}
1373
1374__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1375{
1376 struct map_descriptor *desc;
1377 struct pattern *pat;
1378 struct sample smp;
1379
1380 MAY_LJMP(check_args(L, 2, "lookup"));
1381 desc = MAY_LJMP(hlua_checkmap(L, 1));
1382 if (desc->pat.expect_type == SMP_T_UINT) {
1383 smp.type = SMP_T_UINT;
1384 smp.data.uint = MAY_LJMP(luaL_checkinteger(L, 2));
1385 }
1386 else {
1387 smp.type = SMP_T_STR;
1388 smp.flags = SMP_F_CONST;
1389 smp.data.str.str = (char *)MAY_LJMP(luaL_checklstring(L, 2, (size_t *)&smp.data.str.len));
1390 }
1391
1392 pat = pattern_exec_match(&desc->pat, &smp, 1);
1393 if (!pat || !pat->smp) {
1394 if (str)
1395 lua_pushstring(L, "");
1396 else
1397 lua_pushnil(L);
1398 return 1;
1399 }
1400
1401 /* The Lua pattern must return a string, so we can't check the returned type */
1402 lua_pushlstring(L, pat->smp->data.str.str, pat->smp->data.str.len);
1403 return 1;
1404}
1405
1406__LJMP static int hlua_map_lookup(struct lua_State *L)
1407{
1408 return _hlua_map_lookup(L, 0);
1409}
1410
1411__LJMP static int hlua_map_slookup(struct lua_State *L)
1412{
1413 return _hlua_map_lookup(L, 1);
1414}
1415
1416/*
1417 *
1418 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001419 * Class Socket
1420 *
1421 *
1422 */
1423
1424__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1425{
1426 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1427}
1428
1429/* This function is the handler called for each I/O on the established
1430 * connection. It is used for notify space avalaible to send or data
1431 * received.
1432 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001433static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001434{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001435 struct stream_interface *si = appctx->owner;
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001436 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001437
Willy Tarreau87b09662015-04-03 00:22:06 +02001438 /* Wakeup the main stream if the client connection is closed. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001439 if (!c || channel_output_closed(si_ic(si)) || channel_input_closed(si_oc(si))) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001440 if (appctx->ctx.hlua.socket) {
1441 appctx->ctx.hlua.socket->s = NULL;
1442 appctx->ctx.hlua.socket = NULL;
1443 }
1444 si_shutw(si);
1445 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001446 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001447 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1448 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001449 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001450 }
1451
1452 if (!(c->flags & CO_FL_CONNECTED))
Willy Tarreaud4da1962015-04-20 01:31:23 +02001453 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001454
1455 /* This function is called after the connect. */
1456 appctx->ctx.hlua.connected = 1;
1457
1458 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001459 if (channel_may_recv(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001460 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1461
1462 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001463 if (channel_is_empty(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001464 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1465}
1466
Willy Tarreau87b09662015-04-03 00:22:06 +02001467/* This function is called when the "struct stream" is destroyed.
1468 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001469 * Wake all the pending signals.
1470 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001471static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001472{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001473 /* Remove my link in the original object. */
1474 if (appctx->ctx.hlua.socket)
1475 appctx->ctx.hlua.socket->s = NULL;
1476
1477 /* Wake all the task waiting for me. */
1478 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1479 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1480}
1481
1482/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001483 * uses this object. If the stream does not exists, just quit.
1484 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001485 * pending signal can rest in the read and write lists. destroy
1486 * it.
1487 */
1488__LJMP static int hlua_socket_gc(lua_State *L)
1489{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001490 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001491 struct appctx *appctx;
1492
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001493 MAY_LJMP(check_args(L, 1, "__gc"));
1494
1495 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001496 if (!socket->s)
1497 return 0;
1498
Willy Tarreau87b09662015-04-03 00:22:06 +02001499 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001500 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaue7dff022015-04-03 01:14:29 +02001501 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001502 socket->s = NULL;
1503 appctx->ctx.hlua.socket = NULL;
1504
1505 return 0;
1506}
1507
1508/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001509 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001510 */
1511__LJMP static int hlua_socket_close(lua_State *L)
1512{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001513 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001514 struct appctx *appctx;
1515
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001516 MAY_LJMP(check_args(L, 1, "close"));
1517
1518 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001519 if (!socket->s)
1520 return 0;
1521
Willy Tarreau87b09662015-04-03 00:22:06 +02001522 /* Close the stream and remove the associated stop task. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02001523 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001524 appctx = objt_appctx(socket->s->si[0].end);
1525 appctx->ctx.hlua.socket = NULL;
1526 socket->s = NULL;
1527
1528 return 0;
1529}
1530
1531/* This Lua function assumes that the stack contain three parameters.
1532 * 1 - USERDATA containing a struct socket
1533 * 2 - INTEGER with values of the macro defined below
1534 * If the integer is -1, we must read at most one line.
1535 * If the integer is -2, we ust read all the data until the
1536 * end of the stream.
1537 * If the integer is positive value, we must read a number of
1538 * bytes corresponding to this value.
1539 */
1540#define HLSR_READ_LINE (-1)
1541#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001542__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001543{
1544 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1545 int wanted = lua_tointeger(L, 2);
1546 struct hlua *hlua = hlua_gethlua(L);
1547 struct appctx *appctx;
1548 int len;
1549 int nblk;
1550 char *blk1;
1551 int len1;
1552 char *blk2;
1553 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001554 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001555 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001556
1557 /* Check if this lua stack is schedulable. */
1558 if (!hlua || !hlua->task)
1559 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1560 "'frontend', 'backend' or 'task'"));
1561
1562 /* check for connection closed. If some data where read, return it. */
1563 if (!socket->s)
1564 goto connection_closed;
1565
Willy Tarreau94aa6172015-03-13 14:19:06 +01001566 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001567 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001568 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001569 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001570 if (nblk < 0) /* Connection close. */
1571 goto connection_closed;
1572 if (nblk == 0) /* No data avalaible. */
1573 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001574
1575 /* remove final \r\n. */
1576 if (nblk == 1) {
1577 if (blk1[len1-1] == '\n') {
1578 len1--;
1579 skip_at_end++;
1580 if (blk1[len1-1] == '\r') {
1581 len1--;
1582 skip_at_end++;
1583 }
1584 }
1585 }
1586 else {
1587 if (blk2[len2-1] == '\n') {
1588 len2--;
1589 skip_at_end++;
1590 if (blk2[len2-1] == '\r') {
1591 len2--;
1592 skip_at_end++;
1593 }
1594 }
1595 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001596 }
1597
1598 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001599 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001600 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001601 if (nblk < 0) /* Connection close. */
1602 goto connection_closed;
1603 if (nblk == 0) /* No data avalaible. */
1604 goto connection_empty;
1605 }
1606
1607 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001608 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001609 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001610 if (nblk < 0) /* Connection close. */
1611 goto connection_closed;
1612 if (nblk == 0) /* No data avalaible. */
1613 goto connection_empty;
1614
1615 if (len1 > wanted) {
1616 nblk = 1;
1617 len1 = wanted;
1618 } if (nblk == 2 && len1 + len2 > wanted)
1619 len2 = wanted - len1;
1620 }
1621
1622 len = len1;
1623
1624 luaL_addlstring(&socket->b, blk1, len1);
1625 if (nblk == 2) {
1626 len += len2;
1627 luaL_addlstring(&socket->b, blk2, len2);
1628 }
1629
1630 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001631 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001632
1633 /* Don't wait anything. */
Willy Tarreau828824a2015-04-19 17:20:03 +02001634 si_applet_done(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001635
1636 /* If the pattern reclaim to read all the data
1637 * in the connection, got out.
1638 */
1639 if (wanted == HLSR_READ_ALL)
1640 goto connection_empty;
1641 else if (wanted >= 0 && len < wanted)
1642 goto connection_empty;
1643
1644 /* Return result. */
1645 luaL_pushresult(&socket->b);
1646 return 1;
1647
1648connection_closed:
1649
1650 /* If the buffer containds data. */
1651 if (socket->b.n > 0) {
1652 luaL_pushresult(&socket->b);
1653 return 1;
1654 }
1655 lua_pushnil(L);
1656 lua_pushstring(L, "connection closed.");
1657 return 2;
1658
1659connection_empty:
1660
1661 appctx = objt_appctx(socket->s->si[0].end);
1662 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1663 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001664 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001665 return 0;
1666}
1667
1668/* This Lus function gets two parameters. The first one can be string
1669 * or a number. If the string is "*l", the user require one line. If
1670 * the string is "*a", the user require all the content of the stream.
1671 * If the value is a number, the user require a number of bytes equal
1672 * to the value. The default value is "*l" (a line).
1673 *
1674 * This paraeter with a variable type is converted in integer. This
1675 * integer takes this values:
1676 * -1 : read a line
1677 * -2 : read all the stream
1678 * >0 : amount if bytes.
1679 *
1680 * The second parameter is optinal. It contains a string that must be
1681 * concatenated with the read data.
1682 */
1683__LJMP static int hlua_socket_receive(struct lua_State *L)
1684{
1685 int wanted = HLSR_READ_LINE;
1686 const char *pattern;
1687 int type;
1688 char *error;
1689 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001690 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001691
1692 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1693 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1694
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001695 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001696
1697 /* check for pattern. */
1698 if (lua_gettop(L) >= 2) {
1699 type = lua_type(L, 2);
1700 if (type == LUA_TSTRING) {
1701 pattern = lua_tostring(L, 2);
1702 if (strcmp(pattern, "*a") == 0)
1703 wanted = HLSR_READ_ALL;
1704 else if (strcmp(pattern, "*l") == 0)
1705 wanted = HLSR_READ_LINE;
1706 else {
1707 wanted = strtoll(pattern, &error, 10);
1708 if (*error != '\0')
1709 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1710 }
1711 }
1712 else if (type == LUA_TNUMBER) {
1713 wanted = lua_tointeger(L, 2);
1714 if (wanted < 0)
1715 WILL_LJMP(luaL_error(L, "Unsupported size."));
1716 }
1717 }
1718
1719 /* Set pattern. */
1720 lua_pushinteger(L, wanted);
1721 lua_replace(L, 2);
1722
1723 /* init bufffer, and fiil it wih prefix. */
1724 luaL_buffinit(L, &socket->b);
1725
1726 /* Check prefix. */
1727 if (lua_gettop(L) >= 3) {
1728 if (lua_type(L, 3) != LUA_TSTRING)
1729 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1730 pattern = lua_tolstring(L, 3, &len);
1731 luaL_addlstring(&socket->b, pattern, len);
1732 }
1733
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001734 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001735}
1736
1737/* Write the Lua input string in the output buffer.
1738 * This fucntion returns a yield if no space are available.
1739 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001740static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001741{
1742 struct hlua_socket *socket;
1743 struct hlua *hlua = hlua_gethlua(L);
1744 struct appctx *appctx;
1745 size_t buf_len;
1746 const char *buf;
1747 int len;
1748 int send_len;
1749 int sent;
1750
1751 /* Check if this lua stack is schedulable. */
1752 if (!hlua || !hlua->task)
1753 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1754 "'frontend', 'backend' or 'task'"));
1755
1756 /* Get object */
1757 socket = MAY_LJMP(hlua_checksocket(L, 1));
1758 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001759 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001760
1761 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001762 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001763 lua_pushinteger(L, -1);
1764 return 1;
1765 }
1766
1767 /* Update the input buffer data. */
1768 buf += sent;
1769 send_len = buf_len - sent;
1770
1771 /* All the data are sent. */
1772 if (sent >= buf_len)
1773 return 1; /* Implicitly return the length sent. */
1774
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001775 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1776 * the request buffer if its not required.
1777 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001778 if (socket->s->req.buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02001779 if (!stream_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001780 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001781 goto hlua_socket_write_yield_return;
1782 }
1783 }
1784
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001785 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001786 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001787 if (len <= 0)
1788 goto hlua_socket_write_yield_return;
1789
1790 /* send data */
1791 if (len < send_len)
1792 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001793 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001794
1795 /* "Not enough space" (-1), "Buffer too little to contain
1796 * the data" (-2) are not expected because the available length
1797 * is tested.
1798 * Other unknown error are also not expected.
1799 */
1800 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001801 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001802 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001803
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001804 MAY_LJMP(hlua_socket_close(L));
1805 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001806 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001807 return 1;
1808 }
1809
1810 /* update buffers. */
Willy Tarreau828824a2015-04-19 17:20:03 +02001811 si_applet_done(&socket->s->si[0]);
Willy Tarreau94aa6172015-03-13 14:19:06 +01001812 socket->s->req.rex = TICK_ETERNITY;
1813 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001814
1815 /* Update length sent. */
1816 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001817 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001818
1819 /* All the data buffer is sent ? */
1820 if (sent + len >= buf_len)
1821 return 1;
1822
1823hlua_socket_write_yield_return:
1824 appctx = objt_appctx(socket->s->si[0].end);
1825 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1826 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001827 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001828 return 0;
1829}
1830
1831/* This function initiate the send of data. It just check the input
1832 * parameters and push an integer in the Lua stack that contain the
1833 * amount of data writed in the buffer. This is used by the function
1834 * "hlua_socket_write_yield" that can yield.
1835 *
1836 * The Lua function gets between 3 and 4 parameters. The first one is
1837 * the associated object. The second is a string buffer. The third is
1838 * a facultative integer that represents where is the buffer position
1839 * of the start of the data that can send. The first byte is the
1840 * position "1". The default value is "1". The fourth argument is a
1841 * facultative integer that represents where is the buffer position
1842 * of the end of the data that can send. The default is the last byte.
1843 */
1844static int hlua_socket_send(struct lua_State *L)
1845{
1846 int i;
1847 int j;
1848 const char *buf;
1849 size_t buf_len;
1850
1851 /* Check number of arguments. */
1852 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1853 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1854
1855 /* Get the string. */
1856 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1857
1858 /* Get and check j. */
1859 if (lua_gettop(L) == 4) {
1860 j = MAY_LJMP(luaL_checkinteger(L, 4));
1861 if (j < 0)
1862 j = buf_len + j + 1;
1863 if (j > buf_len)
1864 j = buf_len + 1;
1865 lua_pop(L, 1);
1866 }
1867 else
1868 j = buf_len;
1869
1870 /* Get and check i. */
1871 if (lua_gettop(L) == 3) {
1872 i = MAY_LJMP(luaL_checkinteger(L, 3));
1873 if (i < 0)
1874 i = buf_len + i + 1;
1875 if (i > buf_len)
1876 i = buf_len + 1;
1877 lua_pop(L, 1);
1878 } else
1879 i = 1;
1880
1881 /* Check bth i and j. */
1882 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001883 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001884 return 1;
1885 }
1886 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001887 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001888 return 1;
1889 }
1890 if (i == 0)
1891 i = 1;
1892 if (j == 0)
1893 j = 1;
1894
1895 /* Pop the string. */
1896 lua_pop(L, 1);
1897
1898 /* Update the buffer length. */
1899 buf += i - 1;
1900 buf_len = j - i + 1;
1901 lua_pushlstring(L, buf, buf_len);
1902
1903 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001904 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001905
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001906 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001907}
1908
1909#define SOCKET_INFO_EXPANDED_FORM "[0000:0000:0000:0000:0000:0000:0000:0000]:12345"
1910static char _socket_info_expanded_form[] = SOCKET_INFO_EXPANDED_FORM;
1911#define SOCKET_INFO_MAX_LEN (sizeof(_socket_info_expanded_form))
1912__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
1913{
1914 static char buffer[SOCKET_INFO_MAX_LEN];
1915 int ret;
1916 int len;
1917 char *p;
1918
1919 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
1920 if (ret <= 0) {
1921 lua_pushnil(L);
1922 return 1;
1923 }
1924
1925 if (ret == AF_UNIX) {
1926 lua_pushstring(L, buffer+1);
1927 return 1;
1928 }
1929 else if (ret == AF_INET6) {
1930 buffer[0] = '[';
1931 len = strlen(buffer);
1932 buffer[len] = ']';
1933 len++;
1934 buffer[len] = ':';
1935 len++;
1936 p = buffer;
1937 }
1938 else if (ret == AF_INET) {
1939 p = buffer + 1;
1940 len = strlen(p);
1941 p[len] = ':';
1942 len++;
1943 }
1944 else {
1945 lua_pushnil(L);
1946 return 1;
1947 }
1948
1949 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
1950 lua_pushnil(L);
1951 return 1;
1952 }
1953
1954 lua_pushstring(L, p);
1955 return 1;
1956}
1957
1958/* Returns information about the peer of the connection. */
1959__LJMP static int hlua_socket_getpeername(struct lua_State *L)
1960{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001961 struct hlua_socket *socket;
1962 struct connection *conn;
1963
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001964 MAY_LJMP(check_args(L, 1, "getpeername"));
1965
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001966 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001967
1968 /* Check if the tcp object is avalaible. */
1969 if (!socket->s) {
1970 lua_pushnil(L);
1971 return 1;
1972 }
1973
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001974 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001975 if (!conn) {
1976 lua_pushnil(L);
1977 return 1;
1978 }
1979
1980 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
1981 unsigned int salen = sizeof(conn->addr.to);
1982 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
1983 lua_pushnil(L);
1984 return 1;
1985 }
1986 conn->flags |= CO_FL_ADDR_TO_SET;
1987 }
1988
1989 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
1990}
1991
1992/* Returns information about my connection side. */
1993static int hlua_socket_getsockname(struct lua_State *L)
1994{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001995 struct hlua_socket *socket;
1996 struct connection *conn;
1997
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001998 MAY_LJMP(check_args(L, 1, "getsockname"));
1999
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002000 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002001
2002 /* Check if the tcp object is avalaible. */
2003 if (!socket->s) {
2004 lua_pushnil(L);
2005 return 1;
2006 }
2007
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002008 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002009 if (!conn) {
2010 lua_pushnil(L);
2011 return 1;
2012 }
2013
2014 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
2015 unsigned int salen = sizeof(conn->addr.from);
2016 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
2017 lua_pushnil(L);
2018 return 1;
2019 }
2020 conn->flags |= CO_FL_ADDR_FROM_SET;
2021 }
2022
2023 return hlua_socket_info(L, &conn->addr.from);
2024}
2025
2026/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002027static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002028 .obj_type = OBJ_TYPE_APPLET,
2029 .name = "<LUA_TCP>",
2030 .fct = hlua_socket_handler,
2031 .release = hlua_socket_release,
2032};
2033
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002034__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002035{
2036 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2037 struct hlua *hlua = hlua_gethlua(L);
2038 struct appctx *appctx;
2039
2040 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002041 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002042 lua_pushnil(L);
2043 lua_pushstring(L, "Can't connect");
2044 return 2;
2045 }
2046
2047 appctx = objt_appctx(socket->s->si[0].end);
2048
2049 /* Check for connection established. */
2050 if (appctx->ctx.hlua.connected) {
2051 lua_pushinteger(L, 1);
2052 return 1;
2053 }
2054
2055 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2056 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002057 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002058 return 0;
2059}
2060
2061/* This function fail or initite the connection. */
2062__LJMP static int hlua_socket_connect(struct lua_State *L)
2063{
2064 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002065 int port;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002066 const char *ip;
2067 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002068 struct hlua *hlua;
2069 struct appctx *appctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002070
2071 MAY_LJMP(check_args(L, 3, "connect"));
2072
2073 /* Get args. */
2074 socket = MAY_LJMP(hlua_checksocket(L, 1));
2075 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002076 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002077
Willy Tarreau350f4872014-11-28 14:42:25 +01002078 conn = si_alloc_conn(&socket->s->si[1], 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002079 if (!conn)
2080 WILL_LJMP(luaL_error(L, "connect: internal error"));
2081
2082 /* Parse ip address. */
2083 conn->addr.to.ss_family = AF_UNSPEC;
2084 if (!str2ip2(ip, &conn->addr.to, 0))
2085 WILL_LJMP(luaL_error(L, "connect: cannot parse ip address '%s'", ip));
2086
2087 /* Set port. */
2088 if (conn->addr.to.ss_family == AF_INET)
2089 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2090 else if (conn->addr.to.ss_family == AF_INET6)
2091 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2092
2093 /* it is important not to call the wakeup function directly but to
2094 * pass through task_wakeup(), because this one knows how to apply
2095 * priorities to tasks.
2096 */
2097 task_wakeup(socket->s->task, TASK_WOKEN_INIT);
2098
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002099 hlua = hlua_gethlua(L);
2100 appctx = objt_appctx(socket->s->si[0].end);
2101 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2102 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002103 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002104
2105 return 0;
2106}
2107
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002108#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002109__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2110{
2111 struct hlua_socket *socket;
2112
2113 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2114 socket = MAY_LJMP(hlua_checksocket(L, 1));
2115 socket->s->target = &socket_ssl.obj_type;
2116 return MAY_LJMP(hlua_socket_connect(L));
2117}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002118#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002119
2120__LJMP static int hlua_socket_setoption(struct lua_State *L)
2121{
2122 return 0;
2123}
2124
2125__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2126{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002127 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002128 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002129
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002130 MAY_LJMP(check_args(L, 2, "settimeout"));
2131
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002132 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002133 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002134
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002135 socket->s->req.rto = tmout;
2136 socket->s->req.wto = tmout;
2137 socket->s->res.rto = tmout;
2138 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002139
2140 return 0;
2141}
2142
2143__LJMP static int hlua_socket_new(lua_State *L)
2144{
2145 struct hlua_socket *socket;
2146 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002147 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002148 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002149 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002150
2151 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002152 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002153 hlua_pusherror(L, "socket: full stack");
2154 goto out_fail_conf;
2155 }
2156
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002157 /* Create the object: obj[0] = userdata. */
2158 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002159 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002160 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002161 memset(socket, 0, sizeof(*socket));
2162
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002163 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002164 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002165 hlua_pusherror(L, "socket: uninitialized pools.");
2166 goto out_fail_conf;
2167 }
2168
Willy Tarreau87b09662015-04-03 00:22:06 +02002169 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002170 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2171 lua_setmetatable(L, -2);
2172
Willy Tarreaud420a972015-04-06 00:39:18 +02002173 /* Create the applet context */
2174 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002175 if (!appctx) {
2176 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002177 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002178 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002179
Willy Tarreaud420a972015-04-06 00:39:18 +02002180 appctx->ctx.hlua.socket = socket;
2181 appctx->ctx.hlua.connected = 0;
2182 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2183 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002184
Willy Tarreaud420a972015-04-06 00:39:18 +02002185 /* Now create a session, task and stream for this applet */
2186 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2187 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002188 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002189 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002190 }
2191
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002192 task = task_new();
2193 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002194 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002195 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002196 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002197 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002198
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002199 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002200 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002201 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002202 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002203 }
2204
Willy Tarreaud420a972015-04-06 00:39:18 +02002205 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002206 socket->s = strm;
2207 strm->hlua.T = NULL;
2208 strm->hlua.Tref = LUA_REFNIL;
2209 strm->hlua.Mref = LUA_REFNIL;
2210 strm->hlua.nargs = 0;
2211 strm->hlua.flags = 0;
2212 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002213
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002214 /* Configure "right" stream interface. this "si" is used to connect
2215 * and retrieve data from the server. The connection is initialized
2216 * with the "struct server".
2217 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002218 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002219
2220 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002221 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2222 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002223
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002224 /* Update statistics counters. */
2225 socket_proxy.feconn++; /* beconn will be increased later */
2226 jobs++;
2227 totalconn++;
2228
2229 /* Return yield waiting for connection. */
2230 return 1;
2231
Willy Tarreaud420a972015-04-06 00:39:18 +02002232 out_fail_stream:
2233 task_free(task);
2234 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002235 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002236 out_fail_sess:
2237 appctx_free(appctx);
2238 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002239 WILL_LJMP(lua_error(L));
2240 return 0;
2241}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002242
2243/*
2244 *
2245 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002246 * Class Channel
2247 *
2248 *
2249 */
2250
2251/* Returns the struct hlua_channel join to the class channel in the
2252 * stack entry "ud" or throws an argument error.
2253 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002254__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002255{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002256 return (struct channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002257}
2258
Willy Tarreau47860ed2015-03-10 14:07:50 +01002259/* Pushes the channel onto the top of the stack. If the stask does not have a
2260 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002261 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002262static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002263{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002264 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002265 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002266 return 0;
2267
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002268 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002269 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002270 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002271
2272 /* Pop a class sesison metatable and affect it to the userdata. */
2273 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2274 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002275 return 1;
2276}
2277
2278/* Duplicate all the data present in the input channel and put it
2279 * in a string LUA variables. Returns -1 and push a nil value in
2280 * the stack if the channel is closed and all the data are consumed,
2281 * returns 0 if no data are available, otherwise it returns the length
2282 * of the builded string.
2283 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002284static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002285{
2286 char *blk1;
2287 char *blk2;
2288 int len1;
2289 int len2;
2290 int ret;
2291 luaL_Buffer b;
2292
Willy Tarreau47860ed2015-03-10 14:07:50 +01002293 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002294 if (unlikely(ret == 0))
2295 return 0;
2296
2297 if (unlikely(ret < 0)) {
2298 lua_pushnil(L);
2299 return -1;
2300 }
2301
2302 luaL_buffinit(L, &b);
2303 luaL_addlstring(&b, blk1, len1);
2304 if (unlikely(ret == 2))
2305 luaL_addlstring(&b, blk2, len2);
2306 luaL_pushresult(&b);
2307
2308 if (unlikely(ret == 2))
2309 return len1 + len2;
2310 return len1;
2311}
2312
2313/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2314 * a yield. This function keep the data in the buffer.
2315 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002316__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002317{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002318 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002319
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002320 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2321
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002322 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002323 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002324 return 1;
2325}
2326
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002327/* Check arguments for the function "hlua_channel_dup_yield". */
2328__LJMP static int hlua_channel_dup(lua_State *L)
2329{
2330 MAY_LJMP(check_args(L, 1, "dup"));
2331 MAY_LJMP(hlua_checkchannel(L, 1));
2332 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2333}
2334
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002335/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2336 * a yield. This function consumes the data in the buffer. It returns
2337 * a string containing the data or a nil pointer if no data are available
2338 * and the channel is closed.
2339 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002340__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002341{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002342 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002343 int ret;
2344
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002345 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002346
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002347 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002348 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002349 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002350
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002351 if (unlikely(ret == -1))
2352 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002353
Willy Tarreau47860ed2015-03-10 14:07:50 +01002354 chn->buf->i -= ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002355 return 1;
2356}
2357
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002358/* Check arguments for the fucntion "hlua_channel_get_yield". */
2359__LJMP static int hlua_channel_get(lua_State *L)
2360{
2361 MAY_LJMP(check_args(L, 1, "get"));
2362 MAY_LJMP(hlua_checkchannel(L, 1));
2363 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2364}
2365
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002366/* This functions consumes and returns one line. If the channel is closed,
2367 * and the last data does not contains a final '\n', the data are returned
2368 * without the final '\n'. When no more data are avalaible, it returns nil
2369 * value.
2370 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002371__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002372{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002373 char *blk1;
2374 char *blk2;
2375 int len1;
2376 int len2;
2377 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002378 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002379 int ret;
2380 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002381
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002382 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2383
Willy Tarreau47860ed2015-03-10 14:07:50 +01002384 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002385 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002386 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002387
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002388 if (ret == -1) {
2389 lua_pushnil(L);
2390 return 1;
2391 }
2392
2393 luaL_buffinit(L, &b);
2394 luaL_addlstring(&b, blk1, len1);
2395 len = len1;
2396 if (unlikely(ret == 2)) {
2397 luaL_addlstring(&b, blk2, len2);
2398 len += len2;
2399 }
2400 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002401 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002402 return 1;
2403}
2404
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002405/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2406__LJMP static int hlua_channel_getline(lua_State *L)
2407{
2408 MAY_LJMP(check_args(L, 1, "getline"));
2409 MAY_LJMP(hlua_checkchannel(L, 1));
2410 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2411}
2412
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002413/* This function takes a string as input, and append it at the
2414 * input side of channel. If the data is too big, but a space
2415 * is probably available after sending some data, the function
2416 * yield. If the data is bigger than the buffer, or if the
2417 * channel is closed, it returns -1. otherwise, it returns the
2418 * amount of data writed.
2419 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002420__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002421{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002422 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002423 size_t len;
2424 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2425 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2426 int ret;
2427 int max;
2428
Willy Tarreau47860ed2015-03-10 14:07:50 +01002429 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002430 if (max > len - l)
2431 max = len - l;
2432
Willy Tarreau47860ed2015-03-10 14:07:50 +01002433 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002434 if (ret == -2 || ret == -3) {
2435 lua_pushinteger(L, -1);
2436 return 1;
2437 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002438 if (ret == -1) {
2439 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002440 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002441 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002442 l += ret;
2443 lua_pop(L, 1);
2444 lua_pushinteger(L, l);
2445
Willy Tarreau47860ed2015-03-10 14:07:50 +01002446 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2447 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002448 /* There are no space avalaible, and the output buffer is empty.
2449 * in this case, we cannot add more data, so we cannot yield,
2450 * we return the amount of copyied data.
2451 */
2452 return 1;
2453 }
2454 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002455 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002456 return 1;
2457}
2458
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002459/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002460 * of the writed string, or -1 if the channel is closed or if the
2461 * buffer size is too little for the data.
2462 */
2463__LJMP static int hlua_channel_append(lua_State *L)
2464{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002465 size_t len;
2466
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002467 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002468 MAY_LJMP(hlua_checkchannel(L, 1));
2469 MAY_LJMP(luaL_checklstring(L, 2, &len));
2470 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002471 lua_pushinteger(L, 0);
2472
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002473 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002474}
2475
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002476/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002477 * his process by cleaning the buffer. The result is a replacement
2478 * of the current data. It returns the length of the writed string,
2479 * or -1 if the channel is closed or if the buffer size is too
2480 * little for the data.
2481 */
2482__LJMP static int hlua_channel_set(lua_State *L)
2483{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002484 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002485
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002486 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002487 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002488 lua_pushinteger(L, 0);
2489
Willy Tarreau47860ed2015-03-10 14:07:50 +01002490 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002491
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002492 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002493}
2494
2495/* Append data in the output side of the buffer. This data is immediatly
2496 * sent. The fcuntion returns the ammount of data writed. If the buffer
2497 * cannot contains the data, the function yield. The function returns -1
2498 * if the channel is closed.
2499 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002500__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002501{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002502 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002503 size_t len;
2504 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2505 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2506 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002507 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002508
Willy Tarreau47860ed2015-03-10 14:07:50 +01002509 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002510 lua_pushinteger(L, -1);
2511 return 1;
2512 }
2513
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002514 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2515 * the request buffer if its not required.
2516 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002517 if (chn->buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02002518 if (!stream_alloc_recv_buffer(chn)) {
Willy Tarreau47860ed2015-03-10 14:07:50 +01002519 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002520 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002521 }
2522 }
2523
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002524 /* the writed data will be immediatly sent, so we can check
2525 * the avalaible space without taking in account the reserve.
2526 * The reserve is guaranted for the processing of incoming
2527 * data, because the buffer will be flushed.
2528 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002529 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002530
2531 /* If there are no space avalaible, and the output buffer is empty.
2532 * in this case, we cannot add more data, so we cannot yield,
2533 * we return the amount of copyied data.
2534 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002535 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002536 return 1;
2537
2538 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002539 if (max > len - l)
2540 max = len - l;
2541
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002542 /* The buffer avalaible size may be not contiguous. This test
2543 * detects a non contiguous buffer and realign it.
2544 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002545 if (bi_space_for_replace(chn->buf) < max)
2546 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002547
2548 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002549 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002550
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002551 /* buffer replace considers that the input part is filled.
2552 * so, I must forward these new data in the output part.
2553 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002554 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002555
2556 l += max;
2557 lua_pop(L, 1);
2558 lua_pushinteger(L, l);
2559
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002560 /* If there are no space avalaible, and the output buffer is empty.
2561 * in this case, we cannot add more data, so we cannot yield,
2562 * we return the amount of copyied data.
2563 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002564 max = chn->buf->size - buffer_len(chn->buf);
2565 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002566 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002567
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002568 if (l < len) {
2569 /* If we are waiting for space in the response buffer, we
2570 * must set the flag WAKERESWR. This flag required the task
2571 * wake up if any activity is detected on the response buffer.
2572 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002573 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002574 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002575 else
2576 HLUA_SET_WAKEREQWR(hlua);
2577 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002578 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002579
2580 return 1;
2581}
2582
2583/* Just a wraper of "_hlua_channel_send". This wrapper permits
2584 * yield the LUA process, and resume it without checking the
2585 * input arguments.
2586 */
2587__LJMP static int hlua_channel_send(lua_State *L)
2588{
2589 MAY_LJMP(check_args(L, 2, "send"));
2590 lua_pushinteger(L, 0);
2591
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002592 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002593}
2594
2595/* This function forward and amount of butes. The data pass from
2596 * the input side of the buffer to the output side, and can be
2597 * forwarded. This function never fails.
2598 *
2599 * The Lua function takes an amount of bytes to be forwarded in
2600 * imput. It returns the number of bytes forwarded.
2601 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002602__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002603{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002604 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002605 int len;
2606 int l;
2607 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002608 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002609
2610 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2611 len = MAY_LJMP(luaL_checkinteger(L, 2));
2612 l = MAY_LJMP(luaL_checkinteger(L, -1));
2613
2614 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002615 if (max > chn->buf->i)
2616 max = chn->buf->i;
2617 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002618 l += max;
2619
2620 lua_pop(L, 1);
2621 lua_pushinteger(L, l);
2622
2623 /* Check if it miss bytes to forward. */
2624 if (l < len) {
2625 /* The the input channel or the output channel are closed, we
2626 * must return the amount of data forwarded.
2627 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002628 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002629 return 1;
2630
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002631 /* If we are waiting for space data in the response buffer, we
2632 * must set the flag WAKERESWR. This flag required the task
2633 * wake up if any activity is detected on the response buffer.
2634 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002635 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002636 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002637 else
2638 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002639
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002640 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002641 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002642 }
2643
2644 return 1;
2645}
2646
2647/* Just check the input and prepare the stack for the previous
2648 * function "hlua_channel_forward_yield"
2649 */
2650__LJMP static int hlua_channel_forward(lua_State *L)
2651{
2652 MAY_LJMP(check_args(L, 2, "forward"));
2653 MAY_LJMP(hlua_checkchannel(L, 1));
2654 MAY_LJMP(luaL_checkinteger(L, 2));
2655
2656 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002657 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002658}
2659
2660/* Just returns the number of bytes available in the input
2661 * side of the buffer. This function never fails.
2662 */
2663__LJMP static int hlua_channel_get_in_len(lua_State *L)
2664{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002665 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002666
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002667 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002668 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002669 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002670 return 1;
2671}
2672
2673/* Just returns the number of bytes available in the output
2674 * side of the buffer. This function never fails.
2675 */
2676__LJMP static int hlua_channel_get_out_len(lua_State *L)
2677{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002678 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002679
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002680 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002681 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002682 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002683 return 1;
2684}
2685
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002686/*
2687 *
2688 *
2689 * Class Fetches
2690 *
2691 *
2692 */
2693
2694/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002695 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002696 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002697__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002698{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002699 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002700}
2701
2702/* This function creates and push in the stack a fetch object according
2703 * with a current TXN.
2704 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002705static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002706{
Willy Tarreau7073c472015-04-06 11:15:40 +02002707 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002708
2709 /* Check stack size. */
2710 if (!lua_checkstack(L, 3))
2711 return 0;
2712
2713 /* Create the object: obj[0] = userdata.
2714 * Note that the base of the Fetches object is the
2715 * transaction object.
2716 */
2717 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002718 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002719 lua_rawseti(L, -2, 0);
2720
Willy Tarreau7073c472015-04-06 11:15:40 +02002721 hsmp->s = txn->s;
2722 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002723 hsmp->stringsafe = stringsafe;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002724
2725 /* Pop a class sesison metatable and affect it to the userdata. */
2726 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2727 lua_setmetatable(L, -2);
2728
2729 return 1;
2730}
2731
2732/* This function is an LUA binding. It is called with each sample-fetch.
2733 * It uses closure argument to store the associated sample-fetch. It
2734 * returns only one argument or throws an error. An error is thrown
2735 * only if an error is encountered during the argument parsing. If
2736 * the "sample-fetch" function fails, nil is returned.
2737 */
2738__LJMP static int hlua_run_sample_fetch(lua_State *L)
2739{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002740 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002741 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002742 struct arg args[ARGM_NBARGS + 1];
2743 int i;
2744 struct sample smp;
2745
2746 /* Get closure arguments. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002747 f = (struct sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002748
2749 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002750 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002751
2752 /* Get extra arguments. */
2753 for (i = 0; i < lua_gettop(L) - 1; i++) {
2754 if (i >= ARGM_NBARGS)
2755 break;
2756 hlua_lua2arg(L, i + 2, &args[i]);
2757 }
2758 args[i].type = ARGT_STOP;
2759
2760 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002761 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002762
2763 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002764 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002765 lua_pushfstring(L, "error in arguments");
2766 WILL_LJMP(lua_error(L));
2767 }
2768
2769 /* Initialise the sample. */
2770 memset(&smp, 0, sizeof(smp));
2771
2772 /* Run the sample fetch process. */
Willy Tarreau192252e2015-04-04 01:47:55 +02002773 if (!f->process(hsmp->p, hsmp->s->sess, hsmp->s, 0, args, &smp, f->kw, f->private)) {
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002774 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002775 lua_pushstring(L, "");
2776 else
2777 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002778 return 1;
2779 }
2780
2781 /* Convert the returned sample in lua value. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002782 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002783 hlua_smp2lua_str(L, &smp);
2784 else
2785 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002786 return 1;
2787}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002788
2789/*
2790 *
2791 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002792 * Class Converters
2793 *
2794 *
2795 */
2796
2797/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002798 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002799 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002800__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002801{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002802 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002803}
2804
2805/* This function creates and push in the stack a Converters object
2806 * according with a current TXN.
2807 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002808static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002809{
Willy Tarreau7073c472015-04-06 11:15:40 +02002810 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002811
2812 /* Check stack size. */
2813 if (!lua_checkstack(L, 3))
2814 return 0;
2815
2816 /* Create the object: obj[0] = userdata.
2817 * Note that the base of the Converters object is the
2818 * same than the TXN object.
2819 */
2820 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002821 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002822 lua_rawseti(L, -2, 0);
2823
Willy Tarreau7073c472015-04-06 11:15:40 +02002824 hsmp->s = txn->s;
2825 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002826 hsmp->stringsafe = stringsafe;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002827
Willy Tarreau87b09662015-04-03 00:22:06 +02002828 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002829 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
2830 lua_setmetatable(L, -2);
2831
2832 return 1;
2833}
2834
2835/* This function is an LUA binding. It is called with each converter.
2836 * It uses closure argument to store the associated converter. It
2837 * returns only one argument or throws an error. An error is thrown
2838 * only if an error is encountered during the argument parsing. If
2839 * the converter function function fails, nil is returned.
2840 */
2841__LJMP static int hlua_run_sample_conv(lua_State *L)
2842{
Willy Tarreauda5f1082015-04-06 11:17:13 +02002843 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002844 struct sample_conv *conv;
2845 struct arg args[ARGM_NBARGS + 1];
2846 int i;
2847 struct sample smp;
2848
2849 /* Get closure arguments. */
2850 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
2851
2852 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002853 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002854
2855 /* Get extra arguments. */
2856 for (i = 0; i < lua_gettop(L) - 2; i++) {
2857 if (i >= ARGM_NBARGS)
2858 break;
2859 hlua_lua2arg(L, i + 3, &args[i]);
2860 }
2861 args[i].type = ARGT_STOP;
2862
2863 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002864 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002865
2866 /* Run the special args checker. */
2867 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
2868 hlua_pusherror(L, "error in arguments");
2869 WILL_LJMP(lua_error(L));
2870 }
2871
2872 /* Initialise the sample. */
2873 if (!hlua_lua2smp(L, 2, &smp)) {
2874 hlua_pusherror(L, "error in the input argument");
2875 WILL_LJMP(lua_error(L));
2876 }
2877
2878 /* Apply expected cast. */
2879 if (!sample_casts[smp.type][conv->in_type]) {
2880 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
2881 smp_to_type[smp.type], smp_to_type[conv->in_type]);
2882 WILL_LJMP(lua_error(L));
2883 }
2884 if (sample_casts[smp.type][conv->in_type] != c_none &&
2885 !sample_casts[smp.type][conv->in_type](&smp)) {
2886 hlua_pusherror(L, "error during the input argument casting");
2887 WILL_LJMP(lua_error(L));
2888 }
2889
2890 /* Run the sample conversion process. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002891 if (!conv->process(hsmp->s, args, &smp, conv->private)) {
2892 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002893 lua_pushstring(L, "");
2894 else
2895 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002896 return 1;
2897 }
2898
2899 /* Convert the returned sample in lua value. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002900 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002901 hlua_smp2lua_str(L, &smp);
2902 else
2903 hlua_smp2lua(L, &smp);
2904 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002905}
2906
2907/*
2908 *
2909 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002910 * Class HTTP
2911 *
2912 *
2913 */
2914
2915/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002916 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002917 */
2918__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
2919{
2920 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
2921}
2922
2923/* This function creates and push in the stack a HTTP object
2924 * according with a current TXN.
2925 */
2926static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
2927{
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002928 struct hlua_txn *htxn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002929
2930 /* Check stack size. */
2931 if (!lua_checkstack(L, 3))
2932 return 0;
2933
2934 /* Create the object: obj[0] = userdata.
2935 * Note that the base of the Converters object is the
2936 * same than the TXN object.
2937 */
2938 lua_newtable(L);
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002939 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002940 lua_rawseti(L, -2, 0);
2941
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002942 htxn->s = txn->s;
2943 htxn->p = txn->p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002944
Willy Tarreau87b09662015-04-03 00:22:06 +02002945 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002946 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
2947 lua_setmetatable(L, -2);
2948
2949 return 1;
2950}
2951
2952/* This function creates ans returns an array of HTTP headers.
2953 * This function does not fails. It is used as wrapper with the
2954 * 2 following functions.
2955 */
2956__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
2957{
2958 const char *cur_ptr, *cur_next, *p;
2959 int old_idx, cur_idx;
2960 struct hdr_idx_elem *cur_hdr;
2961 const char *hn, *hv;
2962 int hnl, hvl;
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01002963 int type;
2964 const char *in;
2965 char *out;
2966 int len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002967
2968 /* Create the table. */
2969 lua_newtable(L);
2970
Willy Tarreaueee5b512015-04-03 23:46:31 +02002971 if (!htxn->s->txn)
2972 return 1;
2973
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002974 /* Build array of headers. */
2975 old_idx = 0;
Willy Tarreaueee5b512015-04-03 23:46:31 +02002976 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002977
2978 while (1) {
Willy Tarreaueee5b512015-04-03 23:46:31 +02002979 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002980 if (!cur_idx)
2981 break;
2982 old_idx = cur_idx;
2983
Willy Tarreaueee5b512015-04-03 23:46:31 +02002984 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002985 cur_ptr = cur_next;
2986 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
2987
2988 /* Now we have one full header at cur_ptr of len cur_hdr->len,
2989 * and the next header starts at cur_next. We'll check
2990 * this header in the list as well as against the default
2991 * rule.
2992 */
2993
2994 /* look for ': *'. */
2995 hn = cur_ptr;
2996 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
2997 if (p >= cur_ptr+cur_hdr->len)
2998 continue;
2999 hnl = p - hn;
3000 p++;
3001 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
3002 p++;
3003 if (p >= cur_ptr+cur_hdr->len)
3004 continue;
3005 hv = p;
3006 hvl = cur_ptr+cur_hdr->len-p;
3007
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003008 /* Lowercase the key. Don't check the size of trash, it have
3009 * the size of one buffer and the input data contains in one
3010 * buffer.
3011 */
3012 out = trash.str;
3013 for (in=hn; in<hn+hnl; in++, out++)
3014 *out = tolower(*in);
3015 *out = '\0';
3016
3017 /* Check for existing entry:
3018 * assume that the table is on the top of the stack, and
3019 * push the key in the stack, the function lua_gettable()
3020 * perform the lookup.
3021 */
3022 lua_pushlstring(L, trash.str, hnl);
3023 lua_gettable(L, -2);
3024 type = lua_type(L, -1);
3025
3026 switch (type) {
3027 case LUA_TNIL:
3028 /* Table not found, create it. */
3029 lua_pop(L, 1); /* remove the nil value. */
3030 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
3031 lua_newtable(L); /* create and push empty table. */
3032 lua_pushlstring(L, hv, hvl); /* push header value. */
3033 lua_rawseti(L, -2, 0); /* index header value (pop it). */
3034 lua_rawset(L, -3); /* index new table with header name (pop the values). */
3035 break;
3036
3037 case LUA_TTABLE:
3038 /* Entry found: push the value in the table. */
3039 len = lua_rawlen(L, -1);
3040 lua_pushlstring(L, hv, hvl); /* push header value. */
3041 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
3042 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
3043 break;
3044
3045 default:
3046 /* Other cases are errors. */
3047 hlua_pusherror(L, "internal error during the parsing of headers.");
3048 WILL_LJMP(lua_error(L));
3049 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003050 }
3051
3052 return 1;
3053}
3054
3055__LJMP static int hlua_http_req_get_headers(lua_State *L)
3056{
3057 struct hlua_txn *htxn;
3058
3059 MAY_LJMP(check_args(L, 1, "req_get_headers"));
3060 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3061
Willy Tarreaueee5b512015-04-03 23:46:31 +02003062 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003063}
3064
3065__LJMP static int hlua_http_res_get_headers(lua_State *L)
3066{
3067 struct hlua_txn *htxn;
3068
3069 MAY_LJMP(check_args(L, 1, "res_get_headers"));
3070 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3071
Willy Tarreaueee5b512015-04-03 23:46:31 +02003072 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003073}
3074
3075/* This function replace full header, or just a value in
3076 * the request or in the response. It is a wrapper fir the
3077 * 4 following functions.
3078 */
3079__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
3080 struct http_msg *msg, int action)
3081{
3082 size_t name_len;
3083 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3084 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
3085 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
3086 struct my_regex re;
3087
3088 if (!regex_comp(reg, &re, 1, 1, NULL))
3089 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
3090
3091 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
3092 regex_free(&re);
3093 return 0;
3094}
3095
3096__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
3097{
3098 struct hlua_txn *htxn;
3099
3100 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3101 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3102
Willy Tarreaueee5b512015-04-03 23:46:31 +02003103 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 +01003104}
3105
3106__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
3107{
3108 struct hlua_txn *htxn;
3109
3110 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
3111 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3112
Willy Tarreaueee5b512015-04-03 23:46:31 +02003113 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 +01003114}
3115
3116__LJMP static int hlua_http_req_rep_val(lua_State *L)
3117{
3118 struct hlua_txn *htxn;
3119
3120 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3121 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3122
Willy Tarreaueee5b512015-04-03 23:46:31 +02003123 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 +01003124}
3125
3126__LJMP static int hlua_http_res_rep_val(lua_State *L)
3127{
3128 struct hlua_txn *htxn;
3129
3130 MAY_LJMP(check_args(L, 4, "res_rep_val"));
3131 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3132
Willy Tarreaueee5b512015-04-03 23:46:31 +02003133 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 +01003134}
3135
3136/* This function deletes all the occurences of an header.
3137 * It is a wrapper for the 2 following functions.
3138 */
3139__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3140{
3141 size_t len;
3142 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3143 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02003144 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003145
3146 ctx.idx = 0;
3147 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
3148 http_remove_header2(msg, &txn->hdr_idx, &ctx);
3149 return 0;
3150}
3151
3152__LJMP static int hlua_http_req_del_hdr(lua_State *L)
3153{
3154 struct hlua_txn *htxn;
3155
3156 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3157 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3158
Willy Tarreaueee5b512015-04-03 23:46:31 +02003159 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003160}
3161
3162__LJMP static int hlua_http_res_del_hdr(lua_State *L)
3163{
3164 struct hlua_txn *htxn;
3165
3166 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3167 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3168
Willy Tarreaueee5b512015-04-03 23:46:31 +02003169 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003170}
3171
3172/* This function adds an header. It is a wrapper used by
3173 * the 2 following functions.
3174 */
3175__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3176{
3177 size_t name_len;
3178 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3179 size_t value_len;
3180 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
3181 char *p;
3182
3183 /* Check length. */
3184 trash.len = value_len + name_len + 2;
3185 if (trash.len > trash.size)
3186 return 0;
3187
3188 /* Creates the header string. */
3189 p = trash.str;
3190 memcpy(p, name, name_len);
3191 p += name_len;
3192 *p = ':';
3193 p++;
3194 *p = ' ';
3195 p++;
3196 memcpy(p, value, value_len);
3197
Willy Tarreaueee5b512015-04-03 23:46:31 +02003198 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003199 trash.str, trash.len) != 0);
3200
3201 return 0;
3202}
3203
3204__LJMP static int hlua_http_req_add_hdr(lua_State *L)
3205{
3206 struct hlua_txn *htxn;
3207
3208 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
3209 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3210
Willy Tarreaueee5b512015-04-03 23:46:31 +02003211 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003212}
3213
3214__LJMP static int hlua_http_res_add_hdr(lua_State *L)
3215{
3216 struct hlua_txn *htxn;
3217
3218 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
3219 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3220
Willy Tarreaueee5b512015-04-03 23:46:31 +02003221 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003222}
3223
3224static int hlua_http_req_set_hdr(lua_State *L)
3225{
3226 struct hlua_txn *htxn;
3227
3228 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
3229 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3230
Willy Tarreaueee5b512015-04-03 23:46:31 +02003231 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
3232 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003233}
3234
3235static int hlua_http_res_set_hdr(lua_State *L)
3236{
3237 struct hlua_txn *htxn;
3238
3239 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
3240 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3241
Willy Tarreaueee5b512015-04-03 23:46:31 +02003242 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
3243 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003244}
3245
3246/* This function set the method. */
3247static int hlua_http_req_set_meth(lua_State *L)
3248{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003249 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003250 size_t name_len;
3251 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003252
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003253 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003254 return 1;
3255}
3256
3257/* This function set the method. */
3258static int hlua_http_req_set_path(lua_State *L)
3259{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003260 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003261 size_t name_len;
3262 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003263 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003264 return 1;
3265}
3266
3267/* This function set the query-string. */
3268static int hlua_http_req_set_query(lua_State *L)
3269{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003270 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003271 size_t name_len;
3272 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003273
3274 /* Check length. */
3275 if (name_len > trash.size - 1) {
3276 lua_pushboolean(L, 0);
3277 return 1;
3278 }
3279
3280 /* Add the mark question as prefix. */
3281 chunk_reset(&trash);
3282 trash.str[trash.len++] = '?';
3283 memcpy(trash.str + trash.len, name, name_len);
3284 trash.len += name_len;
3285
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003286 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003287 return 1;
3288}
3289
3290/* This function set the uri. */
3291static int hlua_http_req_set_uri(lua_State *L)
3292{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003293 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003294 size_t name_len;
3295 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003296
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003297 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003298 return 1;
3299}
3300
3301/*
3302 *
3303 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003304 * Class TXN
3305 *
3306 *
3307 */
3308
3309/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003310 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003311 */
3312__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
3313{
3314 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
3315}
3316
Willy Tarreau59551662015-03-10 14:23:13 +01003317__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003318{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003319 struct hlua *hlua;
3320
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003321 MAY_LJMP(check_args(L, 2, "set_priv"));
3322
Willy Tarreau87b09662015-04-03 00:22:06 +02003323 /* It is useles to retrieve the stream, but this function
3324 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003325 */
3326 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003327 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003328
3329 /* Remove previous value. */
3330 if (hlua->Mref != -1)
3331 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3332
3333 /* Get and store new value. */
3334 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3335 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3336
3337 return 0;
3338}
3339
Willy Tarreau59551662015-03-10 14:23:13 +01003340__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003341{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003342 struct hlua *hlua;
3343
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003344 MAY_LJMP(check_args(L, 1, "get_priv"));
3345
Willy Tarreau87b09662015-04-03 00:22:06 +02003346 /* It is useles to retrieve the stream, but this function
3347 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003348 */
3349 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003350 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003351
3352 /* Push configuration index in the stack. */
3353 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3354
3355 return 1;
3356}
3357
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003358/* Create stack entry containing a class TXN. This function
3359 * return 0 if the stack does not contains free slots,
3360 * otherwise it returns 1.
3361 */
Willy Tarreau15e91e12015-04-04 00:52:09 +02003362static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003363{
Willy Tarreaude491382015-04-06 11:04:28 +02003364 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003365
3366 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003367 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003368 return 0;
3369
3370 /* NOTE: The allocation never fails. The failure
3371 * throw an error, and the function never returns.
3372 * if the throw is not avalaible, the process is aborted.
3373 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003374 /* Create the object: obj[0] = userdata. */
3375 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02003376 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003377 lua_rawseti(L, -2, 0);
3378
Willy Tarreaude491382015-04-06 11:04:28 +02003379 htxn->s = s;
3380 htxn->p = p;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003381
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003382 /* Create the "f" field that contains a list of fetches. */
3383 lua_pushstring(L, "f");
Willy Tarreaude491382015-04-06 11:04:28 +02003384 if (!hlua_fetches_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003385 return 0;
3386 lua_settable(L, -3);
3387
3388 /* Create the "sf" field that contains a list of stringsafe fetches. */
3389 lua_pushstring(L, "sf");
Willy Tarreaude491382015-04-06 11:04:28 +02003390 if (!hlua_fetches_new(L, htxn, 1))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003391 return 0;
3392 lua_settable(L, -3);
3393
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003394 /* Create the "c" field that contains a list of converters. */
3395 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02003396 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003397 return 0;
3398 lua_settable(L, -3);
3399
3400 /* Create the "sc" field that contains a list of stringsafe converters. */
3401 lua_pushstring(L, "sc");
Willy Tarreaude491382015-04-06 11:04:28 +02003402 if (!hlua_converters_new(L, htxn, 1))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003403 return 0;
3404 lua_settable(L, -3);
3405
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003406 /* Create the "req" field that contains the request channel object. */
3407 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003408 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003409 return 0;
3410 lua_settable(L, -3);
3411
3412 /* Create the "res" field that contains the response channel object. */
3413 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003414 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003415 return 0;
3416 lua_settable(L, -3);
3417
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003418 /* Creates the HTTP object is the current proxy allows http. */
3419 lua_pushstring(L, "http");
3420 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02003421 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003422 return 0;
3423 }
3424 else
3425 lua_pushnil(L);
3426 lua_settable(L, -3);
3427
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003428 /* Pop a class sesison metatable and affect it to the userdata. */
3429 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
3430 lua_setmetatable(L, -2);
3431
3432 return 1;
3433}
3434
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003435__LJMP static int hlua_txn_deflog(lua_State *L)
3436{
3437 const char *msg;
3438 struct hlua_txn *htxn;
3439
3440 MAY_LJMP(check_args(L, 2, "deflog"));
3441 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3442 msg = MAY_LJMP(luaL_checkstring(L, 2));
3443
3444 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
3445 return 0;
3446}
3447
3448__LJMP static int hlua_txn_log(lua_State *L)
3449{
3450 int level;
3451 const char *msg;
3452 struct hlua_txn *htxn;
3453
3454 MAY_LJMP(check_args(L, 3, "log"));
3455 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3456 level = MAY_LJMP(luaL_checkinteger(L, 2));
3457 msg = MAY_LJMP(luaL_checkstring(L, 3));
3458
3459 if (level < 0 || level >= NB_LOG_LEVELS)
3460 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3461
3462 hlua_sendlog(htxn->s->be, level, msg);
3463 return 0;
3464}
3465
3466__LJMP static int hlua_txn_log_debug(lua_State *L)
3467{
3468 const char *msg;
3469 struct hlua_txn *htxn;
3470
3471 MAY_LJMP(check_args(L, 2, "Debug"));
3472 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3473 msg = MAY_LJMP(luaL_checkstring(L, 2));
3474 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
3475 return 0;
3476}
3477
3478__LJMP static int hlua_txn_log_info(lua_State *L)
3479{
3480 const char *msg;
3481 struct hlua_txn *htxn;
3482
3483 MAY_LJMP(check_args(L, 2, "Info"));
3484 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3485 msg = MAY_LJMP(luaL_checkstring(L, 2));
3486 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
3487 return 0;
3488}
3489
3490__LJMP static int hlua_txn_log_warning(lua_State *L)
3491{
3492 const char *msg;
3493 struct hlua_txn *htxn;
3494
3495 MAY_LJMP(check_args(L, 2, "Warning"));
3496 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3497 msg = MAY_LJMP(luaL_checkstring(L, 2));
3498 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
3499 return 0;
3500}
3501
3502__LJMP static int hlua_txn_log_alert(lua_State *L)
3503{
3504 const char *msg;
3505 struct hlua_txn *htxn;
3506
3507 MAY_LJMP(check_args(L, 2, "Alert"));
3508 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3509 msg = MAY_LJMP(luaL_checkstring(L, 2));
3510 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
3511 return 0;
3512}
3513
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003514__LJMP static int hlua_txn_set_loglevel(lua_State *L)
3515{
3516 struct hlua_txn *htxn;
3517 int ll;
3518
3519 MAY_LJMP(check_args(L, 2, "set_loglevel"));
3520 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3521 ll = MAY_LJMP(luaL_checkinteger(L, 2));
3522
3523 if (ll < 0 || ll > 7)
3524 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
3525
3526 htxn->s->logs.level = ll;
3527 return 0;
3528}
3529
3530__LJMP static int hlua_txn_set_tos(lua_State *L)
3531{
3532 struct hlua_txn *htxn;
3533 struct connection *cli_conn;
3534 int tos;
3535
3536 MAY_LJMP(check_args(L, 2, "set_tos"));
3537 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3538 tos = MAY_LJMP(luaL_checkinteger(L, 2));
3539
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003540 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003541 inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, tos);
3542
3543 return 0;
3544}
3545
3546__LJMP static int hlua_txn_set_mark(lua_State *L)
3547{
3548#ifdef SO_MARK
3549 struct hlua_txn *htxn;
3550 struct connection *cli_conn;
3551 int mark;
3552
3553 MAY_LJMP(check_args(L, 2, "set_mark"));
3554 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3555 mark = MAY_LJMP(luaL_checkinteger(L, 2));
3556
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003557 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02003558 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003559#endif
3560 return 0;
3561}
3562
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003563/* This function is an Lua binding that send pending data
3564 * to the client, and close the stream interface.
3565 */
3566__LJMP static int hlua_txn_close(lua_State *L)
3567{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003568 struct hlua_txn *htxn;
Willy Tarreau81389672015-03-10 12:03:52 +01003569 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003570
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003571 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003572 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003573
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003574 ic = &htxn->s->req;
3575 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01003576
3577 channel_abort(ic);
3578 channel_auto_close(ic);
3579 channel_erase(ic);
3580 channel_auto_read(oc);
3581 channel_auto_close(oc);
3582 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003583
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003584 return 0;
3585}
3586
3587__LJMP static int hlua_log(lua_State *L)
3588{
3589 int level;
3590 const char *msg;
3591
3592 MAY_LJMP(check_args(L, 2, "log"));
3593 level = MAY_LJMP(luaL_checkinteger(L, 1));
3594 msg = MAY_LJMP(luaL_checkstring(L, 2));
3595
3596 if (level < 0 || level >= NB_LOG_LEVELS)
3597 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3598
3599 hlua_sendlog(NULL, level, msg);
3600 return 0;
3601}
3602
3603__LJMP static int hlua_log_debug(lua_State *L)
3604{
3605 const char *msg;
3606
3607 MAY_LJMP(check_args(L, 1, "debug"));
3608 msg = MAY_LJMP(luaL_checkstring(L, 1));
3609 hlua_sendlog(NULL, LOG_DEBUG, msg);
3610 return 0;
3611}
3612
3613__LJMP static int hlua_log_info(lua_State *L)
3614{
3615 const char *msg;
3616
3617 MAY_LJMP(check_args(L, 1, "info"));
3618 msg = MAY_LJMP(luaL_checkstring(L, 1));
3619 hlua_sendlog(NULL, LOG_INFO, msg);
3620 return 0;
3621}
3622
3623__LJMP static int hlua_log_warning(lua_State *L)
3624{
3625 const char *msg;
3626
3627 MAY_LJMP(check_args(L, 1, "warning"));
3628 msg = MAY_LJMP(luaL_checkstring(L, 1));
3629 hlua_sendlog(NULL, LOG_WARNING, msg);
3630 return 0;
3631}
3632
3633__LJMP static int hlua_log_alert(lua_State *L)
3634{
3635 const char *msg;
3636
3637 MAY_LJMP(check_args(L, 1, "alert"));
3638 msg = MAY_LJMP(luaL_checkstring(L, 1));
3639 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003640 return 0;
3641}
3642
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003643__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003644{
3645 int wakeup_ms = lua_tointeger(L, -1);
3646 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003647 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003648 return 0;
3649}
3650
3651__LJMP static int hlua_sleep(lua_State *L)
3652{
3653 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003654 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003655
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003656 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003657
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003658 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003659 wakeup_ms = tick_add(now_ms, delay);
3660 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003661
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003662 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3663 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003664}
3665
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003666__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003667{
3668 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003669 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003670
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003671 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003672
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003673 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003674 wakeup_ms = tick_add(now_ms, delay);
3675 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003676
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003677 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3678 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003679}
3680
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003681/* This functionis an LUA binding. it permits to give back
3682 * the hand at the HAProxy scheduler. It is used when the
3683 * LUA processing consumes a lot of time.
3684 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003685__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003686{
3687 return 0;
3688}
3689
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003690__LJMP static int hlua_yield(lua_State *L)
3691{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003692 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
3693 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003694}
3695
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003696/* This function change the nice of the currently executed
3697 * task. It is used set low or high priority at the current
3698 * task.
3699 */
Willy Tarreau59551662015-03-10 14:23:13 +01003700__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003701{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003702 struct hlua *hlua;
3703 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003704
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003705 MAY_LJMP(check_args(L, 1, "set_nice"));
3706 hlua = hlua_gethlua(L);
3707 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003708
3709 /* If he task is not set, I'm in a start mode. */
3710 if (!hlua || !hlua->task)
3711 return 0;
3712
3713 if (nice < -1024)
3714 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003715 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003716 nice = 1024;
3717
3718 hlua->task->nice = nice;
3719 return 0;
3720}
3721
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003722/* This function is used as a calback of a task. It is called by the
3723 * HAProxy task subsystem when the task is awaked. The LUA runtime can
3724 * return an E_AGAIN signal, the emmiter of this signal must set a
3725 * signal to wake the task.
3726 */
3727static struct task *hlua_process_task(struct task *task)
3728{
3729 struct hlua *hlua = task->context;
3730 enum hlua_exec status;
3731
3732 /* We need to remove the task from the wait queue before executing
3733 * the Lua code because we don't know if it needs to wait for
3734 * another timer or not in the case of E_AGAIN.
3735 */
3736 task_delete(task);
3737
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003738 /* If it is the first call to the task, we must initialize the
3739 * execution timeouts.
3740 */
3741 if (!HLUA_IS_RUNNING(hlua))
3742 hlua->expire = tick_add(now_ms, hlua_timeout_task);
3743
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003744 /* Execute the Lua code. */
3745 status = hlua_ctx_resume(hlua, 1);
3746
3747 switch (status) {
3748 /* finished or yield */
3749 case HLUA_E_OK:
3750 hlua_ctx_destroy(hlua);
3751 task_delete(task);
3752 task_free(task);
3753 break;
3754
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003755 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
3756 if (hlua->wake_time != TICK_ETERNITY)
3757 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003758 break;
3759
3760 /* finished with error. */
3761 case HLUA_E_ERRMSG:
3762 send_log(NULL, LOG_ERR, "Lua task: %s.", lua_tostring(hlua->T, -1));
3763 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3764 Alert("Lua task: %s.\n", lua_tostring(hlua->T, -1));
3765 hlua_ctx_destroy(hlua);
3766 task_delete(task);
3767 task_free(task);
3768 break;
3769
3770 case HLUA_E_ERR:
3771 default:
3772 send_log(NULL, LOG_ERR, "Lua task: unknown error.");
3773 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3774 Alert("Lua task: unknown error.\n");
3775 hlua_ctx_destroy(hlua);
3776 task_delete(task);
3777 task_free(task);
3778 break;
3779 }
3780 return NULL;
3781}
3782
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003783/* This function is an LUA binding that register LUA function to be
3784 * executed after the HAProxy configuration parsing and before the
3785 * HAProxy scheduler starts. This function expect only one LUA
3786 * argument that is a function. This function returns nothing, but
3787 * throws if an error is encountered.
3788 */
3789__LJMP static int hlua_register_init(lua_State *L)
3790{
3791 struct hlua_init_function *init;
3792 int ref;
3793
3794 MAY_LJMP(check_args(L, 1, "register_init"));
3795
3796 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3797
3798 init = malloc(sizeof(*init));
3799 if (!init)
3800 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3801
3802 init->function_ref = ref;
3803 LIST_ADDQ(&hlua_init_functions, &init->l);
3804 return 0;
3805}
3806
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003807/* This functio is an LUA binding. It permits to register a task
3808 * executed in parallel of the main HAroxy activity. The task is
3809 * created and it is set in the HAProxy scheduler. It can be called
3810 * from the "init" section, "post init" or during the runtime.
3811 *
3812 * Lua prototype:
3813 *
3814 * <none> core.register_task(<function>)
3815 */
3816static int hlua_register_task(lua_State *L)
3817{
3818 struct hlua *hlua;
3819 struct task *task;
3820 int ref;
3821
3822 MAY_LJMP(check_args(L, 1, "register_task"));
3823
3824 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3825
3826 hlua = malloc(sizeof(*hlua));
3827 if (!hlua)
3828 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3829
3830 task = task_new();
3831 task->context = hlua;
3832 task->process = hlua_process_task;
3833
3834 if (!hlua_ctx_init(hlua, task))
3835 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3836
3837 /* Restore the function in the stack. */
3838 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
3839 hlua->nargs = 0;
3840
3841 /* Schedule task. */
3842 task_schedule(task, now_ms);
3843
3844 return 0;
3845}
3846
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003847/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
3848 * doesn't allow "yield" functions because the HAProxy engine cannot
3849 * resume converters.
3850 */
Willy Tarreau87b09662015-04-03 00:22:06 +02003851static int hlua_sample_conv_wrapper(struct stream *stream, const struct arg *arg_p,
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003852 struct sample *smp, void *private)
3853{
3854 struct hlua_function *fcn = (struct hlua_function *)private;
3855
Willy Tarreau87b09662015-04-03 00:22:06 +02003856 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003857 * Lua context can be not initialized. This behavior
3858 * permits to save performances because a systematic
3859 * Lua initialization cause 5% performances loss.
3860 */
Willy Tarreau87b09662015-04-03 00:22:06 +02003861 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
3862 send_log(stream->be, LOG_ERR, "Lua converter '%s': can't initialize Lua context.", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003863 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3864 Alert("Lua converter '%s': can't initialize Lua context.\n", fcn->name);
3865 return 0;
3866 }
3867
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003868 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003869 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003870 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003871 if (!lua_checkstack(stream->hlua.T, 1)) {
3872 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003873 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3874 Alert("Lua converter '%s': full stack.\n", fcn->name);
3875 return 0;
3876 }
3877
3878 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003879 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003880
3881 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003882 if (!lua_checkstack(stream->hlua.T, 1)) {
3883 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003884 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3885 Alert("Lua converter '%s': full stack.\n", fcn->name);
3886 return 0;
3887 }
Willy Tarreau87b09662015-04-03 00:22:06 +02003888 hlua_smp2lua(stream->hlua.T, smp);
3889 stream->hlua.nargs = 2;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003890
3891 /* push keywords in the stack. */
3892 if (arg_p) {
3893 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02003894 if (!lua_checkstack(stream->hlua.T, 1)) {
3895 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003896 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3897 Alert("Lua converter '%s': full stack.\n", fcn->name);
3898 return 0;
3899 }
Willy Tarreau87b09662015-04-03 00:22:06 +02003900 hlua_arg2lua(stream->hlua.T, arg_p);
3901 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003902 }
3903 }
3904
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003905 /* We must initialize the execution timeouts. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003906 stream->hlua.expire = tick_add(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003907
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003908 /* Set the currently running flag. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003909 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003910 }
3911
3912 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003913 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003914 /* finished. */
3915 case HLUA_E_OK:
3916 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003917 hlua_lua2smp(stream->hlua.T, -1, smp);
3918 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003919 return 1;
3920
3921 /* yield. */
3922 case HLUA_E_AGAIN:
Willy Tarreau87b09662015-04-03 00:22:06 +02003923 send_log(stream->be, LOG_ERR, "Lua converter '%s': cannot use yielded functions.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003924 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3925 Alert("Lua converter '%s': cannot use yielded functions.\n", fcn->name);
3926 return 0;
3927
3928 /* finished with error. */
3929 case HLUA_E_ERRMSG:
3930 /* Display log. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003931 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 +01003932 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Willy Tarreau87b09662015-04-03 00:22:06 +02003933 Alert("Lua converter '%s': %s.\n", fcn->name, lua_tostring(stream->hlua.T, -1));
3934 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003935 return 0;
3936
3937 case HLUA_E_ERR:
3938 /* Display log. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003939 send_log(stream->be, LOG_ERR, "Lua converter '%s' returns an unknown error.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003940 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3941 Alert("Lua converter '%s' returns an unknown error.\n", fcn->name);
3942
3943 default:
3944 return 0;
3945 }
3946}
3947
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003948/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
3949 * doesn't allow "yield" functions because the HAProxy engine cannot
3950 * resume sample-fetches.
3951 */
Willy Tarreau192252e2015-04-04 01:47:55 +02003952static int hlua_sample_fetch_wrapper(struct proxy *px, struct session *sess,
3953 struct stream *s, unsigned int opt,
3954 const struct arg *arg_p,
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003955 struct sample *smp, const char *kw, void *private)
3956{
3957 struct hlua_function *fcn = (struct hlua_function *)private;
3958
Willy Tarreau87b09662015-04-03 00:22:06 +02003959 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003960 * Lua context can be not initialized. This behavior
3961 * permits to save performances because a systematic
3962 * Lua initialization cause 5% performances loss.
3963 */
3964 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
3965 send_log(s->be, LOG_ERR, "Lua sample-fetch '%s': can't initialize Lua context.", fcn->name);
3966 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3967 Alert("Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
3968 return 0;
3969 }
3970
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003971 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003972 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003973 /* Check stack available size. */
3974 if (!lua_checkstack(s->hlua.T, 2)) {
3975 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3976 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3977 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3978 return 0;
3979 }
3980
3981 /* Restore the function in the stack. */
3982 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
3983
3984 /* push arguments in the stack. */
Willy Tarreau15e91e12015-04-04 00:52:09 +02003985 if (!hlua_txn_new(s->hlua.T, s, px)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003986 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3987 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3988 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3989 return 0;
3990 }
3991 s->hlua.nargs = 1;
3992
3993 /* push keywords in the stack. */
3994 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
3995 /* Check stack available size. */
3996 if (!lua_checkstack(s->hlua.T, 1)) {
3997 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3998 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3999 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4000 return 0;
4001 }
4002 if (!lua_checkstack(s->hlua.T, 1)) {
4003 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
4004 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4005 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4006 return 0;
4007 }
4008 hlua_arg2lua(s->hlua.T, arg_p);
4009 s->hlua.nargs++;
4010 }
4011
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004012 /* We must initialize the execution timeouts. */
4013 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
4014
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004015 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004016 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004017 }
4018
4019 /* Execute the function. */
4020 switch (hlua_ctx_resume(&s->hlua, 0)) {
4021 /* finished. */
4022 case HLUA_E_OK:
4023 /* Convert the returned value in sample. */
4024 hlua_lua2smp(s->hlua.T, -1, smp);
4025 lua_pop(s->hlua.T, 1);
4026
4027 /* Set the end of execution flag. */
4028 smp->flags &= ~SMP_F_MAY_CHANGE;
4029 return 1;
4030
4031 /* yield. */
4032 case HLUA_E_AGAIN:
4033 send_log(px, LOG_ERR, "Lua sample-fetch '%s': cannot use yielded functions.", fcn->name);
4034 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4035 Alert("Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
4036 return 0;
4037
4038 /* finished with error. */
4039 case HLUA_E_ERRMSG:
4040 /* Display log. */
4041 send_log(px, LOG_ERR, "Lua sample-fetch '%s': %s.", fcn->name, lua_tostring(s->hlua.T, -1));
4042 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4043 Alert("Lua sample-fetch '%s': %s.\n", fcn->name, lua_tostring(s->hlua.T, -1));
4044 lua_pop(s->hlua.T, 1);
4045 return 0;
4046
4047 case HLUA_E_ERR:
4048 /* Display log. */
4049 send_log(px, LOG_ERR, "Lua sample-fetch '%s' returns an unknown error.", fcn->name);
4050 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4051 Alert("Lua sample-fetch '%s': returns an unknown error.\n", fcn->name);
4052
4053 default:
4054 return 0;
4055 }
4056}
4057
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004058/* This function is an LUA binding used for registering
4059 * "sample-conv" functions. It expects a converter name used
4060 * in the haproxy configuration file, and an LUA function.
4061 */
4062__LJMP static int hlua_register_converters(lua_State *L)
4063{
4064 struct sample_conv_kw_list *sck;
4065 const char *name;
4066 int ref;
4067 int len;
4068 struct hlua_function *fcn;
4069
4070 MAY_LJMP(check_args(L, 2, "register_converters"));
4071
4072 /* First argument : converter name. */
4073 name = MAY_LJMP(luaL_checkstring(L, 1));
4074
4075 /* Second argument : lua function. */
4076 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4077
4078 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004079 sck = malloc(sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004080 if (!sck)
4081 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4082 fcn = malloc(sizeof(*fcn));
4083 if (!fcn)
4084 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4085
4086 /* Fill fcn. */
4087 fcn->name = strdup(name);
4088 if (!fcn->name)
4089 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4090 fcn->function_ref = ref;
4091
4092 /* List head */
4093 sck->list.n = sck->list.p = NULL;
4094
4095 /* converter keyword. */
4096 len = strlen("lua.") + strlen(name) + 1;
4097 sck->kw[0].kw = malloc(len);
4098 if (!sck->kw[0].kw)
4099 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4100
4101 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
4102 sck->kw[0].process = hlua_sample_conv_wrapper;
4103 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4104 sck->kw[0].val_args = NULL;
4105 sck->kw[0].in_type = SMP_T_STR;
4106 sck->kw[0].out_type = SMP_T_STR;
4107 sck->kw[0].private = fcn;
4108
4109 /* End of array. */
4110 memset(&sck->kw[1], 0, sizeof(struct sample_conv));
4111
4112 /* Register this new converter */
4113 sample_register_convs(sck);
4114
4115 return 0;
4116}
4117
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004118/* This fucntion is an LUA binding used for registering
4119 * "sample-fetch" functions. It expects a converter name used
4120 * in the haproxy configuration file, and an LUA function.
4121 */
4122__LJMP static int hlua_register_fetches(lua_State *L)
4123{
4124 const char *name;
4125 int ref;
4126 int len;
4127 struct sample_fetch_kw_list *sfk;
4128 struct hlua_function *fcn;
4129
4130 MAY_LJMP(check_args(L, 2, "register_fetches"));
4131
4132 /* First argument : sample-fetch name. */
4133 name = MAY_LJMP(luaL_checkstring(L, 1));
4134
4135 /* Second argument : lua function. */
4136 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4137
4138 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004139 sfk = malloc(sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004140 if (!sfk)
4141 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4142 fcn = malloc(sizeof(*fcn));
4143 if (!fcn)
4144 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4145
4146 /* Fill fcn. */
4147 fcn->name = strdup(name);
4148 if (!fcn->name)
4149 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4150 fcn->function_ref = ref;
4151
4152 /* List head */
4153 sfk->list.n = sfk->list.p = NULL;
4154
4155 /* sample-fetch keyword. */
4156 len = strlen("lua.") + strlen(name) + 1;
4157 sfk->kw[0].kw = malloc(len);
4158 if (!sfk->kw[0].kw)
4159 return luaL_error(L, "lua out of memory error.");
4160
4161 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
4162 sfk->kw[0].process = hlua_sample_fetch_wrapper;
4163 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4164 sfk->kw[0].val_args = NULL;
4165 sfk->kw[0].out_type = SMP_T_STR;
4166 sfk->kw[0].use = SMP_USE_HTTP_ANY;
4167 sfk->kw[0].val = 0;
4168 sfk->kw[0].private = fcn;
4169
4170 /* End of array. */
4171 memset(&sfk->kw[1], 0, sizeof(struct sample_fetch));
4172
4173 /* Register this new fetch. */
4174 sample_register_fetches(sfk);
4175
4176 return 0;
4177}
4178
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004179/* global {tcp|http}-request parser. Return 1 in succes case, else return 0. */
4180static int hlua_parse_rule(const char **args, int *cur_arg, struct proxy *px,
4181 struct hlua_rule **rule_p, char **err)
4182{
4183 struct hlua_rule *rule;
4184
4185 /* Memory for the rule. */
4186 rule = malloc(sizeof(*rule));
4187 if (!rule) {
4188 memprintf(err, "out of memory error");
4189 return 0;
4190 }
4191 *rule_p = rule;
4192
4193 /* The requiered arg is a function name. */
4194 if (!args[*cur_arg]) {
4195 memprintf(err, "expect Lua function name");
4196 return 0;
4197 }
4198
4199 /* Lookup for the symbol, and check if it is a function. */
4200 lua_getglobal(gL.T, args[*cur_arg]);
4201 if (lua_isnil(gL.T, -1)) {
4202 lua_pop(gL.T, 1);
4203 memprintf(err, "Lua function '%s' not found", args[*cur_arg]);
4204 return 0;
4205 }
4206 if (!lua_isfunction(gL.T, -1)) {
4207 lua_pop(gL.T, 1);
4208 memprintf(err, "'%s' is not a function", args[*cur_arg]);
4209 return 0;
4210 }
4211
4212 /* Reference the Lua function and store the reference. */
4213 rule->fcn.function_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
4214 rule->fcn.name = strdup(args[*cur_arg]);
4215 if (!rule->fcn.name) {
4216 memprintf(err, "out of memory error.");
4217 return 0;
4218 }
4219 (*cur_arg)++;
4220
4221 /* TODO: later accept arguments. */
4222 rule->args = NULL;
4223
4224 return 1;
4225}
4226
4227/* This function is a wrapper to execute each LUA function declared
4228 * as an action wrapper during the initialisation period. This function
4229 * return 1 if the processing is finished (with oe without error) and
4230 * return 0 if the function must be called again because the LUA
4231 * returns a yield.
4232 */
4233static int hlua_request_act_wrapper(struct hlua_rule *rule, struct proxy *px,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004234 struct stream *s, unsigned int analyzer)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004235{
4236 char **arg;
4237
Willy Tarreau87b09662015-04-03 00:22:06 +02004238 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004239 * Lua context can be not initialized. This behavior
4240 * permits to save performances because a systematic
4241 * Lua initialization cause 5% performances loss.
4242 */
4243 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
4244 send_log(px, LOG_ERR, "Lua action '%s': can't initialize Lua context.", rule->fcn.name);
4245 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4246 Alert("Lua action '%s': can't initialize Lua context.\n", rule->fcn.name);
4247 return 0;
4248 }
4249
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004250 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004251 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004252 /* Check stack available size. */
4253 if (!lua_checkstack(s->hlua.T, 1)) {
4254 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
4255 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4256 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
4257 return 0;
4258 }
4259
4260 /* Restore the function in the stack. */
4261 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->fcn.function_ref);
4262
Willy Tarreau87b09662015-04-03 00:22:06 +02004263 /* Create and and push object stream in the stack. */
Willy Tarreau15e91e12015-04-04 00:52:09 +02004264 if (!hlua_txn_new(s->hlua.T, s, px)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004265 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
4266 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4267 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
4268 return 0;
4269 }
4270 s->hlua.nargs = 1;
4271
4272 /* push keywords in the stack. */
4273 for (arg = rule->args; arg && *arg; arg++) {
4274 if (!lua_checkstack(s->hlua.T, 1)) {
4275 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
4276 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4277 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
4278 return 0;
4279 }
4280 lua_pushstring(s->hlua.T, *arg);
4281 s->hlua.nargs++;
4282 }
4283
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004284 /* We must initialize the execution timeouts. */
4285 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
4286
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004287 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004288 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004289 }
4290
4291 /* Execute the function. */
4292 switch (hlua_ctx_resume(&s->hlua, 1)) {
4293 /* finished. */
4294 case HLUA_E_OK:
4295 return 1;
4296
4297 /* yield. */
4298 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004299 /* Set timeout in the required channel. */
4300 if (s->hlua.wake_time != TICK_ETERNITY) {
4301 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004302 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004303 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004304 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004305 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004306 /* Some actions can be wake up when a "write" event
4307 * is detected on a response channel. This is useful
4308 * only for actions targetted on the requests.
4309 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004310 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004311 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01004312 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004313 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004314 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004315 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004316 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004317 return 0;
4318
4319 /* finished with error. */
4320 case HLUA_E_ERRMSG:
4321 /* Display log. */
4322 send_log(px, LOG_ERR, "Lua function '%s': %s.", rule->fcn.name, lua_tostring(s->hlua.T, -1));
4323 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4324 Alert("Lua function '%s': %s.\n", rule->fcn.name, lua_tostring(s->hlua.T, -1));
4325 lua_pop(s->hlua.T, 1);
4326 return 1;
4327
4328 case HLUA_E_ERR:
4329 /* Display log. */
4330 send_log(px, LOG_ERR, "Lua function '%s' return an unknown error.", rule->fcn.name);
4331 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4332 Alert("Lua function '%s' return an unknown error.\n", rule->fcn.name);
4333
4334 default:
4335 return 1;
4336 }
4337}
4338
4339/* Lua execution wrapper for "tcp-request". This function uses
4340 * "hlua_request_act_wrapper" for executing the LUA code.
4341 */
4342int hlua_tcp_req_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
Willy Tarreau87b09662015-04-03 00:22:06 +02004343 struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004344{
4345 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004346 px, s, AN_REQ_INSPECT_FE);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004347}
4348
4349/* Lua execution wrapper for "tcp-response". This function uses
4350 * "hlua_request_act_wrapper" for executing the LUA code.
4351 */
4352int hlua_tcp_res_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
Willy Tarreau87b09662015-04-03 00:22:06 +02004353 struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004354{
4355 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004356 px, s, AN_RES_INSPECT);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004357}
4358
4359/* Lua execution wrapper for http-request.
4360 * This function uses "hlua_request_act_wrapper" for executing
4361 * the LUA code.
4362 */
4363int hlua_http_req_act_wrapper(struct http_req_rule *rule, struct proxy *px,
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004364 struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004365{
4366 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004367 s, AN_REQ_HTTP_PROCESS_FE);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004368}
4369
4370/* Lua execution wrapper for http-response.
4371 * This function uses "hlua_request_act_wrapper" for executing
4372 * the LUA code.
4373 */
4374int hlua_http_res_act_wrapper(struct http_res_rule *rule, struct proxy *px,
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004375 struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004376{
4377 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004378 s, AN_RES_HTTP_PROCESS_BE);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004379}
4380
4381/* tcp-request <*> configuration wrapper. */
4382static int tcp_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4383 struct tcp_rule *rule, char **err)
4384{
4385 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004386 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004387 rule->action = TCP_ACT_CUSTOM;
4388 rule->action_ptr = hlua_tcp_req_act_wrapper;
4389 return 1;
4390}
4391
4392/* tcp-response <*> configuration wrapper. */
4393static int tcp_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4394 struct tcp_rule *rule, char **err)
4395{
4396 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004397 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004398 rule->action = TCP_ACT_CUSTOM;
4399 rule->action_ptr = hlua_tcp_res_act_wrapper;
4400 return 1;
4401}
4402
4403/* http-request <*> configuration wrapper. */
4404static int http_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4405 struct http_req_rule *rule, char **err)
4406{
4407 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
4408 return -1;
4409 rule->action = HTTP_REQ_ACT_CUSTOM_CONT;
4410 rule->action_ptr = hlua_http_req_act_wrapper;
4411 return 1;
4412}
4413
4414/* http-response <*> configuration wrapper. */
4415static int http_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4416 struct http_res_rule *rule, char **err)
4417{
4418 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
4419 return -1;
4420 rule->action = HTTP_RES_ACT_CUSTOM_CONT;
4421 rule->action_ptr = hlua_http_res_act_wrapper;
4422 return 1;
4423}
4424
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004425static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
4426 struct proxy *defpx, const char *file, int line,
4427 char **err, unsigned int *timeout)
4428{
4429 const char *error;
4430
4431 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
4432 if (error && *error != '\0') {
4433 memprintf(err, "%s: invalid timeout", args[0]);
4434 return -1;
4435 }
4436 return 0;
4437}
4438
4439static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
4440 struct proxy *defpx, const char *file, int line,
4441 char **err)
4442{
4443 return hlua_read_timeout(args, section_type, curpx, defpx,
4444 file, line, err, &hlua_timeout_session);
4445}
4446
4447static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
4448 struct proxy *defpx, const char *file, int line,
4449 char **err)
4450{
4451 return hlua_read_timeout(args, section_type, curpx, defpx,
4452 file, line, err, &hlua_timeout_task);
4453}
4454
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004455static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
4456 struct proxy *defpx, const char *file, int line,
4457 char **err)
4458{
4459 char *error;
4460
4461 hlua_nb_instruction = strtoll(args[1], &error, 10);
4462 if (*error != '\0') {
4463 memprintf(err, "%s: invalid number", args[0]);
4464 return -1;
4465 }
4466 return 0;
4467}
4468
Willy Tarreau32f61e22015-03-18 17:54:59 +01004469static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
4470 struct proxy *defpx, const char *file, int line,
4471 char **err)
4472{
4473 char *error;
4474
4475 if (*(args[1]) == 0) {
4476 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
4477 return -1;
4478 }
4479 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
4480 if (*error != '\0') {
4481 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
4482 return -1;
4483 }
4484 return 0;
4485}
4486
4487
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004488/* This function is called by the main configuration key "lua-load". It loads and
4489 * execute an lua file during the parsing of the HAProxy configuration file. It is
4490 * the main lua entry point.
4491 *
4492 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
4493 * occured, otherwise it returns 0.
4494 *
4495 * In some error case, LUA set an error message in top of the stack. This function
4496 * returns this error message in the HAProxy logs and pop it from the stack.
4497 */
4498static int hlua_load(char **args, int section_type, struct proxy *curpx,
4499 struct proxy *defpx, const char *file, int line,
4500 char **err)
4501{
4502 int error;
4503
4504 /* Just load and compile the file. */
4505 error = luaL_loadfile(gL.T, args[1]);
4506 if (error) {
4507 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
4508 lua_pop(gL.T, 1);
4509 return -1;
4510 }
4511
4512 /* If no syntax error where detected, execute the code. */
4513 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
4514 switch (error) {
4515 case LUA_OK:
4516 break;
4517 case LUA_ERRRUN:
4518 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
4519 lua_pop(gL.T, 1);
4520 return -1;
4521 case LUA_ERRMEM:
4522 memprintf(err, "lua out of memory error\n");
4523 return -1;
4524 case LUA_ERRERR:
4525 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
4526 lua_pop(gL.T, 1);
4527 return -1;
4528 case LUA_ERRGCMM:
4529 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
4530 lua_pop(gL.T, 1);
4531 return -1;
4532 default:
4533 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
4534 lua_pop(gL.T, 1);
4535 return -1;
4536 }
4537
4538 return 0;
4539}
4540
4541/* configuration keywords declaration */
4542static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004543 { CFG_GLOBAL, "lua-load", hlua_load },
4544 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
4545 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004546 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01004547 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004548 { 0, NULL, NULL },
4549}};
4550
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004551static struct http_req_action_kw_list http_req_kws = {"lua", { }, {
4552 { "lua", http_req_action_register_lua },
4553 { NULL, NULL }
4554}};
4555
4556static struct http_res_action_kw_list http_res_kws = {"lua", { }, {
4557 { "lua", http_res_action_register_lua },
4558 { NULL, NULL }
4559}};
4560
4561static struct tcp_action_kw_list tcp_req_cont_kws = {"lua", { }, {
4562 { "lua", tcp_req_action_register_lua },
4563 { NULL, NULL }
4564}};
4565
4566static struct tcp_action_kw_list tcp_res_cont_kws = {"lua", { }, {
4567 { "lua", tcp_res_action_register_lua },
4568 { NULL, NULL }
4569}};
4570
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004571int hlua_post_init()
4572{
4573 struct hlua_init_function *init;
4574 const char *msg;
4575 enum hlua_exec ret;
4576
4577 list_for_each_entry(init, &hlua_init_functions, l) {
4578 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
4579 ret = hlua_ctx_resume(&gL, 0);
4580 switch (ret) {
4581 case HLUA_E_OK:
4582 lua_pop(gL.T, -1);
4583 return 1;
4584 case HLUA_E_AGAIN:
4585 Alert("lua init: yield not allowed.\n");
4586 return 0;
4587 case HLUA_E_ERRMSG:
4588 msg = lua_tostring(gL.T, -1);
4589 Alert("lua init: %s.\n", msg);
4590 return 0;
4591 case HLUA_E_ERR:
4592 default:
4593 Alert("lua init: unknown runtime error.\n");
4594 return 0;
4595 }
4596 }
4597 return 1;
4598}
4599
Willy Tarreau32f61e22015-03-18 17:54:59 +01004600/* The memory allocator used by the Lua stack. <ud> is a pointer to the
4601 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
4602 * is the previously allocated size or the kind of object in case of a new
4603 * allocation. <nsize> is the requested new size.
4604 */
4605static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
4606{
4607 struct hlua_mem_allocator *zone = ud;
4608
4609 if (nsize == 0) {
4610 /* it's a free */
4611 if (ptr)
4612 zone->allocated -= osize;
4613 free(ptr);
4614 return NULL;
4615 }
4616
4617 if (!ptr) {
4618 /* it's a new allocation */
4619 if (zone->limit && zone->allocated + nsize > zone->limit)
4620 return NULL;
4621
4622 ptr = malloc(nsize);
4623 if (ptr)
4624 zone->allocated += nsize;
4625 return ptr;
4626 }
4627
4628 /* it's a realloc */
4629 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
4630 return NULL;
4631
4632 ptr = realloc(ptr, nsize);
4633 if (ptr)
4634 zone->allocated += nsize - osize;
4635 return ptr;
4636}
4637
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01004638void hlua_init(void)
4639{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004640 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004641 int idx;
4642 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004643 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004644 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004645#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004646 struct srv_kw *kw;
4647 int tmp_error;
4648 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01004649 char *args[] = { /* SSL client configuration. */
4650 "ssl",
4651 "verify",
4652 "none",
4653 "force-sslv3",
4654 NULL
4655 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004656#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004657
Willy Tarreau87b09662015-04-03 00:22:06 +02004658 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004659 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
4660
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004661 /* Register configuration keywords. */
4662 cfg_register_keywords(&cfg_kws);
4663
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004664 /* Register custom HTTP rules. */
4665 http_req_keywords_register(&http_req_kws);
4666 http_res_keywords_register(&http_res_kws);
4667 tcp_req_cont_keywords_register(&tcp_req_cont_kws);
4668 tcp_res_cont_keywords_register(&tcp_res_cont_kws);
4669
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004670 /* Init main lua stack. */
4671 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004672 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004673 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004674 gL.T = luaL_newstate();
4675 hlua_sethlua(&gL);
4676 gL.Tref = LUA_REFNIL;
4677 gL.task = NULL;
4678
Willy Tarreau32f61e22015-03-18 17:54:59 +01004679 /* change the memory allocators to track memory usage */
4680 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
4681
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004682 /* Initialise lua. */
4683 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004684
4685 /*
4686 *
4687 * Create "core" object.
4688 *
4689 */
4690
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01004691 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004692 lua_newtable(gL.T);
4693
4694 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004695 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004696 hlua_class_const_int(gL.T, log_levels[i], i);
4697
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004698 /* Register special functions. */
4699 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004700 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004701 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004702 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004703 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01004704 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004705 hlua_class_function(gL.T, "sleep", hlua_sleep);
4706 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01004707 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
4708 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
4709 hlua_class_function(gL.T, "set_map", hlua_set_map);
4710 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004711 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004712 hlua_class_function(gL.T, "log", hlua_log);
4713 hlua_class_function(gL.T, "Debug", hlua_log_debug);
4714 hlua_class_function(gL.T, "Info", hlua_log_info);
4715 hlua_class_function(gL.T, "Warning", hlua_log_warning);
4716 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004717
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004718 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004719
4720 /*
4721 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02004722 * Register class Map
4723 *
4724 */
4725
4726 /* This table entry is the object "Map" base. */
4727 lua_newtable(gL.T);
4728
4729 /* register pattern types. */
4730 for (i=0; i<PAT_MATCH_NUM; i++)
4731 hlua_class_const_int(gL.T, pat_match_names[i], i);
4732
4733 /* register constructor. */
4734 hlua_class_function(gL.T, "new", hlua_map_new);
4735
4736 /* Create and fill the metatable. */
4737 lua_newtable(gL.T);
4738
4739 /* Create and fille the __index entry. */
4740 lua_pushstring(gL.T, "__index");
4741 lua_newtable(gL.T);
4742
4743 /* Register . */
4744 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
4745 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
4746
4747 lua_settable(gL.T, -3);
4748
4749 /* Register previous table in the registry with reference and named entry. */
4750 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4751 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4752 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_MAP); /* register class session. */
4753 class_map_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4754
4755 /* Assign the metatable to the mai Map object. */
4756 lua_setmetatable(gL.T, -2);
4757
4758 /* Set a name to the table. */
4759 lua_setglobal(gL.T, "Map");
4760
4761 /*
4762 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004763 * Register class Channel
4764 *
4765 */
4766
4767 /* Create and fill the metatable. */
4768 lua_newtable(gL.T);
4769
4770 /* Create and fille the __index entry. */
4771 lua_pushstring(gL.T, "__index");
4772 lua_newtable(gL.T);
4773
4774 /* Register . */
4775 hlua_class_function(gL.T, "get", hlua_channel_get);
4776 hlua_class_function(gL.T, "dup", hlua_channel_dup);
4777 hlua_class_function(gL.T, "getline", hlua_channel_getline);
4778 hlua_class_function(gL.T, "set", hlua_channel_set);
4779 hlua_class_function(gL.T, "append", hlua_channel_append);
4780 hlua_class_function(gL.T, "send", hlua_channel_send);
4781 hlua_class_function(gL.T, "forward", hlua_channel_forward);
4782 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
4783 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
4784
4785 lua_settable(gL.T, -3);
4786
4787 /* Register previous table in the registry with reference and named entry. */
4788 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4789 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
4790 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4791
4792 /*
4793 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004794 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004795 *
4796 */
4797
4798 /* Create and fill the metatable. */
4799 lua_newtable(gL.T);
4800
4801 /* Create and fille the __index entry. */
4802 lua_pushstring(gL.T, "__index");
4803 lua_newtable(gL.T);
4804
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004805 /* Browse existing fetches and create the associated
4806 * object method.
4807 */
4808 sf = NULL;
4809 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
4810
4811 /* Dont register the keywork if the arguments check function are
4812 * not safe during the runtime.
4813 */
4814 if ((sf->val_args != NULL) &&
4815 (sf->val_args != val_payload_lv) &&
4816 (sf->val_args != val_hdr))
4817 continue;
4818
4819 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4820 * by an underscore.
4821 */
4822 strncpy(trash.str, sf->kw, trash.size);
4823 trash.str[trash.size - 1] = '\0';
4824 for (p = trash.str; *p; p++)
4825 if (*p == '.' || *p == '-' || *p == '+')
4826 *p = '_';
4827
4828 /* Register the function. */
4829 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01004830 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004831 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
4832 lua_settable(gL.T, -3);
4833 }
4834
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004835 lua_settable(gL.T, -3);
4836
4837 /* Register previous table in the registry with reference and named entry. */
4838 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4839 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
4840 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4841
4842 /*
4843 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004844 * Register class Converters
4845 *
4846 */
4847
4848 /* Create and fill the metatable. */
4849 lua_newtable(gL.T);
4850
4851 /* Create and fill the __index entry. */
4852 lua_pushstring(gL.T, "__index");
4853 lua_newtable(gL.T);
4854
4855 /* Browse existing converters and create the associated
4856 * object method.
4857 */
4858 sc = NULL;
4859 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
4860 /* Dont register the keywork if the arguments check function are
4861 * not safe during the runtime.
4862 */
4863 if (sc->val_args != NULL)
4864 continue;
4865
4866 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4867 * by an underscore.
4868 */
4869 strncpy(trash.str, sc->kw, trash.size);
4870 trash.str[trash.size - 1] = '\0';
4871 for (p = trash.str; *p; p++)
4872 if (*p == '.' || *p == '-' || *p == '+')
4873 *p = '_';
4874
4875 /* Register the function. */
4876 lua_pushstring(gL.T, trash.str);
4877 lua_pushlightuserdata(gL.T, sc);
4878 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
4879 lua_settable(gL.T, -3);
4880 }
4881
4882 lua_settable(gL.T, -3);
4883
4884 /* Register previous table in the registry with reference and named entry. */
4885 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4886 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
4887 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4888
4889 /*
4890 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004891 * Register class HTTP
4892 *
4893 */
4894
4895 /* Create and fill the metatable. */
4896 lua_newtable(gL.T);
4897
4898 /* Create and fille the __index entry. */
4899 lua_pushstring(gL.T, "__index");
4900 lua_newtable(gL.T);
4901
4902 /* Register Lua functions. */
4903 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
4904 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
4905 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
4906 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
4907 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
4908 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
4909 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
4910 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
4911 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
4912 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
4913
4914 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
4915 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
4916 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
4917 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
4918 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
4919 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
4920
4921 lua_settable(gL.T, -3);
4922
4923 /* Register previous table in the registry with reference and named entry. */
4924 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4925 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_HTTP); /* register class session. */
4926 class_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4927
4928 /*
4929 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004930 * Register class TXN
4931 *
4932 */
4933
4934 /* Create and fill the metatable. */
4935 lua_newtable(gL.T);
4936
4937 /* Create and fille the __index entry. */
4938 lua_pushstring(gL.T, "__index");
4939 lua_newtable(gL.T);
4940
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004941 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01004942 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
4943 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004944 hlua_class_function(gL.T, "close", hlua_txn_close);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004945 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
4946 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
4947 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004948 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
4949 hlua_class_function(gL.T, "log", hlua_txn_log);
4950 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
4951 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
4952 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
4953 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004954
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004955 lua_settable(gL.T, -3);
4956
4957 /* Register previous table in the registry with reference and named entry. */
4958 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4959 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
4960 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004961
4962 /*
4963 *
4964 * Register class Socket
4965 *
4966 */
4967
4968 /* Create and fill the metatable. */
4969 lua_newtable(gL.T);
4970
4971 /* Create and fille the __index entry. */
4972 lua_pushstring(gL.T, "__index");
4973 lua_newtable(gL.T);
4974
Baptiste Assmann84bb4932015-03-02 21:40:06 +01004975#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004976 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01004977#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004978 hlua_class_function(gL.T, "connect", hlua_socket_connect);
4979 hlua_class_function(gL.T, "send", hlua_socket_send);
4980 hlua_class_function(gL.T, "receive", hlua_socket_receive);
4981 hlua_class_function(gL.T, "close", hlua_socket_close);
4982 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
4983 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
4984 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
4985 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
4986
4987 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
4988
4989 /* Register the garbage collector entry. */
4990 lua_pushstring(gL.T, "__gc");
4991 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
4992 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
4993
4994 /* Register previous table in the registry with reference and named entry. */
4995 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4996 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4997 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
4998 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
4999
5000 /* Proxy and server configuration initialisation. */
5001 memset(&socket_proxy, 0, sizeof(socket_proxy));
5002 init_new_proxy(&socket_proxy);
5003 socket_proxy.parent = NULL;
5004 socket_proxy.last_change = now.tv_sec;
5005 socket_proxy.id = "LUA-SOCKET";
5006 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
5007 socket_proxy.maxconn = 0;
5008 socket_proxy.accept = NULL;
5009 socket_proxy.options2 |= PR_O2_INDEPSTR;
5010 socket_proxy.srv = NULL;
5011 socket_proxy.conn_retries = 0;
5012 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
5013
5014 /* Init TCP server: unchanged parameters */
5015 memset(&socket_tcp, 0, sizeof(socket_tcp));
5016 socket_tcp.next = NULL;
5017 socket_tcp.proxy = &socket_proxy;
5018 socket_tcp.obj_type = OBJ_TYPE_SERVER;
5019 LIST_INIT(&socket_tcp.actconns);
5020 LIST_INIT(&socket_tcp.pendconns);
5021 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
5022 socket_tcp.last_change = 0;
5023 socket_tcp.id = "LUA-TCP-CONN";
5024 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5025 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5026 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
5027
5028 /* XXX: Copy default parameter from default server,
5029 * but the default server is not initialized.
5030 */
5031 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
5032 socket_tcp.minconn = socket_proxy.defsrv.minconn;
5033 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
5034 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
5035 socket_tcp.onerror = socket_proxy.defsrv.onerror;
5036 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5037 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
5038 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5039 socket_tcp.uweight = socket_proxy.defsrv.iweight;
5040 socket_tcp.iweight = socket_proxy.defsrv.iweight;
5041
5042 socket_tcp.check.status = HCHK_STATUS_INI;
5043 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
5044 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
5045 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
5046 socket_tcp.check.server = &socket_tcp;
5047
5048 socket_tcp.agent.status = HCHK_STATUS_INI;
5049 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
5050 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
5051 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
5052 socket_tcp.agent.server = &socket_tcp;
5053
5054 socket_tcp.xprt = &raw_sock;
5055
5056#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005057 /* Init TCP server: unchanged parameters */
5058 memset(&socket_ssl, 0, sizeof(socket_ssl));
5059 socket_ssl.next = NULL;
5060 socket_ssl.proxy = &socket_proxy;
5061 socket_ssl.obj_type = OBJ_TYPE_SERVER;
5062 LIST_INIT(&socket_ssl.actconns);
5063 LIST_INIT(&socket_ssl.pendconns);
5064 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
5065 socket_ssl.last_change = 0;
5066 socket_ssl.id = "LUA-SSL-CONN";
5067 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5068 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5069 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
5070
5071 /* XXX: Copy default parameter from default server,
5072 * but the default server is not initialized.
5073 */
5074 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
5075 socket_ssl.minconn = socket_proxy.defsrv.minconn;
5076 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
5077 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
5078 socket_ssl.onerror = socket_proxy.defsrv.onerror;
5079 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5080 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
5081 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5082 socket_ssl.uweight = socket_proxy.defsrv.iweight;
5083 socket_ssl.iweight = socket_proxy.defsrv.iweight;
5084
5085 socket_ssl.check.status = HCHK_STATUS_INI;
5086 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
5087 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
5088 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
5089 socket_ssl.check.server = &socket_ssl;
5090
5091 socket_ssl.agent.status = HCHK_STATUS_INI;
5092 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
5093 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
5094 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
5095 socket_ssl.agent.server = &socket_ssl;
5096
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005097 socket_ssl.use_ssl = 1;
5098 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005099
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005100 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005101 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
5102 /*
5103 *
5104 * If the keyword is not known, we can search in the registered
5105 * server keywords. This is usefull to configure special SSL
5106 * features like client certificates and ssl_verify.
5107 *
5108 */
5109 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
5110 if (tmp_error != 0) {
5111 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
5112 abort(); /* This must be never arrives because the command line
5113 not editable by the user. */
5114 }
5115 idx += kw->skip;
5116 }
5117 }
5118
5119 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005120 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005121#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01005122}