blob: fb006e6e1ebf32eaacb0f5adb7e613f14b9f84bb [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 Tarreau828824a2015-04-19 17:20:03 +02001449 goto leave;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001450 }
1451
1452 if (!(c->flags & CO_FL_CONNECTED))
Willy Tarreau828824a2015-04-19 17:20:03 +02001453 goto leave;
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);
Willy Tarreau828824a2015-04-19 17:20:03 +02001465
1466 leave:
1467 si_applet_done(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001468}
1469
Willy Tarreau87b09662015-04-03 00:22:06 +02001470/* This function is called when the "struct stream" is destroyed.
1471 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001472 * Wake all the pending signals.
1473 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001474static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001475{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001476 /* Remove my link in the original object. */
1477 if (appctx->ctx.hlua.socket)
1478 appctx->ctx.hlua.socket->s = NULL;
1479
1480 /* Wake all the task waiting for me. */
1481 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1482 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1483}
1484
1485/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001486 * uses this object. If the stream does not exists, just quit.
1487 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001488 * pending signal can rest in the read and write lists. destroy
1489 * it.
1490 */
1491__LJMP static int hlua_socket_gc(lua_State *L)
1492{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001493 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001494 struct appctx *appctx;
1495
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001496 MAY_LJMP(check_args(L, 1, "__gc"));
1497
1498 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001499 if (!socket->s)
1500 return 0;
1501
Willy Tarreau87b09662015-04-03 00:22:06 +02001502 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001503 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaue7dff022015-04-03 01:14:29 +02001504 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001505 socket->s = NULL;
1506 appctx->ctx.hlua.socket = NULL;
1507
1508 return 0;
1509}
1510
1511/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001512 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001513 */
1514__LJMP static int hlua_socket_close(lua_State *L)
1515{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001516 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001517 struct appctx *appctx;
1518
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001519 MAY_LJMP(check_args(L, 1, "close"));
1520
1521 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001522 if (!socket->s)
1523 return 0;
1524
Willy Tarreau87b09662015-04-03 00:22:06 +02001525 /* Close the stream and remove the associated stop task. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02001526 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001527 appctx = objt_appctx(socket->s->si[0].end);
1528 appctx->ctx.hlua.socket = NULL;
1529 socket->s = NULL;
1530
1531 return 0;
1532}
1533
1534/* This Lua function assumes that the stack contain three parameters.
1535 * 1 - USERDATA containing a struct socket
1536 * 2 - INTEGER with values of the macro defined below
1537 * If the integer is -1, we must read at most one line.
1538 * If the integer is -2, we ust read all the data until the
1539 * end of the stream.
1540 * If the integer is positive value, we must read a number of
1541 * bytes corresponding to this value.
1542 */
1543#define HLSR_READ_LINE (-1)
1544#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001545__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001546{
1547 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1548 int wanted = lua_tointeger(L, 2);
1549 struct hlua *hlua = hlua_gethlua(L);
1550 struct appctx *appctx;
1551 int len;
1552 int nblk;
1553 char *blk1;
1554 int len1;
1555 char *blk2;
1556 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001557 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001558 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001559
1560 /* Check if this lua stack is schedulable. */
1561 if (!hlua || !hlua->task)
1562 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1563 "'frontend', 'backend' or 'task'"));
1564
1565 /* check for connection closed. If some data where read, return it. */
1566 if (!socket->s)
1567 goto connection_closed;
1568
Willy Tarreau94aa6172015-03-13 14:19:06 +01001569 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001570 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001571 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001572 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001573 if (nblk < 0) /* Connection close. */
1574 goto connection_closed;
1575 if (nblk == 0) /* No data avalaible. */
1576 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001577
1578 /* remove final \r\n. */
1579 if (nblk == 1) {
1580 if (blk1[len1-1] == '\n') {
1581 len1--;
1582 skip_at_end++;
1583 if (blk1[len1-1] == '\r') {
1584 len1--;
1585 skip_at_end++;
1586 }
1587 }
1588 }
1589 else {
1590 if (blk2[len2-1] == '\n') {
1591 len2--;
1592 skip_at_end++;
1593 if (blk2[len2-1] == '\r') {
1594 len2--;
1595 skip_at_end++;
1596 }
1597 }
1598 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001599 }
1600
1601 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001602 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001603 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001604 if (nblk < 0) /* Connection close. */
1605 goto connection_closed;
1606 if (nblk == 0) /* No data avalaible. */
1607 goto connection_empty;
1608 }
1609
1610 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001611 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001612 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001613 if (nblk < 0) /* Connection close. */
1614 goto connection_closed;
1615 if (nblk == 0) /* No data avalaible. */
1616 goto connection_empty;
1617
1618 if (len1 > wanted) {
1619 nblk = 1;
1620 len1 = wanted;
1621 } if (nblk == 2 && len1 + len2 > wanted)
1622 len2 = wanted - len1;
1623 }
1624
1625 len = len1;
1626
1627 luaL_addlstring(&socket->b, blk1, len1);
1628 if (nblk == 2) {
1629 len += len2;
1630 luaL_addlstring(&socket->b, blk2, len2);
1631 }
1632
1633 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001634 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001635
1636 /* Don't wait anything. */
Willy Tarreau828824a2015-04-19 17:20:03 +02001637 si_applet_done(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001638
1639 /* If the pattern reclaim to read all the data
1640 * in the connection, got out.
1641 */
1642 if (wanted == HLSR_READ_ALL)
1643 goto connection_empty;
1644 else if (wanted >= 0 && len < wanted)
1645 goto connection_empty;
1646
1647 /* Return result. */
1648 luaL_pushresult(&socket->b);
1649 return 1;
1650
1651connection_closed:
1652
1653 /* If the buffer containds data. */
1654 if (socket->b.n > 0) {
1655 luaL_pushresult(&socket->b);
1656 return 1;
1657 }
1658 lua_pushnil(L);
1659 lua_pushstring(L, "connection closed.");
1660 return 2;
1661
1662connection_empty:
1663
1664 appctx = objt_appctx(socket->s->si[0].end);
1665 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1666 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001667 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001668 return 0;
1669}
1670
1671/* This Lus function gets two parameters. The first one can be string
1672 * or a number. If the string is "*l", the user require one line. If
1673 * the string is "*a", the user require all the content of the stream.
1674 * If the value is a number, the user require a number of bytes equal
1675 * to the value. The default value is "*l" (a line).
1676 *
1677 * This paraeter with a variable type is converted in integer. This
1678 * integer takes this values:
1679 * -1 : read a line
1680 * -2 : read all the stream
1681 * >0 : amount if bytes.
1682 *
1683 * The second parameter is optinal. It contains a string that must be
1684 * concatenated with the read data.
1685 */
1686__LJMP static int hlua_socket_receive(struct lua_State *L)
1687{
1688 int wanted = HLSR_READ_LINE;
1689 const char *pattern;
1690 int type;
1691 char *error;
1692 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001693 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001694
1695 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1696 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1697
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001698 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001699
1700 /* check for pattern. */
1701 if (lua_gettop(L) >= 2) {
1702 type = lua_type(L, 2);
1703 if (type == LUA_TSTRING) {
1704 pattern = lua_tostring(L, 2);
1705 if (strcmp(pattern, "*a") == 0)
1706 wanted = HLSR_READ_ALL;
1707 else if (strcmp(pattern, "*l") == 0)
1708 wanted = HLSR_READ_LINE;
1709 else {
1710 wanted = strtoll(pattern, &error, 10);
1711 if (*error != '\0')
1712 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1713 }
1714 }
1715 else if (type == LUA_TNUMBER) {
1716 wanted = lua_tointeger(L, 2);
1717 if (wanted < 0)
1718 WILL_LJMP(luaL_error(L, "Unsupported size."));
1719 }
1720 }
1721
1722 /* Set pattern. */
1723 lua_pushinteger(L, wanted);
1724 lua_replace(L, 2);
1725
1726 /* init bufffer, and fiil it wih prefix. */
1727 luaL_buffinit(L, &socket->b);
1728
1729 /* Check prefix. */
1730 if (lua_gettop(L) >= 3) {
1731 if (lua_type(L, 3) != LUA_TSTRING)
1732 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1733 pattern = lua_tolstring(L, 3, &len);
1734 luaL_addlstring(&socket->b, pattern, len);
1735 }
1736
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001737 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001738}
1739
1740/* Write the Lua input string in the output buffer.
1741 * This fucntion returns a yield if no space are available.
1742 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001743static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001744{
1745 struct hlua_socket *socket;
1746 struct hlua *hlua = hlua_gethlua(L);
1747 struct appctx *appctx;
1748 size_t buf_len;
1749 const char *buf;
1750 int len;
1751 int send_len;
1752 int sent;
1753
1754 /* Check if this lua stack is schedulable. */
1755 if (!hlua || !hlua->task)
1756 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1757 "'frontend', 'backend' or 'task'"));
1758
1759 /* Get object */
1760 socket = MAY_LJMP(hlua_checksocket(L, 1));
1761 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001762 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001763
1764 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001765 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001766 lua_pushinteger(L, -1);
1767 return 1;
1768 }
1769
1770 /* Update the input buffer data. */
1771 buf += sent;
1772 send_len = buf_len - sent;
1773
1774 /* All the data are sent. */
1775 if (sent >= buf_len)
1776 return 1; /* Implicitly return the length sent. */
1777
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001778 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1779 * the request buffer if its not required.
1780 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001781 if (socket->s->req.buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02001782 if (!stream_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001783 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001784 goto hlua_socket_write_yield_return;
1785 }
1786 }
1787
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001788 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001789 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001790 if (len <= 0)
1791 goto hlua_socket_write_yield_return;
1792
1793 /* send data */
1794 if (len < send_len)
1795 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001796 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001797
1798 /* "Not enough space" (-1), "Buffer too little to contain
1799 * the data" (-2) are not expected because the available length
1800 * is tested.
1801 * Other unknown error are also not expected.
1802 */
1803 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001804 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001805 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001806
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001807 MAY_LJMP(hlua_socket_close(L));
1808 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001809 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001810 return 1;
1811 }
1812
1813 /* update buffers. */
Willy Tarreau828824a2015-04-19 17:20:03 +02001814 si_applet_done(&socket->s->si[0]);
Willy Tarreau94aa6172015-03-13 14:19:06 +01001815 socket->s->req.rex = TICK_ETERNITY;
1816 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001817
1818 /* Update length sent. */
1819 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001820 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001821
1822 /* All the data buffer is sent ? */
1823 if (sent + len >= buf_len)
1824 return 1;
1825
1826hlua_socket_write_yield_return:
1827 appctx = objt_appctx(socket->s->si[0].end);
1828 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1829 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001830 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001831 return 0;
1832}
1833
1834/* This function initiate the send of data. It just check the input
1835 * parameters and push an integer in the Lua stack that contain the
1836 * amount of data writed in the buffer. This is used by the function
1837 * "hlua_socket_write_yield" that can yield.
1838 *
1839 * The Lua function gets between 3 and 4 parameters. The first one is
1840 * the associated object. The second is a string buffer. The third is
1841 * a facultative integer that represents where is the buffer position
1842 * of the start of the data that can send. The first byte is the
1843 * position "1". The default value is "1". The fourth argument is a
1844 * facultative integer that represents where is the buffer position
1845 * of the end of the data that can send. The default is the last byte.
1846 */
1847static int hlua_socket_send(struct lua_State *L)
1848{
1849 int i;
1850 int j;
1851 const char *buf;
1852 size_t buf_len;
1853
1854 /* Check number of arguments. */
1855 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1856 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1857
1858 /* Get the string. */
1859 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1860
1861 /* Get and check j. */
1862 if (lua_gettop(L) == 4) {
1863 j = MAY_LJMP(luaL_checkinteger(L, 4));
1864 if (j < 0)
1865 j = buf_len + j + 1;
1866 if (j > buf_len)
1867 j = buf_len + 1;
1868 lua_pop(L, 1);
1869 }
1870 else
1871 j = buf_len;
1872
1873 /* Get and check i. */
1874 if (lua_gettop(L) == 3) {
1875 i = MAY_LJMP(luaL_checkinteger(L, 3));
1876 if (i < 0)
1877 i = buf_len + i + 1;
1878 if (i > buf_len)
1879 i = buf_len + 1;
1880 lua_pop(L, 1);
1881 } else
1882 i = 1;
1883
1884 /* Check bth i and j. */
1885 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001886 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001887 return 1;
1888 }
1889 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001890 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001891 return 1;
1892 }
1893 if (i == 0)
1894 i = 1;
1895 if (j == 0)
1896 j = 1;
1897
1898 /* Pop the string. */
1899 lua_pop(L, 1);
1900
1901 /* Update the buffer length. */
1902 buf += i - 1;
1903 buf_len = j - i + 1;
1904 lua_pushlstring(L, buf, buf_len);
1905
1906 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001907 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001908
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001909 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001910}
1911
1912#define SOCKET_INFO_EXPANDED_FORM "[0000:0000:0000:0000:0000:0000:0000:0000]:12345"
1913static char _socket_info_expanded_form[] = SOCKET_INFO_EXPANDED_FORM;
1914#define SOCKET_INFO_MAX_LEN (sizeof(_socket_info_expanded_form))
1915__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
1916{
1917 static char buffer[SOCKET_INFO_MAX_LEN];
1918 int ret;
1919 int len;
1920 char *p;
1921
1922 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
1923 if (ret <= 0) {
1924 lua_pushnil(L);
1925 return 1;
1926 }
1927
1928 if (ret == AF_UNIX) {
1929 lua_pushstring(L, buffer+1);
1930 return 1;
1931 }
1932 else if (ret == AF_INET6) {
1933 buffer[0] = '[';
1934 len = strlen(buffer);
1935 buffer[len] = ']';
1936 len++;
1937 buffer[len] = ':';
1938 len++;
1939 p = buffer;
1940 }
1941 else if (ret == AF_INET) {
1942 p = buffer + 1;
1943 len = strlen(p);
1944 p[len] = ':';
1945 len++;
1946 }
1947 else {
1948 lua_pushnil(L);
1949 return 1;
1950 }
1951
1952 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
1953 lua_pushnil(L);
1954 return 1;
1955 }
1956
1957 lua_pushstring(L, p);
1958 return 1;
1959}
1960
1961/* Returns information about the peer of the connection. */
1962__LJMP static int hlua_socket_getpeername(struct lua_State *L)
1963{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001964 struct hlua_socket *socket;
1965 struct connection *conn;
1966
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001967 MAY_LJMP(check_args(L, 1, "getpeername"));
1968
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001969 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001970
1971 /* Check if the tcp object is avalaible. */
1972 if (!socket->s) {
1973 lua_pushnil(L);
1974 return 1;
1975 }
1976
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001977 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001978 if (!conn) {
1979 lua_pushnil(L);
1980 return 1;
1981 }
1982
1983 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
1984 unsigned int salen = sizeof(conn->addr.to);
1985 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
1986 lua_pushnil(L);
1987 return 1;
1988 }
1989 conn->flags |= CO_FL_ADDR_TO_SET;
1990 }
1991
1992 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
1993}
1994
1995/* Returns information about my connection side. */
1996static int hlua_socket_getsockname(struct lua_State *L)
1997{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001998 struct hlua_socket *socket;
1999 struct connection *conn;
2000
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002001 MAY_LJMP(check_args(L, 1, "getsockname"));
2002
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002003 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002004
2005 /* Check if the tcp object is avalaible. */
2006 if (!socket->s) {
2007 lua_pushnil(L);
2008 return 1;
2009 }
2010
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002011 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002012 if (!conn) {
2013 lua_pushnil(L);
2014 return 1;
2015 }
2016
2017 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
2018 unsigned int salen = sizeof(conn->addr.from);
2019 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
2020 lua_pushnil(L);
2021 return 1;
2022 }
2023 conn->flags |= CO_FL_ADDR_FROM_SET;
2024 }
2025
2026 return hlua_socket_info(L, &conn->addr.from);
2027}
2028
2029/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002030static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002031 .obj_type = OBJ_TYPE_APPLET,
2032 .name = "<LUA_TCP>",
2033 .fct = hlua_socket_handler,
2034 .release = hlua_socket_release,
2035};
2036
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002037__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002038{
2039 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2040 struct hlua *hlua = hlua_gethlua(L);
2041 struct appctx *appctx;
2042
2043 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002044 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002045 lua_pushnil(L);
2046 lua_pushstring(L, "Can't connect");
2047 return 2;
2048 }
2049
2050 appctx = objt_appctx(socket->s->si[0].end);
2051
2052 /* Check for connection established. */
2053 if (appctx->ctx.hlua.connected) {
2054 lua_pushinteger(L, 1);
2055 return 1;
2056 }
2057
2058 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2059 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002060 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002061 return 0;
2062}
2063
2064/* This function fail or initite the connection. */
2065__LJMP static int hlua_socket_connect(struct lua_State *L)
2066{
2067 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002068 int port;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002069 const char *ip;
2070 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002071 struct hlua *hlua;
2072 struct appctx *appctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002073
2074 MAY_LJMP(check_args(L, 3, "connect"));
2075
2076 /* Get args. */
2077 socket = MAY_LJMP(hlua_checksocket(L, 1));
2078 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002079 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002080
Willy Tarreau350f4872014-11-28 14:42:25 +01002081 conn = si_alloc_conn(&socket->s->si[1], 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002082 if (!conn)
2083 WILL_LJMP(luaL_error(L, "connect: internal error"));
2084
2085 /* Parse ip address. */
2086 conn->addr.to.ss_family = AF_UNSPEC;
2087 if (!str2ip2(ip, &conn->addr.to, 0))
2088 WILL_LJMP(luaL_error(L, "connect: cannot parse ip address '%s'", ip));
2089
2090 /* Set port. */
2091 if (conn->addr.to.ss_family == AF_INET)
2092 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2093 else if (conn->addr.to.ss_family == AF_INET6)
2094 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2095
2096 /* it is important not to call the wakeup function directly but to
2097 * pass through task_wakeup(), because this one knows how to apply
2098 * priorities to tasks.
2099 */
2100 task_wakeup(socket->s->task, TASK_WOKEN_INIT);
2101
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002102 hlua = hlua_gethlua(L);
2103 appctx = objt_appctx(socket->s->si[0].end);
2104 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2105 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002106 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002107
2108 return 0;
2109}
2110
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002111#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002112__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2113{
2114 struct hlua_socket *socket;
2115
2116 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2117 socket = MAY_LJMP(hlua_checksocket(L, 1));
2118 socket->s->target = &socket_ssl.obj_type;
2119 return MAY_LJMP(hlua_socket_connect(L));
2120}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002121#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002122
2123__LJMP static int hlua_socket_setoption(struct lua_State *L)
2124{
2125 return 0;
2126}
2127
2128__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2129{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002130 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002131 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002132
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002133 MAY_LJMP(check_args(L, 2, "settimeout"));
2134
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002135 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002136 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002137
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002138 socket->s->req.rto = tmout;
2139 socket->s->req.wto = tmout;
2140 socket->s->res.rto = tmout;
2141 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002142
2143 return 0;
2144}
2145
2146__LJMP static int hlua_socket_new(lua_State *L)
2147{
2148 struct hlua_socket *socket;
2149 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002150 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002151 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002152 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002153
2154 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002155 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002156 hlua_pusherror(L, "socket: full stack");
2157 goto out_fail_conf;
2158 }
2159
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002160 /* Create the object: obj[0] = userdata. */
2161 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002162 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002163 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002164 memset(socket, 0, sizeof(*socket));
2165
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002166 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002167 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002168 hlua_pusherror(L, "socket: uninitialized pools.");
2169 goto out_fail_conf;
2170 }
2171
Willy Tarreau87b09662015-04-03 00:22:06 +02002172 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002173 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2174 lua_setmetatable(L, -2);
2175
Willy Tarreaud420a972015-04-06 00:39:18 +02002176 /* Create the applet context */
2177 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002178 if (!appctx) {
2179 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002180 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002181 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002182
Willy Tarreaud420a972015-04-06 00:39:18 +02002183 appctx->ctx.hlua.socket = socket;
2184 appctx->ctx.hlua.connected = 0;
2185 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2186 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002187
Willy Tarreaud420a972015-04-06 00:39:18 +02002188 /* Now create a session, task and stream for this applet */
2189 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2190 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002191 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002192 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002193 }
2194
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002195 task = task_new();
2196 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002197 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002198 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002199 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002200 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002201
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002202 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002203 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002204 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002205 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002206 }
2207
Willy Tarreaud420a972015-04-06 00:39:18 +02002208 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002209 socket->s = strm;
2210 strm->hlua.T = NULL;
2211 strm->hlua.Tref = LUA_REFNIL;
2212 strm->hlua.Mref = LUA_REFNIL;
2213 strm->hlua.nargs = 0;
2214 strm->hlua.flags = 0;
2215 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002216
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002217 /* Configure "right" stream interface. this "si" is used to connect
2218 * and retrieve data from the server. The connection is initialized
2219 * with the "struct server".
2220 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002221 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002222
2223 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002224 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2225 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002226
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002227 /* Update statistics counters. */
2228 socket_proxy.feconn++; /* beconn will be increased later */
2229 jobs++;
2230 totalconn++;
2231
2232 /* Return yield waiting for connection. */
2233 return 1;
2234
Willy Tarreaud420a972015-04-06 00:39:18 +02002235 out_fail_stream:
2236 task_free(task);
2237 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002238 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002239 out_fail_sess:
2240 appctx_free(appctx);
2241 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002242 WILL_LJMP(lua_error(L));
2243 return 0;
2244}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002245
2246/*
2247 *
2248 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002249 * Class Channel
2250 *
2251 *
2252 */
2253
2254/* Returns the struct hlua_channel join to the class channel in the
2255 * stack entry "ud" or throws an argument error.
2256 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002257__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002258{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002259 return (struct channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002260}
2261
Willy Tarreau47860ed2015-03-10 14:07:50 +01002262/* Pushes the channel onto the top of the stack. If the stask does not have a
2263 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002264 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002265static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002266{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002267 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002268 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002269 return 0;
2270
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002271 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002272 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002273 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002274
2275 /* Pop a class sesison metatable and affect it to the userdata. */
2276 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2277 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002278 return 1;
2279}
2280
2281/* Duplicate all the data present in the input channel and put it
2282 * in a string LUA variables. Returns -1 and push a nil value in
2283 * the stack if the channel is closed and all the data are consumed,
2284 * returns 0 if no data are available, otherwise it returns the length
2285 * of the builded string.
2286 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002287static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002288{
2289 char *blk1;
2290 char *blk2;
2291 int len1;
2292 int len2;
2293 int ret;
2294 luaL_Buffer b;
2295
Willy Tarreau47860ed2015-03-10 14:07:50 +01002296 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002297 if (unlikely(ret == 0))
2298 return 0;
2299
2300 if (unlikely(ret < 0)) {
2301 lua_pushnil(L);
2302 return -1;
2303 }
2304
2305 luaL_buffinit(L, &b);
2306 luaL_addlstring(&b, blk1, len1);
2307 if (unlikely(ret == 2))
2308 luaL_addlstring(&b, blk2, len2);
2309 luaL_pushresult(&b);
2310
2311 if (unlikely(ret == 2))
2312 return len1 + len2;
2313 return len1;
2314}
2315
2316/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2317 * a yield. This function keep the data in the buffer.
2318 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002319__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002320{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002321 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002322
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002323 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2324
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002325 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002326 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002327 return 1;
2328}
2329
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002330/* Check arguments for the function "hlua_channel_dup_yield". */
2331__LJMP static int hlua_channel_dup(lua_State *L)
2332{
2333 MAY_LJMP(check_args(L, 1, "dup"));
2334 MAY_LJMP(hlua_checkchannel(L, 1));
2335 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2336}
2337
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002338/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2339 * a yield. This function consumes the data in the buffer. It returns
2340 * a string containing the data or a nil pointer if no data are available
2341 * and the channel is closed.
2342 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002343__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002344{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002345 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002346 int ret;
2347
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002348 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002349
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002350 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002351 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002352 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002353
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002354 if (unlikely(ret == -1))
2355 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002356
Willy Tarreau47860ed2015-03-10 14:07:50 +01002357 chn->buf->i -= ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002358 return 1;
2359}
2360
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002361/* Check arguments for the fucntion "hlua_channel_get_yield". */
2362__LJMP static int hlua_channel_get(lua_State *L)
2363{
2364 MAY_LJMP(check_args(L, 1, "get"));
2365 MAY_LJMP(hlua_checkchannel(L, 1));
2366 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2367}
2368
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002369/* This functions consumes and returns one line. If the channel is closed,
2370 * and the last data does not contains a final '\n', the data are returned
2371 * without the final '\n'. When no more data are avalaible, it returns nil
2372 * value.
2373 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002374__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002375{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002376 char *blk1;
2377 char *blk2;
2378 int len1;
2379 int len2;
2380 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002381 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002382 int ret;
2383 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002384
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002385 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2386
Willy Tarreau47860ed2015-03-10 14:07:50 +01002387 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002388 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002389 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002390
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002391 if (ret == -1) {
2392 lua_pushnil(L);
2393 return 1;
2394 }
2395
2396 luaL_buffinit(L, &b);
2397 luaL_addlstring(&b, blk1, len1);
2398 len = len1;
2399 if (unlikely(ret == 2)) {
2400 luaL_addlstring(&b, blk2, len2);
2401 len += len2;
2402 }
2403 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002404 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002405 return 1;
2406}
2407
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002408/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2409__LJMP static int hlua_channel_getline(lua_State *L)
2410{
2411 MAY_LJMP(check_args(L, 1, "getline"));
2412 MAY_LJMP(hlua_checkchannel(L, 1));
2413 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2414}
2415
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002416/* This function takes a string as input, and append it at the
2417 * input side of channel. If the data is too big, but a space
2418 * is probably available after sending some data, the function
2419 * yield. If the data is bigger than the buffer, or if the
2420 * channel is closed, it returns -1. otherwise, it returns the
2421 * amount of data writed.
2422 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002423__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002424{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002425 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002426 size_t len;
2427 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2428 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2429 int ret;
2430 int max;
2431
Willy Tarreau47860ed2015-03-10 14:07:50 +01002432 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002433 if (max > len - l)
2434 max = len - l;
2435
Willy Tarreau47860ed2015-03-10 14:07:50 +01002436 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002437 if (ret == -2 || ret == -3) {
2438 lua_pushinteger(L, -1);
2439 return 1;
2440 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002441 if (ret == -1) {
2442 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002443 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002444 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002445 l += ret;
2446 lua_pop(L, 1);
2447 lua_pushinteger(L, l);
2448
Willy Tarreau47860ed2015-03-10 14:07:50 +01002449 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2450 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002451 /* There are no space avalaible, and the output buffer is empty.
2452 * in this case, we cannot add more data, so we cannot yield,
2453 * we return the amount of copyied data.
2454 */
2455 return 1;
2456 }
2457 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002458 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002459 return 1;
2460}
2461
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002462/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002463 * of the writed string, or -1 if the channel is closed or if the
2464 * buffer size is too little for the data.
2465 */
2466__LJMP static int hlua_channel_append(lua_State *L)
2467{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002468 size_t len;
2469
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002470 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002471 MAY_LJMP(hlua_checkchannel(L, 1));
2472 MAY_LJMP(luaL_checklstring(L, 2, &len));
2473 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002474 lua_pushinteger(L, 0);
2475
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002476 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002477}
2478
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002479/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002480 * his process by cleaning the buffer. The result is a replacement
2481 * of the current data. It returns the length of the writed string,
2482 * or -1 if the channel is closed or if the buffer size is too
2483 * little for the data.
2484 */
2485__LJMP static int hlua_channel_set(lua_State *L)
2486{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002487 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002488
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002489 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002490 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002491 lua_pushinteger(L, 0);
2492
Willy Tarreau47860ed2015-03-10 14:07:50 +01002493 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002494
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002495 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002496}
2497
2498/* Append data in the output side of the buffer. This data is immediatly
2499 * sent. The fcuntion returns the ammount of data writed. If the buffer
2500 * cannot contains the data, the function yield. The function returns -1
2501 * if the channel is closed.
2502 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002503__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002504{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002505 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002506 size_t len;
2507 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2508 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2509 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002510 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002511
Willy Tarreau47860ed2015-03-10 14:07:50 +01002512 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002513 lua_pushinteger(L, -1);
2514 return 1;
2515 }
2516
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002517 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2518 * the request buffer if its not required.
2519 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002520 if (chn->buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02002521 if (!stream_alloc_recv_buffer(chn)) {
Willy Tarreau47860ed2015-03-10 14:07:50 +01002522 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002523 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002524 }
2525 }
2526
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002527 /* the writed data will be immediatly sent, so we can check
2528 * the avalaible space without taking in account the reserve.
2529 * The reserve is guaranted for the processing of incoming
2530 * data, because the buffer will be flushed.
2531 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002532 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002533
2534 /* If there are no space avalaible, and the output buffer is empty.
2535 * in this case, we cannot add more data, so we cannot yield,
2536 * we return the amount of copyied data.
2537 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002538 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002539 return 1;
2540
2541 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002542 if (max > len - l)
2543 max = len - l;
2544
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002545 /* The buffer avalaible size may be not contiguous. This test
2546 * detects a non contiguous buffer and realign it.
2547 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002548 if (bi_space_for_replace(chn->buf) < max)
2549 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002550
2551 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002552 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002553
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002554 /* buffer replace considers that the input part is filled.
2555 * so, I must forward these new data in the output part.
2556 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002557 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002558
2559 l += max;
2560 lua_pop(L, 1);
2561 lua_pushinteger(L, l);
2562
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002563 /* If there are no space avalaible, and the output buffer is empty.
2564 * in this case, we cannot add more data, so we cannot yield,
2565 * we return the amount of copyied data.
2566 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002567 max = chn->buf->size - buffer_len(chn->buf);
2568 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002569 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002570
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002571 if (l < len) {
2572 /* If we are waiting for space in the response buffer, we
2573 * must set the flag WAKERESWR. This flag required the task
2574 * wake up if any activity is detected on the response buffer.
2575 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002576 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002577 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002578 else
2579 HLUA_SET_WAKEREQWR(hlua);
2580 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002581 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002582
2583 return 1;
2584}
2585
2586/* Just a wraper of "_hlua_channel_send". This wrapper permits
2587 * yield the LUA process, and resume it without checking the
2588 * input arguments.
2589 */
2590__LJMP static int hlua_channel_send(lua_State *L)
2591{
2592 MAY_LJMP(check_args(L, 2, "send"));
2593 lua_pushinteger(L, 0);
2594
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002595 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002596}
2597
2598/* This function forward and amount of butes. The data pass from
2599 * the input side of the buffer to the output side, and can be
2600 * forwarded. This function never fails.
2601 *
2602 * The Lua function takes an amount of bytes to be forwarded in
2603 * imput. It returns the number of bytes forwarded.
2604 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002605__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002606{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002607 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002608 int len;
2609 int l;
2610 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002611 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002612
2613 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2614 len = MAY_LJMP(luaL_checkinteger(L, 2));
2615 l = MAY_LJMP(luaL_checkinteger(L, -1));
2616
2617 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002618 if (max > chn->buf->i)
2619 max = chn->buf->i;
2620 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002621 l += max;
2622
2623 lua_pop(L, 1);
2624 lua_pushinteger(L, l);
2625
2626 /* Check if it miss bytes to forward. */
2627 if (l < len) {
2628 /* The the input channel or the output channel are closed, we
2629 * must return the amount of data forwarded.
2630 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002631 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002632 return 1;
2633
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002634 /* If we are waiting for space data in the response buffer, we
2635 * must set the flag WAKERESWR. This flag required the task
2636 * wake up if any activity is detected on the response buffer.
2637 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002638 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002639 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002640 else
2641 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002642
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002643 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002644 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002645 }
2646
2647 return 1;
2648}
2649
2650/* Just check the input and prepare the stack for the previous
2651 * function "hlua_channel_forward_yield"
2652 */
2653__LJMP static int hlua_channel_forward(lua_State *L)
2654{
2655 MAY_LJMP(check_args(L, 2, "forward"));
2656 MAY_LJMP(hlua_checkchannel(L, 1));
2657 MAY_LJMP(luaL_checkinteger(L, 2));
2658
2659 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002660 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002661}
2662
2663/* Just returns the number of bytes available in the input
2664 * side of the buffer. This function never fails.
2665 */
2666__LJMP static int hlua_channel_get_in_len(lua_State *L)
2667{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002668 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002669
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002670 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002671 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002672 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002673 return 1;
2674}
2675
2676/* Just returns the number of bytes available in the output
2677 * side of the buffer. This function never fails.
2678 */
2679__LJMP static int hlua_channel_get_out_len(lua_State *L)
2680{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002681 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002682
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002683 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002684 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002685 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002686 return 1;
2687}
2688
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002689/*
2690 *
2691 *
2692 * Class Fetches
2693 *
2694 *
2695 */
2696
2697/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002698 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002699 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002700__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002701{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002702 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002703}
2704
2705/* This function creates and push in the stack a fetch object according
2706 * with a current TXN.
2707 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002708static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002709{
Willy Tarreau7073c472015-04-06 11:15:40 +02002710 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002711
2712 /* Check stack size. */
2713 if (!lua_checkstack(L, 3))
2714 return 0;
2715
2716 /* Create the object: obj[0] = userdata.
2717 * Note that the base of the Fetches object is the
2718 * transaction object.
2719 */
2720 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002721 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002722 lua_rawseti(L, -2, 0);
2723
Willy Tarreau7073c472015-04-06 11:15:40 +02002724 hsmp->s = txn->s;
2725 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002726 hsmp->stringsafe = stringsafe;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002727
2728 /* Pop a class sesison metatable and affect it to the userdata. */
2729 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2730 lua_setmetatable(L, -2);
2731
2732 return 1;
2733}
2734
2735/* This function is an LUA binding. It is called with each sample-fetch.
2736 * It uses closure argument to store the associated sample-fetch. It
2737 * returns only one argument or throws an error. An error is thrown
2738 * only if an error is encountered during the argument parsing. If
2739 * the "sample-fetch" function fails, nil is returned.
2740 */
2741__LJMP static int hlua_run_sample_fetch(lua_State *L)
2742{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002743 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002744 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002745 struct arg args[ARGM_NBARGS + 1];
2746 int i;
2747 struct sample smp;
2748
2749 /* Get closure arguments. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002750 f = (struct sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002751
2752 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002753 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002754
2755 /* Get extra arguments. */
2756 for (i = 0; i < lua_gettop(L) - 1; i++) {
2757 if (i >= ARGM_NBARGS)
2758 break;
2759 hlua_lua2arg(L, i + 2, &args[i]);
2760 }
2761 args[i].type = ARGT_STOP;
2762
2763 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002764 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002765
2766 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002767 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002768 lua_pushfstring(L, "error in arguments");
2769 WILL_LJMP(lua_error(L));
2770 }
2771
2772 /* Initialise the sample. */
2773 memset(&smp, 0, sizeof(smp));
2774
2775 /* Run the sample fetch process. */
Willy Tarreau192252e2015-04-04 01:47:55 +02002776 if (!f->process(hsmp->p, hsmp->s->sess, hsmp->s, 0, args, &smp, f->kw, f->private)) {
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002777 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002778 lua_pushstring(L, "");
2779 else
2780 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002781 return 1;
2782 }
2783
2784 /* Convert the returned sample in lua value. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002785 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002786 hlua_smp2lua_str(L, &smp);
2787 else
2788 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002789 return 1;
2790}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002791
2792/*
2793 *
2794 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002795 * Class Converters
2796 *
2797 *
2798 */
2799
2800/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002801 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002802 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002803__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002804{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002805 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002806}
2807
2808/* This function creates and push in the stack a Converters object
2809 * according with a current TXN.
2810 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002811static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002812{
Willy Tarreau7073c472015-04-06 11:15:40 +02002813 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002814
2815 /* Check stack size. */
2816 if (!lua_checkstack(L, 3))
2817 return 0;
2818
2819 /* Create the object: obj[0] = userdata.
2820 * Note that the base of the Converters object is the
2821 * same than the TXN object.
2822 */
2823 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002824 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002825 lua_rawseti(L, -2, 0);
2826
Willy Tarreau7073c472015-04-06 11:15:40 +02002827 hsmp->s = txn->s;
2828 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002829 hsmp->stringsafe = stringsafe;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002830
Willy Tarreau87b09662015-04-03 00:22:06 +02002831 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002832 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
2833 lua_setmetatable(L, -2);
2834
2835 return 1;
2836}
2837
2838/* This function is an LUA binding. It is called with each converter.
2839 * It uses closure argument to store the associated converter. It
2840 * returns only one argument or throws an error. An error is thrown
2841 * only if an error is encountered during the argument parsing. If
2842 * the converter function function fails, nil is returned.
2843 */
2844__LJMP static int hlua_run_sample_conv(lua_State *L)
2845{
Willy Tarreauda5f1082015-04-06 11:17:13 +02002846 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002847 struct sample_conv *conv;
2848 struct arg args[ARGM_NBARGS + 1];
2849 int i;
2850 struct sample smp;
2851
2852 /* Get closure arguments. */
2853 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
2854
2855 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002856 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002857
2858 /* Get extra arguments. */
2859 for (i = 0; i < lua_gettop(L) - 2; i++) {
2860 if (i >= ARGM_NBARGS)
2861 break;
2862 hlua_lua2arg(L, i + 3, &args[i]);
2863 }
2864 args[i].type = ARGT_STOP;
2865
2866 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002867 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002868
2869 /* Run the special args checker. */
2870 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
2871 hlua_pusherror(L, "error in arguments");
2872 WILL_LJMP(lua_error(L));
2873 }
2874
2875 /* Initialise the sample. */
2876 if (!hlua_lua2smp(L, 2, &smp)) {
2877 hlua_pusherror(L, "error in the input argument");
2878 WILL_LJMP(lua_error(L));
2879 }
2880
2881 /* Apply expected cast. */
2882 if (!sample_casts[smp.type][conv->in_type]) {
2883 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
2884 smp_to_type[smp.type], smp_to_type[conv->in_type]);
2885 WILL_LJMP(lua_error(L));
2886 }
2887 if (sample_casts[smp.type][conv->in_type] != c_none &&
2888 !sample_casts[smp.type][conv->in_type](&smp)) {
2889 hlua_pusherror(L, "error during the input argument casting");
2890 WILL_LJMP(lua_error(L));
2891 }
2892
2893 /* Run the sample conversion process. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002894 if (!conv->process(hsmp->s, args, &smp, conv->private)) {
2895 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002896 lua_pushstring(L, "");
2897 else
2898 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002899 return 1;
2900 }
2901
2902 /* Convert the returned sample in lua value. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002903 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002904 hlua_smp2lua_str(L, &smp);
2905 else
2906 hlua_smp2lua(L, &smp);
2907 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002908}
2909
2910/*
2911 *
2912 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002913 * Class HTTP
2914 *
2915 *
2916 */
2917
2918/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002919 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002920 */
2921__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
2922{
2923 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
2924}
2925
2926/* This function creates and push in the stack a HTTP object
2927 * according with a current TXN.
2928 */
2929static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
2930{
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002931 struct hlua_txn *htxn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002932
2933 /* Check stack size. */
2934 if (!lua_checkstack(L, 3))
2935 return 0;
2936
2937 /* Create the object: obj[0] = userdata.
2938 * Note that the base of the Converters object is the
2939 * same than the TXN object.
2940 */
2941 lua_newtable(L);
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002942 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002943 lua_rawseti(L, -2, 0);
2944
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002945 htxn->s = txn->s;
2946 htxn->p = txn->p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002947
Willy Tarreau87b09662015-04-03 00:22:06 +02002948 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002949 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
2950 lua_setmetatable(L, -2);
2951
2952 return 1;
2953}
2954
2955/* This function creates ans returns an array of HTTP headers.
2956 * This function does not fails. It is used as wrapper with the
2957 * 2 following functions.
2958 */
2959__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
2960{
2961 const char *cur_ptr, *cur_next, *p;
2962 int old_idx, cur_idx;
2963 struct hdr_idx_elem *cur_hdr;
2964 const char *hn, *hv;
2965 int hnl, hvl;
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01002966 int type;
2967 const char *in;
2968 char *out;
2969 int len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002970
2971 /* Create the table. */
2972 lua_newtable(L);
2973
Willy Tarreaueee5b512015-04-03 23:46:31 +02002974 if (!htxn->s->txn)
2975 return 1;
2976
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002977 /* Build array of headers. */
2978 old_idx = 0;
Willy Tarreaueee5b512015-04-03 23:46:31 +02002979 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002980
2981 while (1) {
Willy Tarreaueee5b512015-04-03 23:46:31 +02002982 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002983 if (!cur_idx)
2984 break;
2985 old_idx = cur_idx;
2986
Willy Tarreaueee5b512015-04-03 23:46:31 +02002987 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002988 cur_ptr = cur_next;
2989 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
2990
2991 /* Now we have one full header at cur_ptr of len cur_hdr->len,
2992 * and the next header starts at cur_next. We'll check
2993 * this header in the list as well as against the default
2994 * rule.
2995 */
2996
2997 /* look for ': *'. */
2998 hn = cur_ptr;
2999 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
3000 if (p >= cur_ptr+cur_hdr->len)
3001 continue;
3002 hnl = p - hn;
3003 p++;
3004 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
3005 p++;
3006 if (p >= cur_ptr+cur_hdr->len)
3007 continue;
3008 hv = p;
3009 hvl = cur_ptr+cur_hdr->len-p;
3010
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003011 /* Lowercase the key. Don't check the size of trash, it have
3012 * the size of one buffer and the input data contains in one
3013 * buffer.
3014 */
3015 out = trash.str;
3016 for (in=hn; in<hn+hnl; in++, out++)
3017 *out = tolower(*in);
3018 *out = '\0';
3019
3020 /* Check for existing entry:
3021 * assume that the table is on the top of the stack, and
3022 * push the key in the stack, the function lua_gettable()
3023 * perform the lookup.
3024 */
3025 lua_pushlstring(L, trash.str, hnl);
3026 lua_gettable(L, -2);
3027 type = lua_type(L, -1);
3028
3029 switch (type) {
3030 case LUA_TNIL:
3031 /* Table not found, create it. */
3032 lua_pop(L, 1); /* remove the nil value. */
3033 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
3034 lua_newtable(L); /* create and push empty table. */
3035 lua_pushlstring(L, hv, hvl); /* push header value. */
3036 lua_rawseti(L, -2, 0); /* index header value (pop it). */
3037 lua_rawset(L, -3); /* index new table with header name (pop the values). */
3038 break;
3039
3040 case LUA_TTABLE:
3041 /* Entry found: push the value in the table. */
3042 len = lua_rawlen(L, -1);
3043 lua_pushlstring(L, hv, hvl); /* push header value. */
3044 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
3045 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
3046 break;
3047
3048 default:
3049 /* Other cases are errors. */
3050 hlua_pusherror(L, "internal error during the parsing of headers.");
3051 WILL_LJMP(lua_error(L));
3052 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003053 }
3054
3055 return 1;
3056}
3057
3058__LJMP static int hlua_http_req_get_headers(lua_State *L)
3059{
3060 struct hlua_txn *htxn;
3061
3062 MAY_LJMP(check_args(L, 1, "req_get_headers"));
3063 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3064
Willy Tarreaueee5b512015-04-03 23:46:31 +02003065 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003066}
3067
3068__LJMP static int hlua_http_res_get_headers(lua_State *L)
3069{
3070 struct hlua_txn *htxn;
3071
3072 MAY_LJMP(check_args(L, 1, "res_get_headers"));
3073 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3074
Willy Tarreaueee5b512015-04-03 23:46:31 +02003075 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003076}
3077
3078/* This function replace full header, or just a value in
3079 * the request or in the response. It is a wrapper fir the
3080 * 4 following functions.
3081 */
3082__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
3083 struct http_msg *msg, int action)
3084{
3085 size_t name_len;
3086 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3087 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
3088 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
3089 struct my_regex re;
3090
3091 if (!regex_comp(reg, &re, 1, 1, NULL))
3092 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
3093
3094 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
3095 regex_free(&re);
3096 return 0;
3097}
3098
3099__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
3100{
3101 struct hlua_txn *htxn;
3102
3103 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3104 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3105
Willy Tarreaueee5b512015-04-03 23:46:31 +02003106 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 +01003107}
3108
3109__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
3110{
3111 struct hlua_txn *htxn;
3112
3113 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
3114 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3115
Willy Tarreaueee5b512015-04-03 23:46:31 +02003116 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 +01003117}
3118
3119__LJMP static int hlua_http_req_rep_val(lua_State *L)
3120{
3121 struct hlua_txn *htxn;
3122
3123 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3124 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3125
Willy Tarreaueee5b512015-04-03 23:46:31 +02003126 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 +01003127}
3128
3129__LJMP static int hlua_http_res_rep_val(lua_State *L)
3130{
3131 struct hlua_txn *htxn;
3132
3133 MAY_LJMP(check_args(L, 4, "res_rep_val"));
3134 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3135
Willy Tarreaueee5b512015-04-03 23:46:31 +02003136 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 +01003137}
3138
3139/* This function deletes all the occurences of an header.
3140 * It is a wrapper for the 2 following functions.
3141 */
3142__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3143{
3144 size_t len;
3145 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3146 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02003147 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003148
3149 ctx.idx = 0;
3150 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
3151 http_remove_header2(msg, &txn->hdr_idx, &ctx);
3152 return 0;
3153}
3154
3155__LJMP static int hlua_http_req_del_hdr(lua_State *L)
3156{
3157 struct hlua_txn *htxn;
3158
3159 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3160 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3161
Willy Tarreaueee5b512015-04-03 23:46:31 +02003162 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003163}
3164
3165__LJMP static int hlua_http_res_del_hdr(lua_State *L)
3166{
3167 struct hlua_txn *htxn;
3168
3169 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3170 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3171
Willy Tarreaueee5b512015-04-03 23:46:31 +02003172 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003173}
3174
3175/* This function adds an header. It is a wrapper used by
3176 * the 2 following functions.
3177 */
3178__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3179{
3180 size_t name_len;
3181 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3182 size_t value_len;
3183 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
3184 char *p;
3185
3186 /* Check length. */
3187 trash.len = value_len + name_len + 2;
3188 if (trash.len > trash.size)
3189 return 0;
3190
3191 /* Creates the header string. */
3192 p = trash.str;
3193 memcpy(p, name, name_len);
3194 p += name_len;
3195 *p = ':';
3196 p++;
3197 *p = ' ';
3198 p++;
3199 memcpy(p, value, value_len);
3200
Willy Tarreaueee5b512015-04-03 23:46:31 +02003201 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003202 trash.str, trash.len) != 0);
3203
3204 return 0;
3205}
3206
3207__LJMP static int hlua_http_req_add_hdr(lua_State *L)
3208{
3209 struct hlua_txn *htxn;
3210
3211 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
3212 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3213
Willy Tarreaueee5b512015-04-03 23:46:31 +02003214 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003215}
3216
3217__LJMP static int hlua_http_res_add_hdr(lua_State *L)
3218{
3219 struct hlua_txn *htxn;
3220
3221 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
3222 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3223
Willy Tarreaueee5b512015-04-03 23:46:31 +02003224 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003225}
3226
3227static int hlua_http_req_set_hdr(lua_State *L)
3228{
3229 struct hlua_txn *htxn;
3230
3231 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
3232 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3233
Willy Tarreaueee5b512015-04-03 23:46:31 +02003234 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
3235 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003236}
3237
3238static int hlua_http_res_set_hdr(lua_State *L)
3239{
3240 struct hlua_txn *htxn;
3241
3242 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
3243 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3244
Willy Tarreaueee5b512015-04-03 23:46:31 +02003245 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
3246 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003247}
3248
3249/* This function set the method. */
3250static int hlua_http_req_set_meth(lua_State *L)
3251{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003252 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003253 size_t name_len;
3254 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003255
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003256 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003257 return 1;
3258}
3259
3260/* This function set the method. */
3261static int hlua_http_req_set_path(lua_State *L)
3262{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003263 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003264 size_t name_len;
3265 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003266 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003267 return 1;
3268}
3269
3270/* This function set the query-string. */
3271static int hlua_http_req_set_query(lua_State *L)
3272{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003273 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003274 size_t name_len;
3275 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003276
3277 /* Check length. */
3278 if (name_len > trash.size - 1) {
3279 lua_pushboolean(L, 0);
3280 return 1;
3281 }
3282
3283 /* Add the mark question as prefix. */
3284 chunk_reset(&trash);
3285 trash.str[trash.len++] = '?';
3286 memcpy(trash.str + trash.len, name, name_len);
3287 trash.len += name_len;
3288
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003289 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003290 return 1;
3291}
3292
3293/* This function set the uri. */
3294static int hlua_http_req_set_uri(lua_State *L)
3295{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003296 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003297 size_t name_len;
3298 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003299
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003300 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003301 return 1;
3302}
3303
3304/*
3305 *
3306 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003307 * Class TXN
3308 *
3309 *
3310 */
3311
3312/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003313 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003314 */
3315__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
3316{
3317 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
3318}
3319
Willy Tarreau59551662015-03-10 14:23:13 +01003320__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003321{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003322 struct hlua *hlua;
3323
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003324 MAY_LJMP(check_args(L, 2, "set_priv"));
3325
Willy Tarreau87b09662015-04-03 00:22:06 +02003326 /* It is useles to retrieve the stream, but this function
3327 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003328 */
3329 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003330 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003331
3332 /* Remove previous value. */
3333 if (hlua->Mref != -1)
3334 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3335
3336 /* Get and store new value. */
3337 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3338 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3339
3340 return 0;
3341}
3342
Willy Tarreau59551662015-03-10 14:23:13 +01003343__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003344{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003345 struct hlua *hlua;
3346
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003347 MAY_LJMP(check_args(L, 1, "get_priv"));
3348
Willy Tarreau87b09662015-04-03 00:22:06 +02003349 /* It is useles to retrieve the stream, but this function
3350 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003351 */
3352 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003353 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003354
3355 /* Push configuration index in the stack. */
3356 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3357
3358 return 1;
3359}
3360
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003361/* Create stack entry containing a class TXN. This function
3362 * return 0 if the stack does not contains free slots,
3363 * otherwise it returns 1.
3364 */
Willy Tarreau15e91e12015-04-04 00:52:09 +02003365static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003366{
Willy Tarreaude491382015-04-06 11:04:28 +02003367 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003368
3369 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003370 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003371 return 0;
3372
3373 /* NOTE: The allocation never fails. The failure
3374 * throw an error, and the function never returns.
3375 * if the throw is not avalaible, the process is aborted.
3376 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003377 /* Create the object: obj[0] = userdata. */
3378 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02003379 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003380 lua_rawseti(L, -2, 0);
3381
Willy Tarreaude491382015-04-06 11:04:28 +02003382 htxn->s = s;
3383 htxn->p = p;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003384
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003385 /* Create the "f" field that contains a list of fetches. */
3386 lua_pushstring(L, "f");
Willy Tarreaude491382015-04-06 11:04:28 +02003387 if (!hlua_fetches_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003388 return 0;
3389 lua_settable(L, -3);
3390
3391 /* Create the "sf" field that contains a list of stringsafe fetches. */
3392 lua_pushstring(L, "sf");
Willy Tarreaude491382015-04-06 11:04:28 +02003393 if (!hlua_fetches_new(L, htxn, 1))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003394 return 0;
3395 lua_settable(L, -3);
3396
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003397 /* Create the "c" field that contains a list of converters. */
3398 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02003399 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003400 return 0;
3401 lua_settable(L, -3);
3402
3403 /* Create the "sc" field that contains a list of stringsafe converters. */
3404 lua_pushstring(L, "sc");
Willy Tarreaude491382015-04-06 11:04:28 +02003405 if (!hlua_converters_new(L, htxn, 1))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003406 return 0;
3407 lua_settable(L, -3);
3408
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003409 /* Create the "req" field that contains the request channel object. */
3410 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003411 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003412 return 0;
3413 lua_settable(L, -3);
3414
3415 /* Create the "res" field that contains the response channel object. */
3416 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003417 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003418 return 0;
3419 lua_settable(L, -3);
3420
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003421 /* Creates the HTTP object is the current proxy allows http. */
3422 lua_pushstring(L, "http");
3423 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02003424 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003425 return 0;
3426 }
3427 else
3428 lua_pushnil(L);
3429 lua_settable(L, -3);
3430
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003431 /* Pop a class sesison metatable and affect it to the userdata. */
3432 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
3433 lua_setmetatable(L, -2);
3434
3435 return 1;
3436}
3437
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003438__LJMP static int hlua_txn_deflog(lua_State *L)
3439{
3440 const char *msg;
3441 struct hlua_txn *htxn;
3442
3443 MAY_LJMP(check_args(L, 2, "deflog"));
3444 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3445 msg = MAY_LJMP(luaL_checkstring(L, 2));
3446
3447 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
3448 return 0;
3449}
3450
3451__LJMP static int hlua_txn_log(lua_State *L)
3452{
3453 int level;
3454 const char *msg;
3455 struct hlua_txn *htxn;
3456
3457 MAY_LJMP(check_args(L, 3, "log"));
3458 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3459 level = MAY_LJMP(luaL_checkinteger(L, 2));
3460 msg = MAY_LJMP(luaL_checkstring(L, 3));
3461
3462 if (level < 0 || level >= NB_LOG_LEVELS)
3463 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3464
3465 hlua_sendlog(htxn->s->be, level, msg);
3466 return 0;
3467}
3468
3469__LJMP static int hlua_txn_log_debug(lua_State *L)
3470{
3471 const char *msg;
3472 struct hlua_txn *htxn;
3473
3474 MAY_LJMP(check_args(L, 2, "Debug"));
3475 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3476 msg = MAY_LJMP(luaL_checkstring(L, 2));
3477 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
3478 return 0;
3479}
3480
3481__LJMP static int hlua_txn_log_info(lua_State *L)
3482{
3483 const char *msg;
3484 struct hlua_txn *htxn;
3485
3486 MAY_LJMP(check_args(L, 2, "Info"));
3487 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3488 msg = MAY_LJMP(luaL_checkstring(L, 2));
3489 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
3490 return 0;
3491}
3492
3493__LJMP static int hlua_txn_log_warning(lua_State *L)
3494{
3495 const char *msg;
3496 struct hlua_txn *htxn;
3497
3498 MAY_LJMP(check_args(L, 2, "Warning"));
3499 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3500 msg = MAY_LJMP(luaL_checkstring(L, 2));
3501 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
3502 return 0;
3503}
3504
3505__LJMP static int hlua_txn_log_alert(lua_State *L)
3506{
3507 const char *msg;
3508 struct hlua_txn *htxn;
3509
3510 MAY_LJMP(check_args(L, 2, "Alert"));
3511 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3512 msg = MAY_LJMP(luaL_checkstring(L, 2));
3513 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
3514 return 0;
3515}
3516
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003517__LJMP static int hlua_txn_set_loglevel(lua_State *L)
3518{
3519 struct hlua_txn *htxn;
3520 int ll;
3521
3522 MAY_LJMP(check_args(L, 2, "set_loglevel"));
3523 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3524 ll = MAY_LJMP(luaL_checkinteger(L, 2));
3525
3526 if (ll < 0 || ll > 7)
3527 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
3528
3529 htxn->s->logs.level = ll;
3530 return 0;
3531}
3532
3533__LJMP static int hlua_txn_set_tos(lua_State *L)
3534{
3535 struct hlua_txn *htxn;
3536 struct connection *cli_conn;
3537 int tos;
3538
3539 MAY_LJMP(check_args(L, 2, "set_tos"));
3540 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3541 tos = MAY_LJMP(luaL_checkinteger(L, 2));
3542
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003543 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003544 inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, tos);
3545
3546 return 0;
3547}
3548
3549__LJMP static int hlua_txn_set_mark(lua_State *L)
3550{
3551#ifdef SO_MARK
3552 struct hlua_txn *htxn;
3553 struct connection *cli_conn;
3554 int mark;
3555
3556 MAY_LJMP(check_args(L, 2, "set_mark"));
3557 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3558 mark = MAY_LJMP(luaL_checkinteger(L, 2));
3559
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003560 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02003561 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003562#endif
3563 return 0;
3564}
3565
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003566/* This function is an Lua binding that send pending data
3567 * to the client, and close the stream interface.
3568 */
3569__LJMP static int hlua_txn_close(lua_State *L)
3570{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003571 struct hlua_txn *htxn;
Willy Tarreau81389672015-03-10 12:03:52 +01003572 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003573
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003574 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003575 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003576
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003577 ic = &htxn->s->req;
3578 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01003579
3580 channel_abort(ic);
3581 channel_auto_close(ic);
3582 channel_erase(ic);
3583 channel_auto_read(oc);
3584 channel_auto_close(oc);
3585 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003586
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003587 return 0;
3588}
3589
3590__LJMP static int hlua_log(lua_State *L)
3591{
3592 int level;
3593 const char *msg;
3594
3595 MAY_LJMP(check_args(L, 2, "log"));
3596 level = MAY_LJMP(luaL_checkinteger(L, 1));
3597 msg = MAY_LJMP(luaL_checkstring(L, 2));
3598
3599 if (level < 0 || level >= NB_LOG_LEVELS)
3600 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3601
3602 hlua_sendlog(NULL, level, msg);
3603 return 0;
3604}
3605
3606__LJMP static int hlua_log_debug(lua_State *L)
3607{
3608 const char *msg;
3609
3610 MAY_LJMP(check_args(L, 1, "debug"));
3611 msg = MAY_LJMP(luaL_checkstring(L, 1));
3612 hlua_sendlog(NULL, LOG_DEBUG, msg);
3613 return 0;
3614}
3615
3616__LJMP static int hlua_log_info(lua_State *L)
3617{
3618 const char *msg;
3619
3620 MAY_LJMP(check_args(L, 1, "info"));
3621 msg = MAY_LJMP(luaL_checkstring(L, 1));
3622 hlua_sendlog(NULL, LOG_INFO, msg);
3623 return 0;
3624}
3625
3626__LJMP static int hlua_log_warning(lua_State *L)
3627{
3628 const char *msg;
3629
3630 MAY_LJMP(check_args(L, 1, "warning"));
3631 msg = MAY_LJMP(luaL_checkstring(L, 1));
3632 hlua_sendlog(NULL, LOG_WARNING, msg);
3633 return 0;
3634}
3635
3636__LJMP static int hlua_log_alert(lua_State *L)
3637{
3638 const char *msg;
3639
3640 MAY_LJMP(check_args(L, 1, "alert"));
3641 msg = MAY_LJMP(luaL_checkstring(L, 1));
3642 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003643 return 0;
3644}
3645
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003646__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003647{
3648 int wakeup_ms = lua_tointeger(L, -1);
3649 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003650 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003651 return 0;
3652}
3653
3654__LJMP static int hlua_sleep(lua_State *L)
3655{
3656 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003657 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003658
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003659 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003660
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003661 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003662 wakeup_ms = tick_add(now_ms, delay);
3663 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003664
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003665 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3666 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003667}
3668
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003669__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003670{
3671 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003672 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003673
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003674 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003675
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003676 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003677 wakeup_ms = tick_add(now_ms, delay);
3678 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003679
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003680 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3681 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003682}
3683
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003684/* This functionis an LUA binding. it permits to give back
3685 * the hand at the HAProxy scheduler. It is used when the
3686 * LUA processing consumes a lot of time.
3687 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003688__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003689{
3690 return 0;
3691}
3692
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003693__LJMP static int hlua_yield(lua_State *L)
3694{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003695 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
3696 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003697}
3698
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003699/* This function change the nice of the currently executed
3700 * task. It is used set low or high priority at the current
3701 * task.
3702 */
Willy Tarreau59551662015-03-10 14:23:13 +01003703__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003704{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003705 struct hlua *hlua;
3706 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003707
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003708 MAY_LJMP(check_args(L, 1, "set_nice"));
3709 hlua = hlua_gethlua(L);
3710 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003711
3712 /* If he task is not set, I'm in a start mode. */
3713 if (!hlua || !hlua->task)
3714 return 0;
3715
3716 if (nice < -1024)
3717 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003718 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003719 nice = 1024;
3720
3721 hlua->task->nice = nice;
3722 return 0;
3723}
3724
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003725/* This function is used as a calback of a task. It is called by the
3726 * HAProxy task subsystem when the task is awaked. The LUA runtime can
3727 * return an E_AGAIN signal, the emmiter of this signal must set a
3728 * signal to wake the task.
3729 */
3730static struct task *hlua_process_task(struct task *task)
3731{
3732 struct hlua *hlua = task->context;
3733 enum hlua_exec status;
3734
3735 /* We need to remove the task from the wait queue before executing
3736 * the Lua code because we don't know if it needs to wait for
3737 * another timer or not in the case of E_AGAIN.
3738 */
3739 task_delete(task);
3740
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003741 /* If it is the first call to the task, we must initialize the
3742 * execution timeouts.
3743 */
3744 if (!HLUA_IS_RUNNING(hlua))
3745 hlua->expire = tick_add(now_ms, hlua_timeout_task);
3746
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003747 /* Execute the Lua code. */
3748 status = hlua_ctx_resume(hlua, 1);
3749
3750 switch (status) {
3751 /* finished or yield */
3752 case HLUA_E_OK:
3753 hlua_ctx_destroy(hlua);
3754 task_delete(task);
3755 task_free(task);
3756 break;
3757
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003758 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
3759 if (hlua->wake_time != TICK_ETERNITY)
3760 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003761 break;
3762
3763 /* finished with error. */
3764 case HLUA_E_ERRMSG:
3765 send_log(NULL, LOG_ERR, "Lua task: %s.", lua_tostring(hlua->T, -1));
3766 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3767 Alert("Lua task: %s.\n", lua_tostring(hlua->T, -1));
3768 hlua_ctx_destroy(hlua);
3769 task_delete(task);
3770 task_free(task);
3771 break;
3772
3773 case HLUA_E_ERR:
3774 default:
3775 send_log(NULL, LOG_ERR, "Lua task: unknown error.");
3776 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3777 Alert("Lua task: unknown error.\n");
3778 hlua_ctx_destroy(hlua);
3779 task_delete(task);
3780 task_free(task);
3781 break;
3782 }
3783 return NULL;
3784}
3785
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003786/* This function is an LUA binding that register LUA function to be
3787 * executed after the HAProxy configuration parsing and before the
3788 * HAProxy scheduler starts. This function expect only one LUA
3789 * argument that is a function. This function returns nothing, but
3790 * throws if an error is encountered.
3791 */
3792__LJMP static int hlua_register_init(lua_State *L)
3793{
3794 struct hlua_init_function *init;
3795 int ref;
3796
3797 MAY_LJMP(check_args(L, 1, "register_init"));
3798
3799 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3800
3801 init = malloc(sizeof(*init));
3802 if (!init)
3803 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3804
3805 init->function_ref = ref;
3806 LIST_ADDQ(&hlua_init_functions, &init->l);
3807 return 0;
3808}
3809
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003810/* This functio is an LUA binding. It permits to register a task
3811 * executed in parallel of the main HAroxy activity. The task is
3812 * created and it is set in the HAProxy scheduler. It can be called
3813 * from the "init" section, "post init" or during the runtime.
3814 *
3815 * Lua prototype:
3816 *
3817 * <none> core.register_task(<function>)
3818 */
3819static int hlua_register_task(lua_State *L)
3820{
3821 struct hlua *hlua;
3822 struct task *task;
3823 int ref;
3824
3825 MAY_LJMP(check_args(L, 1, "register_task"));
3826
3827 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3828
3829 hlua = malloc(sizeof(*hlua));
3830 if (!hlua)
3831 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3832
3833 task = task_new();
3834 task->context = hlua;
3835 task->process = hlua_process_task;
3836
3837 if (!hlua_ctx_init(hlua, task))
3838 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3839
3840 /* Restore the function in the stack. */
3841 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
3842 hlua->nargs = 0;
3843
3844 /* Schedule task. */
3845 task_schedule(task, now_ms);
3846
3847 return 0;
3848}
3849
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003850/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
3851 * doesn't allow "yield" functions because the HAProxy engine cannot
3852 * resume converters.
3853 */
Willy Tarreau87b09662015-04-03 00:22:06 +02003854static int hlua_sample_conv_wrapper(struct stream *stream, const struct arg *arg_p,
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003855 struct sample *smp, void *private)
3856{
3857 struct hlua_function *fcn = (struct hlua_function *)private;
3858
Willy Tarreau87b09662015-04-03 00:22:06 +02003859 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003860 * Lua context can be not initialized. This behavior
3861 * permits to save performances because a systematic
3862 * Lua initialization cause 5% performances loss.
3863 */
Willy Tarreau87b09662015-04-03 00:22:06 +02003864 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
3865 send_log(stream->be, LOG_ERR, "Lua converter '%s': can't initialize Lua context.", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003866 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3867 Alert("Lua converter '%s': can't initialize Lua context.\n", fcn->name);
3868 return 0;
3869 }
3870
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003871 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003872 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003873 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003874 if (!lua_checkstack(stream->hlua.T, 1)) {
3875 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003876 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3877 Alert("Lua converter '%s': full stack.\n", fcn->name);
3878 return 0;
3879 }
3880
3881 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003882 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003883
3884 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003885 if (!lua_checkstack(stream->hlua.T, 1)) {
3886 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003887 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3888 Alert("Lua converter '%s': full stack.\n", fcn->name);
3889 return 0;
3890 }
Willy Tarreau87b09662015-04-03 00:22:06 +02003891 hlua_smp2lua(stream->hlua.T, smp);
3892 stream->hlua.nargs = 2;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003893
3894 /* push keywords in the stack. */
3895 if (arg_p) {
3896 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02003897 if (!lua_checkstack(stream->hlua.T, 1)) {
3898 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003899 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3900 Alert("Lua converter '%s': full stack.\n", fcn->name);
3901 return 0;
3902 }
Willy Tarreau87b09662015-04-03 00:22:06 +02003903 hlua_arg2lua(stream->hlua.T, arg_p);
3904 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003905 }
3906 }
3907
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003908 /* We must initialize the execution timeouts. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003909 stream->hlua.expire = tick_add(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003910
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003911 /* Set the currently running flag. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003912 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003913 }
3914
3915 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003916 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003917 /* finished. */
3918 case HLUA_E_OK:
3919 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003920 hlua_lua2smp(stream->hlua.T, -1, smp);
3921 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003922 return 1;
3923
3924 /* yield. */
3925 case HLUA_E_AGAIN:
Willy Tarreau87b09662015-04-03 00:22:06 +02003926 send_log(stream->be, LOG_ERR, "Lua converter '%s': cannot use yielded functions.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003927 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3928 Alert("Lua converter '%s': cannot use yielded functions.\n", fcn->name);
3929 return 0;
3930
3931 /* finished with error. */
3932 case HLUA_E_ERRMSG:
3933 /* Display log. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003934 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 +01003935 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Willy Tarreau87b09662015-04-03 00:22:06 +02003936 Alert("Lua converter '%s': %s.\n", fcn->name, lua_tostring(stream->hlua.T, -1));
3937 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003938 return 0;
3939
3940 case HLUA_E_ERR:
3941 /* Display log. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003942 send_log(stream->be, LOG_ERR, "Lua converter '%s' returns an unknown error.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003943 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3944 Alert("Lua converter '%s' returns an unknown error.\n", fcn->name);
3945
3946 default:
3947 return 0;
3948 }
3949}
3950
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003951/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
3952 * doesn't allow "yield" functions because the HAProxy engine cannot
3953 * resume sample-fetches.
3954 */
Willy Tarreau192252e2015-04-04 01:47:55 +02003955static int hlua_sample_fetch_wrapper(struct proxy *px, struct session *sess,
3956 struct stream *s, unsigned int opt,
3957 const struct arg *arg_p,
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003958 struct sample *smp, const char *kw, void *private)
3959{
3960 struct hlua_function *fcn = (struct hlua_function *)private;
3961
Willy Tarreau87b09662015-04-03 00:22:06 +02003962 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003963 * Lua context can be not initialized. This behavior
3964 * permits to save performances because a systematic
3965 * Lua initialization cause 5% performances loss.
3966 */
3967 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
3968 send_log(s->be, LOG_ERR, "Lua sample-fetch '%s': can't initialize Lua context.", fcn->name);
3969 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3970 Alert("Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
3971 return 0;
3972 }
3973
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003974 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003975 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003976 /* Check stack available size. */
3977 if (!lua_checkstack(s->hlua.T, 2)) {
3978 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3979 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3980 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3981 return 0;
3982 }
3983
3984 /* Restore the function in the stack. */
3985 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
3986
3987 /* push arguments in the stack. */
Willy Tarreau15e91e12015-04-04 00:52:09 +02003988 if (!hlua_txn_new(s->hlua.T, s, px)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003989 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3990 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3991 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3992 return 0;
3993 }
3994 s->hlua.nargs = 1;
3995
3996 /* push keywords in the stack. */
3997 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
3998 /* Check stack available size. */
3999 if (!lua_checkstack(s->hlua.T, 1)) {
4000 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
4001 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4002 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4003 return 0;
4004 }
4005 if (!lua_checkstack(s->hlua.T, 1)) {
4006 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
4007 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4008 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4009 return 0;
4010 }
4011 hlua_arg2lua(s->hlua.T, arg_p);
4012 s->hlua.nargs++;
4013 }
4014
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004015 /* We must initialize the execution timeouts. */
4016 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
4017
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004018 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004019 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004020 }
4021
4022 /* Execute the function. */
4023 switch (hlua_ctx_resume(&s->hlua, 0)) {
4024 /* finished. */
4025 case HLUA_E_OK:
4026 /* Convert the returned value in sample. */
4027 hlua_lua2smp(s->hlua.T, -1, smp);
4028 lua_pop(s->hlua.T, 1);
4029
4030 /* Set the end of execution flag. */
4031 smp->flags &= ~SMP_F_MAY_CHANGE;
4032 return 1;
4033
4034 /* yield. */
4035 case HLUA_E_AGAIN:
4036 send_log(px, LOG_ERR, "Lua sample-fetch '%s': cannot use yielded functions.", fcn->name);
4037 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4038 Alert("Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
4039 return 0;
4040
4041 /* finished with error. */
4042 case HLUA_E_ERRMSG:
4043 /* Display log. */
4044 send_log(px, LOG_ERR, "Lua sample-fetch '%s': %s.", fcn->name, lua_tostring(s->hlua.T, -1));
4045 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4046 Alert("Lua sample-fetch '%s': %s.\n", fcn->name, lua_tostring(s->hlua.T, -1));
4047 lua_pop(s->hlua.T, 1);
4048 return 0;
4049
4050 case HLUA_E_ERR:
4051 /* Display log. */
4052 send_log(px, LOG_ERR, "Lua sample-fetch '%s' returns an unknown error.", fcn->name);
4053 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4054 Alert("Lua sample-fetch '%s': returns an unknown error.\n", fcn->name);
4055
4056 default:
4057 return 0;
4058 }
4059}
4060
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004061/* This function is an LUA binding used for registering
4062 * "sample-conv" functions. It expects a converter name used
4063 * in the haproxy configuration file, and an LUA function.
4064 */
4065__LJMP static int hlua_register_converters(lua_State *L)
4066{
4067 struct sample_conv_kw_list *sck;
4068 const char *name;
4069 int ref;
4070 int len;
4071 struct hlua_function *fcn;
4072
4073 MAY_LJMP(check_args(L, 2, "register_converters"));
4074
4075 /* First argument : converter name. */
4076 name = MAY_LJMP(luaL_checkstring(L, 1));
4077
4078 /* Second argument : lua function. */
4079 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4080
4081 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004082 sck = malloc(sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004083 if (!sck)
4084 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4085 fcn = malloc(sizeof(*fcn));
4086 if (!fcn)
4087 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4088
4089 /* Fill fcn. */
4090 fcn->name = strdup(name);
4091 if (!fcn->name)
4092 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4093 fcn->function_ref = ref;
4094
4095 /* List head */
4096 sck->list.n = sck->list.p = NULL;
4097
4098 /* converter keyword. */
4099 len = strlen("lua.") + strlen(name) + 1;
4100 sck->kw[0].kw = malloc(len);
4101 if (!sck->kw[0].kw)
4102 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4103
4104 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
4105 sck->kw[0].process = hlua_sample_conv_wrapper;
4106 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4107 sck->kw[0].val_args = NULL;
4108 sck->kw[0].in_type = SMP_T_STR;
4109 sck->kw[0].out_type = SMP_T_STR;
4110 sck->kw[0].private = fcn;
4111
4112 /* End of array. */
4113 memset(&sck->kw[1], 0, sizeof(struct sample_conv));
4114
4115 /* Register this new converter */
4116 sample_register_convs(sck);
4117
4118 return 0;
4119}
4120
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004121/* This fucntion is an LUA binding used for registering
4122 * "sample-fetch" functions. It expects a converter name used
4123 * in the haproxy configuration file, and an LUA function.
4124 */
4125__LJMP static int hlua_register_fetches(lua_State *L)
4126{
4127 const char *name;
4128 int ref;
4129 int len;
4130 struct sample_fetch_kw_list *sfk;
4131 struct hlua_function *fcn;
4132
4133 MAY_LJMP(check_args(L, 2, "register_fetches"));
4134
4135 /* First argument : sample-fetch name. */
4136 name = MAY_LJMP(luaL_checkstring(L, 1));
4137
4138 /* Second argument : lua function. */
4139 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4140
4141 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004142 sfk = malloc(sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004143 if (!sfk)
4144 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4145 fcn = malloc(sizeof(*fcn));
4146 if (!fcn)
4147 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4148
4149 /* Fill fcn. */
4150 fcn->name = strdup(name);
4151 if (!fcn->name)
4152 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4153 fcn->function_ref = ref;
4154
4155 /* List head */
4156 sfk->list.n = sfk->list.p = NULL;
4157
4158 /* sample-fetch keyword. */
4159 len = strlen("lua.") + strlen(name) + 1;
4160 sfk->kw[0].kw = malloc(len);
4161 if (!sfk->kw[0].kw)
4162 return luaL_error(L, "lua out of memory error.");
4163
4164 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
4165 sfk->kw[0].process = hlua_sample_fetch_wrapper;
4166 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4167 sfk->kw[0].val_args = NULL;
4168 sfk->kw[0].out_type = SMP_T_STR;
4169 sfk->kw[0].use = SMP_USE_HTTP_ANY;
4170 sfk->kw[0].val = 0;
4171 sfk->kw[0].private = fcn;
4172
4173 /* End of array. */
4174 memset(&sfk->kw[1], 0, sizeof(struct sample_fetch));
4175
4176 /* Register this new fetch. */
4177 sample_register_fetches(sfk);
4178
4179 return 0;
4180}
4181
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004182/* global {tcp|http}-request parser. Return 1 in succes case, else return 0. */
4183static int hlua_parse_rule(const char **args, int *cur_arg, struct proxy *px,
4184 struct hlua_rule **rule_p, char **err)
4185{
4186 struct hlua_rule *rule;
4187
4188 /* Memory for the rule. */
4189 rule = malloc(sizeof(*rule));
4190 if (!rule) {
4191 memprintf(err, "out of memory error");
4192 return 0;
4193 }
4194 *rule_p = rule;
4195
4196 /* The requiered arg is a function name. */
4197 if (!args[*cur_arg]) {
4198 memprintf(err, "expect Lua function name");
4199 return 0;
4200 }
4201
4202 /* Lookup for the symbol, and check if it is a function. */
4203 lua_getglobal(gL.T, args[*cur_arg]);
4204 if (lua_isnil(gL.T, -1)) {
4205 lua_pop(gL.T, 1);
4206 memprintf(err, "Lua function '%s' not found", args[*cur_arg]);
4207 return 0;
4208 }
4209 if (!lua_isfunction(gL.T, -1)) {
4210 lua_pop(gL.T, 1);
4211 memprintf(err, "'%s' is not a function", args[*cur_arg]);
4212 return 0;
4213 }
4214
4215 /* Reference the Lua function and store the reference. */
4216 rule->fcn.function_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
4217 rule->fcn.name = strdup(args[*cur_arg]);
4218 if (!rule->fcn.name) {
4219 memprintf(err, "out of memory error.");
4220 return 0;
4221 }
4222 (*cur_arg)++;
4223
4224 /* TODO: later accept arguments. */
4225 rule->args = NULL;
4226
4227 return 1;
4228}
4229
4230/* This function is a wrapper to execute each LUA function declared
4231 * as an action wrapper during the initialisation period. This function
4232 * return 1 if the processing is finished (with oe without error) and
4233 * return 0 if the function must be called again because the LUA
4234 * returns a yield.
4235 */
4236static int hlua_request_act_wrapper(struct hlua_rule *rule, struct proxy *px,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004237 struct stream *s, unsigned int analyzer)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004238{
4239 char **arg;
4240
Willy Tarreau87b09662015-04-03 00:22:06 +02004241 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004242 * Lua context can be not initialized. This behavior
4243 * permits to save performances because a systematic
4244 * Lua initialization cause 5% performances loss.
4245 */
4246 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
4247 send_log(px, LOG_ERR, "Lua action '%s': can't initialize Lua context.", rule->fcn.name);
4248 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4249 Alert("Lua action '%s': can't initialize Lua context.\n", rule->fcn.name);
4250 return 0;
4251 }
4252
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004253 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004254 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004255 /* Check stack available size. */
4256 if (!lua_checkstack(s->hlua.T, 1)) {
4257 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
4258 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4259 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
4260 return 0;
4261 }
4262
4263 /* Restore the function in the stack. */
4264 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->fcn.function_ref);
4265
Willy Tarreau87b09662015-04-03 00:22:06 +02004266 /* Create and and push object stream in the stack. */
Willy Tarreau15e91e12015-04-04 00:52:09 +02004267 if (!hlua_txn_new(s->hlua.T, s, px)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004268 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
4269 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4270 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
4271 return 0;
4272 }
4273 s->hlua.nargs = 1;
4274
4275 /* push keywords in the stack. */
4276 for (arg = rule->args; arg && *arg; arg++) {
4277 if (!lua_checkstack(s->hlua.T, 1)) {
4278 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
4279 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4280 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
4281 return 0;
4282 }
4283 lua_pushstring(s->hlua.T, *arg);
4284 s->hlua.nargs++;
4285 }
4286
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004287 /* We must initialize the execution timeouts. */
4288 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
4289
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004290 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004291 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004292 }
4293
4294 /* Execute the function. */
4295 switch (hlua_ctx_resume(&s->hlua, 1)) {
4296 /* finished. */
4297 case HLUA_E_OK:
4298 return 1;
4299
4300 /* yield. */
4301 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004302 /* Set timeout in the required channel. */
4303 if (s->hlua.wake_time != TICK_ETERNITY) {
4304 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004305 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004306 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004307 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004308 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004309 /* Some actions can be wake up when a "write" event
4310 * is detected on a response channel. This is useful
4311 * only for actions targetted on the requests.
4312 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004313 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004314 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01004315 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004316 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004317 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004318 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004319 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004320 return 0;
4321
4322 /* finished with error. */
4323 case HLUA_E_ERRMSG:
4324 /* Display log. */
4325 send_log(px, LOG_ERR, "Lua function '%s': %s.", rule->fcn.name, lua_tostring(s->hlua.T, -1));
4326 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4327 Alert("Lua function '%s': %s.\n", rule->fcn.name, lua_tostring(s->hlua.T, -1));
4328 lua_pop(s->hlua.T, 1);
4329 return 1;
4330
4331 case HLUA_E_ERR:
4332 /* Display log. */
4333 send_log(px, LOG_ERR, "Lua function '%s' return an unknown error.", rule->fcn.name);
4334 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4335 Alert("Lua function '%s' return an unknown error.\n", rule->fcn.name);
4336
4337 default:
4338 return 1;
4339 }
4340}
4341
4342/* Lua execution wrapper for "tcp-request". This function uses
4343 * "hlua_request_act_wrapper" for executing the LUA code.
4344 */
4345int hlua_tcp_req_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
Willy Tarreau87b09662015-04-03 00:22:06 +02004346 struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004347{
4348 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004349 px, s, AN_REQ_INSPECT_FE);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004350}
4351
4352/* Lua execution wrapper for "tcp-response". This function uses
4353 * "hlua_request_act_wrapper" for executing the LUA code.
4354 */
4355int hlua_tcp_res_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
Willy Tarreau87b09662015-04-03 00:22:06 +02004356 struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004357{
4358 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004359 px, s, AN_RES_INSPECT);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004360}
4361
4362/* Lua execution wrapper for http-request.
4363 * This function uses "hlua_request_act_wrapper" for executing
4364 * the LUA code.
4365 */
4366int hlua_http_req_act_wrapper(struct http_req_rule *rule, struct proxy *px,
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004367 struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004368{
4369 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004370 s, AN_REQ_HTTP_PROCESS_FE);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004371}
4372
4373/* Lua execution wrapper for http-response.
4374 * This function uses "hlua_request_act_wrapper" for executing
4375 * the LUA code.
4376 */
4377int hlua_http_res_act_wrapper(struct http_res_rule *rule, struct proxy *px,
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004378 struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004379{
4380 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004381 s, AN_RES_HTTP_PROCESS_BE);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004382}
4383
4384/* tcp-request <*> configuration wrapper. */
4385static int tcp_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4386 struct tcp_rule *rule, char **err)
4387{
4388 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004389 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004390 rule->action = TCP_ACT_CUSTOM;
4391 rule->action_ptr = hlua_tcp_req_act_wrapper;
4392 return 1;
4393}
4394
4395/* tcp-response <*> configuration wrapper. */
4396static int tcp_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4397 struct tcp_rule *rule, char **err)
4398{
4399 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004400 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004401 rule->action = TCP_ACT_CUSTOM;
4402 rule->action_ptr = hlua_tcp_res_act_wrapper;
4403 return 1;
4404}
4405
4406/* http-request <*> configuration wrapper. */
4407static int http_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4408 struct http_req_rule *rule, char **err)
4409{
4410 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
4411 return -1;
4412 rule->action = HTTP_REQ_ACT_CUSTOM_CONT;
4413 rule->action_ptr = hlua_http_req_act_wrapper;
4414 return 1;
4415}
4416
4417/* http-response <*> configuration wrapper. */
4418static int http_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4419 struct http_res_rule *rule, char **err)
4420{
4421 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
4422 return -1;
4423 rule->action = HTTP_RES_ACT_CUSTOM_CONT;
4424 rule->action_ptr = hlua_http_res_act_wrapper;
4425 return 1;
4426}
4427
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004428static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
4429 struct proxy *defpx, const char *file, int line,
4430 char **err, unsigned int *timeout)
4431{
4432 const char *error;
4433
4434 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
4435 if (error && *error != '\0') {
4436 memprintf(err, "%s: invalid timeout", args[0]);
4437 return -1;
4438 }
4439 return 0;
4440}
4441
4442static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
4443 struct proxy *defpx, const char *file, int line,
4444 char **err)
4445{
4446 return hlua_read_timeout(args, section_type, curpx, defpx,
4447 file, line, err, &hlua_timeout_session);
4448}
4449
4450static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
4451 struct proxy *defpx, const char *file, int line,
4452 char **err)
4453{
4454 return hlua_read_timeout(args, section_type, curpx, defpx,
4455 file, line, err, &hlua_timeout_task);
4456}
4457
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004458static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
4459 struct proxy *defpx, const char *file, int line,
4460 char **err)
4461{
4462 char *error;
4463
4464 hlua_nb_instruction = strtoll(args[1], &error, 10);
4465 if (*error != '\0') {
4466 memprintf(err, "%s: invalid number", args[0]);
4467 return -1;
4468 }
4469 return 0;
4470}
4471
Willy Tarreau32f61e22015-03-18 17:54:59 +01004472static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
4473 struct proxy *defpx, const char *file, int line,
4474 char **err)
4475{
4476 char *error;
4477
4478 if (*(args[1]) == 0) {
4479 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
4480 return -1;
4481 }
4482 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
4483 if (*error != '\0') {
4484 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
4485 return -1;
4486 }
4487 return 0;
4488}
4489
4490
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004491/* This function is called by the main configuration key "lua-load". It loads and
4492 * execute an lua file during the parsing of the HAProxy configuration file. It is
4493 * the main lua entry point.
4494 *
4495 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
4496 * occured, otherwise it returns 0.
4497 *
4498 * In some error case, LUA set an error message in top of the stack. This function
4499 * returns this error message in the HAProxy logs and pop it from the stack.
4500 */
4501static int hlua_load(char **args, int section_type, struct proxy *curpx,
4502 struct proxy *defpx, const char *file, int line,
4503 char **err)
4504{
4505 int error;
4506
4507 /* Just load and compile the file. */
4508 error = luaL_loadfile(gL.T, args[1]);
4509 if (error) {
4510 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
4511 lua_pop(gL.T, 1);
4512 return -1;
4513 }
4514
4515 /* If no syntax error where detected, execute the code. */
4516 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
4517 switch (error) {
4518 case LUA_OK:
4519 break;
4520 case LUA_ERRRUN:
4521 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
4522 lua_pop(gL.T, 1);
4523 return -1;
4524 case LUA_ERRMEM:
4525 memprintf(err, "lua out of memory error\n");
4526 return -1;
4527 case LUA_ERRERR:
4528 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
4529 lua_pop(gL.T, 1);
4530 return -1;
4531 case LUA_ERRGCMM:
4532 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
4533 lua_pop(gL.T, 1);
4534 return -1;
4535 default:
4536 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
4537 lua_pop(gL.T, 1);
4538 return -1;
4539 }
4540
4541 return 0;
4542}
4543
4544/* configuration keywords declaration */
4545static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004546 { CFG_GLOBAL, "lua-load", hlua_load },
4547 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
4548 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004549 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01004550 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004551 { 0, NULL, NULL },
4552}};
4553
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004554static struct http_req_action_kw_list http_req_kws = {"lua", { }, {
4555 { "lua", http_req_action_register_lua },
4556 { NULL, NULL }
4557}};
4558
4559static struct http_res_action_kw_list http_res_kws = {"lua", { }, {
4560 { "lua", http_res_action_register_lua },
4561 { NULL, NULL }
4562}};
4563
4564static struct tcp_action_kw_list tcp_req_cont_kws = {"lua", { }, {
4565 { "lua", tcp_req_action_register_lua },
4566 { NULL, NULL }
4567}};
4568
4569static struct tcp_action_kw_list tcp_res_cont_kws = {"lua", { }, {
4570 { "lua", tcp_res_action_register_lua },
4571 { NULL, NULL }
4572}};
4573
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004574int hlua_post_init()
4575{
4576 struct hlua_init_function *init;
4577 const char *msg;
4578 enum hlua_exec ret;
4579
4580 list_for_each_entry(init, &hlua_init_functions, l) {
4581 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
4582 ret = hlua_ctx_resume(&gL, 0);
4583 switch (ret) {
4584 case HLUA_E_OK:
4585 lua_pop(gL.T, -1);
4586 return 1;
4587 case HLUA_E_AGAIN:
4588 Alert("lua init: yield not allowed.\n");
4589 return 0;
4590 case HLUA_E_ERRMSG:
4591 msg = lua_tostring(gL.T, -1);
4592 Alert("lua init: %s.\n", msg);
4593 return 0;
4594 case HLUA_E_ERR:
4595 default:
4596 Alert("lua init: unknown runtime error.\n");
4597 return 0;
4598 }
4599 }
4600 return 1;
4601}
4602
Willy Tarreau32f61e22015-03-18 17:54:59 +01004603/* The memory allocator used by the Lua stack. <ud> is a pointer to the
4604 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
4605 * is the previously allocated size or the kind of object in case of a new
4606 * allocation. <nsize> is the requested new size.
4607 */
4608static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
4609{
4610 struct hlua_mem_allocator *zone = ud;
4611
4612 if (nsize == 0) {
4613 /* it's a free */
4614 if (ptr)
4615 zone->allocated -= osize;
4616 free(ptr);
4617 return NULL;
4618 }
4619
4620 if (!ptr) {
4621 /* it's a new allocation */
4622 if (zone->limit && zone->allocated + nsize > zone->limit)
4623 return NULL;
4624
4625 ptr = malloc(nsize);
4626 if (ptr)
4627 zone->allocated += nsize;
4628 return ptr;
4629 }
4630
4631 /* it's a realloc */
4632 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
4633 return NULL;
4634
4635 ptr = realloc(ptr, nsize);
4636 if (ptr)
4637 zone->allocated += nsize - osize;
4638 return ptr;
4639}
4640
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01004641void hlua_init(void)
4642{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004643 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004644 int idx;
4645 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004646 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004647 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004648#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004649 struct srv_kw *kw;
4650 int tmp_error;
4651 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01004652 char *args[] = { /* SSL client configuration. */
4653 "ssl",
4654 "verify",
4655 "none",
4656 "force-sslv3",
4657 NULL
4658 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004659#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004660
Willy Tarreau87b09662015-04-03 00:22:06 +02004661 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004662 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
4663
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004664 /* Register configuration keywords. */
4665 cfg_register_keywords(&cfg_kws);
4666
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004667 /* Register custom HTTP rules. */
4668 http_req_keywords_register(&http_req_kws);
4669 http_res_keywords_register(&http_res_kws);
4670 tcp_req_cont_keywords_register(&tcp_req_cont_kws);
4671 tcp_res_cont_keywords_register(&tcp_res_cont_kws);
4672
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004673 /* Init main lua stack. */
4674 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004675 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004676 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004677 gL.T = luaL_newstate();
4678 hlua_sethlua(&gL);
4679 gL.Tref = LUA_REFNIL;
4680 gL.task = NULL;
4681
Willy Tarreau32f61e22015-03-18 17:54:59 +01004682 /* change the memory allocators to track memory usage */
4683 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
4684
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004685 /* Initialise lua. */
4686 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004687
4688 /*
4689 *
4690 * Create "core" object.
4691 *
4692 */
4693
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01004694 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004695 lua_newtable(gL.T);
4696
4697 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004698 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004699 hlua_class_const_int(gL.T, log_levels[i], i);
4700
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004701 /* Register special functions. */
4702 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004703 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004704 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004705 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004706 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01004707 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004708 hlua_class_function(gL.T, "sleep", hlua_sleep);
4709 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01004710 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
4711 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
4712 hlua_class_function(gL.T, "set_map", hlua_set_map);
4713 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004714 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004715 hlua_class_function(gL.T, "log", hlua_log);
4716 hlua_class_function(gL.T, "Debug", hlua_log_debug);
4717 hlua_class_function(gL.T, "Info", hlua_log_info);
4718 hlua_class_function(gL.T, "Warning", hlua_log_warning);
4719 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004720
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004721 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004722
4723 /*
4724 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02004725 * Register class Map
4726 *
4727 */
4728
4729 /* This table entry is the object "Map" base. */
4730 lua_newtable(gL.T);
4731
4732 /* register pattern types. */
4733 for (i=0; i<PAT_MATCH_NUM; i++)
4734 hlua_class_const_int(gL.T, pat_match_names[i], i);
4735
4736 /* register constructor. */
4737 hlua_class_function(gL.T, "new", hlua_map_new);
4738
4739 /* Create and fill the metatable. */
4740 lua_newtable(gL.T);
4741
4742 /* Create and fille the __index entry. */
4743 lua_pushstring(gL.T, "__index");
4744 lua_newtable(gL.T);
4745
4746 /* Register . */
4747 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
4748 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
4749
4750 lua_settable(gL.T, -3);
4751
4752 /* Register previous table in the registry with reference and named entry. */
4753 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4754 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4755 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_MAP); /* register class session. */
4756 class_map_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4757
4758 /* Assign the metatable to the mai Map object. */
4759 lua_setmetatable(gL.T, -2);
4760
4761 /* Set a name to the table. */
4762 lua_setglobal(gL.T, "Map");
4763
4764 /*
4765 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004766 * Register class Channel
4767 *
4768 */
4769
4770 /* Create and fill the metatable. */
4771 lua_newtable(gL.T);
4772
4773 /* Create and fille the __index entry. */
4774 lua_pushstring(gL.T, "__index");
4775 lua_newtable(gL.T);
4776
4777 /* Register . */
4778 hlua_class_function(gL.T, "get", hlua_channel_get);
4779 hlua_class_function(gL.T, "dup", hlua_channel_dup);
4780 hlua_class_function(gL.T, "getline", hlua_channel_getline);
4781 hlua_class_function(gL.T, "set", hlua_channel_set);
4782 hlua_class_function(gL.T, "append", hlua_channel_append);
4783 hlua_class_function(gL.T, "send", hlua_channel_send);
4784 hlua_class_function(gL.T, "forward", hlua_channel_forward);
4785 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
4786 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
4787
4788 lua_settable(gL.T, -3);
4789
4790 /* Register previous table in the registry with reference and named entry. */
4791 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4792 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
4793 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4794
4795 /*
4796 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004797 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004798 *
4799 */
4800
4801 /* Create and fill the metatable. */
4802 lua_newtable(gL.T);
4803
4804 /* Create and fille the __index entry. */
4805 lua_pushstring(gL.T, "__index");
4806 lua_newtable(gL.T);
4807
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004808 /* Browse existing fetches and create the associated
4809 * object method.
4810 */
4811 sf = NULL;
4812 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
4813
4814 /* Dont register the keywork if the arguments check function are
4815 * not safe during the runtime.
4816 */
4817 if ((sf->val_args != NULL) &&
4818 (sf->val_args != val_payload_lv) &&
4819 (sf->val_args != val_hdr))
4820 continue;
4821
4822 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4823 * by an underscore.
4824 */
4825 strncpy(trash.str, sf->kw, trash.size);
4826 trash.str[trash.size - 1] = '\0';
4827 for (p = trash.str; *p; p++)
4828 if (*p == '.' || *p == '-' || *p == '+')
4829 *p = '_';
4830
4831 /* Register the function. */
4832 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01004833 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004834 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
4835 lua_settable(gL.T, -3);
4836 }
4837
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004838 lua_settable(gL.T, -3);
4839
4840 /* Register previous table in the registry with reference and named entry. */
4841 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4842 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
4843 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4844
4845 /*
4846 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004847 * Register class Converters
4848 *
4849 */
4850
4851 /* Create and fill the metatable. */
4852 lua_newtable(gL.T);
4853
4854 /* Create and fill the __index entry. */
4855 lua_pushstring(gL.T, "__index");
4856 lua_newtable(gL.T);
4857
4858 /* Browse existing converters and create the associated
4859 * object method.
4860 */
4861 sc = NULL;
4862 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
4863 /* Dont register the keywork if the arguments check function are
4864 * not safe during the runtime.
4865 */
4866 if (sc->val_args != NULL)
4867 continue;
4868
4869 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4870 * by an underscore.
4871 */
4872 strncpy(trash.str, sc->kw, trash.size);
4873 trash.str[trash.size - 1] = '\0';
4874 for (p = trash.str; *p; p++)
4875 if (*p == '.' || *p == '-' || *p == '+')
4876 *p = '_';
4877
4878 /* Register the function. */
4879 lua_pushstring(gL.T, trash.str);
4880 lua_pushlightuserdata(gL.T, sc);
4881 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
4882 lua_settable(gL.T, -3);
4883 }
4884
4885 lua_settable(gL.T, -3);
4886
4887 /* Register previous table in the registry with reference and named entry. */
4888 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4889 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
4890 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4891
4892 /*
4893 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004894 * Register class HTTP
4895 *
4896 */
4897
4898 /* Create and fill the metatable. */
4899 lua_newtable(gL.T);
4900
4901 /* Create and fille the __index entry. */
4902 lua_pushstring(gL.T, "__index");
4903 lua_newtable(gL.T);
4904
4905 /* Register Lua functions. */
4906 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
4907 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
4908 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
4909 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
4910 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
4911 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
4912 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
4913 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
4914 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
4915 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
4916
4917 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
4918 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
4919 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
4920 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
4921 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
4922 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
4923
4924 lua_settable(gL.T, -3);
4925
4926 /* Register previous table in the registry with reference and named entry. */
4927 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4928 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_HTTP); /* register class session. */
4929 class_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4930
4931 /*
4932 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004933 * Register class TXN
4934 *
4935 */
4936
4937 /* Create and fill the metatable. */
4938 lua_newtable(gL.T);
4939
4940 /* Create and fille the __index entry. */
4941 lua_pushstring(gL.T, "__index");
4942 lua_newtable(gL.T);
4943
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004944 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01004945 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
4946 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004947 hlua_class_function(gL.T, "close", hlua_txn_close);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004948 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
4949 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
4950 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004951 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
4952 hlua_class_function(gL.T, "log", hlua_txn_log);
4953 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
4954 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
4955 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
4956 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004957
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004958 lua_settable(gL.T, -3);
4959
4960 /* Register previous table in the registry with reference and named entry. */
4961 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4962 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
4963 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004964
4965 /*
4966 *
4967 * Register class Socket
4968 *
4969 */
4970
4971 /* Create and fill the metatable. */
4972 lua_newtable(gL.T);
4973
4974 /* Create and fille the __index entry. */
4975 lua_pushstring(gL.T, "__index");
4976 lua_newtable(gL.T);
4977
Baptiste Assmann84bb4932015-03-02 21:40:06 +01004978#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004979 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01004980#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004981 hlua_class_function(gL.T, "connect", hlua_socket_connect);
4982 hlua_class_function(gL.T, "send", hlua_socket_send);
4983 hlua_class_function(gL.T, "receive", hlua_socket_receive);
4984 hlua_class_function(gL.T, "close", hlua_socket_close);
4985 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
4986 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
4987 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
4988 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
4989
4990 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
4991
4992 /* Register the garbage collector entry. */
4993 lua_pushstring(gL.T, "__gc");
4994 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
4995 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
4996
4997 /* Register previous table in the registry with reference and named entry. */
4998 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4999 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5000 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
5001 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
5002
5003 /* Proxy and server configuration initialisation. */
5004 memset(&socket_proxy, 0, sizeof(socket_proxy));
5005 init_new_proxy(&socket_proxy);
5006 socket_proxy.parent = NULL;
5007 socket_proxy.last_change = now.tv_sec;
5008 socket_proxy.id = "LUA-SOCKET";
5009 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
5010 socket_proxy.maxconn = 0;
5011 socket_proxy.accept = NULL;
5012 socket_proxy.options2 |= PR_O2_INDEPSTR;
5013 socket_proxy.srv = NULL;
5014 socket_proxy.conn_retries = 0;
5015 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
5016
5017 /* Init TCP server: unchanged parameters */
5018 memset(&socket_tcp, 0, sizeof(socket_tcp));
5019 socket_tcp.next = NULL;
5020 socket_tcp.proxy = &socket_proxy;
5021 socket_tcp.obj_type = OBJ_TYPE_SERVER;
5022 LIST_INIT(&socket_tcp.actconns);
5023 LIST_INIT(&socket_tcp.pendconns);
5024 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
5025 socket_tcp.last_change = 0;
5026 socket_tcp.id = "LUA-TCP-CONN";
5027 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5028 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5029 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
5030
5031 /* XXX: Copy default parameter from default server,
5032 * but the default server is not initialized.
5033 */
5034 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
5035 socket_tcp.minconn = socket_proxy.defsrv.minconn;
5036 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
5037 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
5038 socket_tcp.onerror = socket_proxy.defsrv.onerror;
5039 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5040 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
5041 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5042 socket_tcp.uweight = socket_proxy.defsrv.iweight;
5043 socket_tcp.iweight = socket_proxy.defsrv.iweight;
5044
5045 socket_tcp.check.status = HCHK_STATUS_INI;
5046 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
5047 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
5048 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
5049 socket_tcp.check.server = &socket_tcp;
5050
5051 socket_tcp.agent.status = HCHK_STATUS_INI;
5052 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
5053 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
5054 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
5055 socket_tcp.agent.server = &socket_tcp;
5056
5057 socket_tcp.xprt = &raw_sock;
5058
5059#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005060 /* Init TCP server: unchanged parameters */
5061 memset(&socket_ssl, 0, sizeof(socket_ssl));
5062 socket_ssl.next = NULL;
5063 socket_ssl.proxy = &socket_proxy;
5064 socket_ssl.obj_type = OBJ_TYPE_SERVER;
5065 LIST_INIT(&socket_ssl.actconns);
5066 LIST_INIT(&socket_ssl.pendconns);
5067 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
5068 socket_ssl.last_change = 0;
5069 socket_ssl.id = "LUA-SSL-CONN";
5070 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5071 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5072 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
5073
5074 /* XXX: Copy default parameter from default server,
5075 * but the default server is not initialized.
5076 */
5077 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
5078 socket_ssl.minconn = socket_proxy.defsrv.minconn;
5079 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
5080 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
5081 socket_ssl.onerror = socket_proxy.defsrv.onerror;
5082 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5083 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
5084 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5085 socket_ssl.uweight = socket_proxy.defsrv.iweight;
5086 socket_ssl.iweight = socket_proxy.defsrv.iweight;
5087
5088 socket_ssl.check.status = HCHK_STATUS_INI;
5089 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
5090 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
5091 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
5092 socket_ssl.check.server = &socket_ssl;
5093
5094 socket_ssl.agent.status = HCHK_STATUS_INI;
5095 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
5096 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
5097 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
5098 socket_ssl.agent.server = &socket_ssl;
5099
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005100 socket_ssl.use_ssl = 1;
5101 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005102
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005103 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005104 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
5105 /*
5106 *
5107 * If the keyword is not known, we can search in the registered
5108 * server keywords. This is usefull to configure special SSL
5109 * features like client certificates and ssl_verify.
5110 *
5111 */
5112 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
5113 if (tmp_error != 0) {
5114 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
5115 abort(); /* This must be never arrives because the command line
5116 not editable by the user. */
5117 }
5118 idx += kw->skip;
5119 }
5120 }
5121
5122 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005123 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005124#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01005125}