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