blob: ab4a5e7da68a4e6ee5382f959c84efbe100c6c54 [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;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200635 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100636 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;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200646 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100647 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;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200657 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100658 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;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200672 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100673 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;
Thierry FOURNIER1d33b882015-05-11 15:25:29 +02002776 smp.opt = 0;
Thierry FOURNIER0786d052015-05-11 15:42:45 +02002777 if (!f->process(args, &smp, f->kw, f->private)) {
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002778 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002779 lua_pushstring(L, "");
2780 else
2781 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002782 return 1;
2783 }
2784
2785 /* Convert the returned sample in lua value. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002786 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002787 hlua_smp2lua_str(L, &smp);
2788 else
2789 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002790 return 1;
2791}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002792
2793/*
2794 *
2795 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002796 * Class Converters
2797 *
2798 *
2799 */
2800
2801/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002802 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002803 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002804__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002805{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002806 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002807}
2808
2809/* This function creates and push in the stack a Converters object
2810 * according with a current TXN.
2811 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002812static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002813{
Willy Tarreau7073c472015-04-06 11:15:40 +02002814 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002815
2816 /* Check stack size. */
2817 if (!lua_checkstack(L, 3))
2818 return 0;
2819
2820 /* Create the object: obj[0] = userdata.
2821 * Note that the base of the Converters object is the
2822 * same than the TXN object.
2823 */
2824 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002825 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002826 lua_rawseti(L, -2, 0);
2827
Willy Tarreau7073c472015-04-06 11:15:40 +02002828 hsmp->s = txn->s;
2829 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002830 hsmp->stringsafe = stringsafe;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002831
Willy Tarreau87b09662015-04-03 00:22:06 +02002832 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002833 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
2834 lua_setmetatable(L, -2);
2835
2836 return 1;
2837}
2838
2839/* This function is an LUA binding. It is called with each converter.
2840 * It uses closure argument to store the associated converter. It
2841 * returns only one argument or throws an error. An error is thrown
2842 * only if an error is encountered during the argument parsing. If
2843 * the converter function function fails, nil is returned.
2844 */
2845__LJMP static int hlua_run_sample_conv(lua_State *L)
2846{
Willy Tarreauda5f1082015-04-06 11:17:13 +02002847 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002848 struct sample_conv *conv;
2849 struct arg args[ARGM_NBARGS + 1];
2850 int i;
2851 struct sample smp;
2852
2853 /* Get closure arguments. */
2854 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
2855
2856 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002857 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002858
2859 /* Get extra arguments. */
2860 for (i = 0; i < lua_gettop(L) - 2; i++) {
2861 if (i >= ARGM_NBARGS)
2862 break;
2863 hlua_lua2arg(L, i + 3, &args[i]);
2864 }
2865 args[i].type = ARGT_STOP;
2866
2867 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002868 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002869
2870 /* Run the special args checker. */
2871 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
2872 hlua_pusherror(L, "error in arguments");
2873 WILL_LJMP(lua_error(L));
2874 }
2875
2876 /* Initialise the sample. */
2877 if (!hlua_lua2smp(L, 2, &smp)) {
2878 hlua_pusherror(L, "error in the input argument");
2879 WILL_LJMP(lua_error(L));
2880 }
2881
2882 /* Apply expected cast. */
2883 if (!sample_casts[smp.type][conv->in_type]) {
2884 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
2885 smp_to_type[smp.type], smp_to_type[conv->in_type]);
2886 WILL_LJMP(lua_error(L));
2887 }
2888 if (sample_casts[smp.type][conv->in_type] != c_none &&
2889 !sample_casts[smp.type][conv->in_type](&smp)) {
2890 hlua_pusherror(L, "error during the input argument casting");
2891 WILL_LJMP(lua_error(L));
2892 }
2893
2894 /* Run the sample conversion process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02002895 smp.px = hsmp->p;
2896 smp.sess = hsmp->s->sess;
2897 smp.strm = hsmp->s;
Thierry FOURNIER1d33b882015-05-11 15:25:29 +02002898 smp.opt = 0;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02002899 if (!conv->process(args, &smp, conv->private)) {
Willy Tarreauda5f1082015-04-06 11:17:13 +02002900 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002901 lua_pushstring(L, "");
2902 else
2903 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002904 return 1;
2905 }
2906
2907 /* Convert the returned sample in lua value. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002908 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002909 hlua_smp2lua_str(L, &smp);
2910 else
2911 hlua_smp2lua(L, &smp);
2912 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002913}
2914
2915/*
2916 *
2917 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002918 * Class HTTP
2919 *
2920 *
2921 */
2922
2923/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002924 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002925 */
2926__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
2927{
2928 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
2929}
2930
2931/* This function creates and push in the stack a HTTP object
2932 * according with a current TXN.
2933 */
2934static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
2935{
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002936 struct hlua_txn *htxn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002937
2938 /* Check stack size. */
2939 if (!lua_checkstack(L, 3))
2940 return 0;
2941
2942 /* Create the object: obj[0] = userdata.
2943 * Note that the base of the Converters object is the
2944 * same than the TXN object.
2945 */
2946 lua_newtable(L);
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002947 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002948 lua_rawseti(L, -2, 0);
2949
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002950 htxn->s = txn->s;
2951 htxn->p = txn->p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002952
Willy Tarreau87b09662015-04-03 00:22:06 +02002953 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002954 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
2955 lua_setmetatable(L, -2);
2956
2957 return 1;
2958}
2959
2960/* This function creates ans returns an array of HTTP headers.
2961 * This function does not fails. It is used as wrapper with the
2962 * 2 following functions.
2963 */
2964__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
2965{
2966 const char *cur_ptr, *cur_next, *p;
2967 int old_idx, cur_idx;
2968 struct hdr_idx_elem *cur_hdr;
2969 const char *hn, *hv;
2970 int hnl, hvl;
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01002971 int type;
2972 const char *in;
2973 char *out;
2974 int len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002975
2976 /* Create the table. */
2977 lua_newtable(L);
2978
Willy Tarreaueee5b512015-04-03 23:46:31 +02002979 if (!htxn->s->txn)
2980 return 1;
2981
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002982 /* Build array of headers. */
2983 old_idx = 0;
Willy Tarreaueee5b512015-04-03 23:46:31 +02002984 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002985
2986 while (1) {
Willy Tarreaueee5b512015-04-03 23:46:31 +02002987 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002988 if (!cur_idx)
2989 break;
2990 old_idx = cur_idx;
2991
Willy Tarreaueee5b512015-04-03 23:46:31 +02002992 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002993 cur_ptr = cur_next;
2994 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
2995
2996 /* Now we have one full header at cur_ptr of len cur_hdr->len,
2997 * and the next header starts at cur_next. We'll check
2998 * this header in the list as well as against the default
2999 * rule.
3000 */
3001
3002 /* look for ': *'. */
3003 hn = cur_ptr;
3004 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
3005 if (p >= cur_ptr+cur_hdr->len)
3006 continue;
3007 hnl = p - hn;
3008 p++;
3009 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
3010 p++;
3011 if (p >= cur_ptr+cur_hdr->len)
3012 continue;
3013 hv = p;
3014 hvl = cur_ptr+cur_hdr->len-p;
3015
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003016 /* Lowercase the key. Don't check the size of trash, it have
3017 * the size of one buffer and the input data contains in one
3018 * buffer.
3019 */
3020 out = trash.str;
3021 for (in=hn; in<hn+hnl; in++, out++)
3022 *out = tolower(*in);
3023 *out = '\0';
3024
3025 /* Check for existing entry:
3026 * assume that the table is on the top of the stack, and
3027 * push the key in the stack, the function lua_gettable()
3028 * perform the lookup.
3029 */
3030 lua_pushlstring(L, trash.str, hnl);
3031 lua_gettable(L, -2);
3032 type = lua_type(L, -1);
3033
3034 switch (type) {
3035 case LUA_TNIL:
3036 /* Table not found, create it. */
3037 lua_pop(L, 1); /* remove the nil value. */
3038 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
3039 lua_newtable(L); /* create and push empty table. */
3040 lua_pushlstring(L, hv, hvl); /* push header value. */
3041 lua_rawseti(L, -2, 0); /* index header value (pop it). */
3042 lua_rawset(L, -3); /* index new table with header name (pop the values). */
3043 break;
3044
3045 case LUA_TTABLE:
3046 /* Entry found: push the value in the table. */
3047 len = lua_rawlen(L, -1);
3048 lua_pushlstring(L, hv, hvl); /* push header value. */
3049 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
3050 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
3051 break;
3052
3053 default:
3054 /* Other cases are errors. */
3055 hlua_pusherror(L, "internal error during the parsing of headers.");
3056 WILL_LJMP(lua_error(L));
3057 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003058 }
3059
3060 return 1;
3061}
3062
3063__LJMP static int hlua_http_req_get_headers(lua_State *L)
3064{
3065 struct hlua_txn *htxn;
3066
3067 MAY_LJMP(check_args(L, 1, "req_get_headers"));
3068 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3069
Willy Tarreaueee5b512015-04-03 23:46:31 +02003070 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003071}
3072
3073__LJMP static int hlua_http_res_get_headers(lua_State *L)
3074{
3075 struct hlua_txn *htxn;
3076
3077 MAY_LJMP(check_args(L, 1, "res_get_headers"));
3078 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3079
Willy Tarreaueee5b512015-04-03 23:46:31 +02003080 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003081}
3082
3083/* This function replace full header, or just a value in
3084 * the request or in the response. It is a wrapper fir the
3085 * 4 following functions.
3086 */
3087__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
3088 struct http_msg *msg, int action)
3089{
3090 size_t name_len;
3091 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3092 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
3093 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
3094 struct my_regex re;
3095
3096 if (!regex_comp(reg, &re, 1, 1, NULL))
3097 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
3098
3099 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
3100 regex_free(&re);
3101 return 0;
3102}
3103
3104__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
3105{
3106 struct hlua_txn *htxn;
3107
3108 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3109 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3110
Willy Tarreaueee5b512015-04-03 23:46:31 +02003111 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 +01003112}
3113
3114__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
3115{
3116 struct hlua_txn *htxn;
3117
3118 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
3119 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3120
Willy Tarreaueee5b512015-04-03 23:46:31 +02003121 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 +01003122}
3123
3124__LJMP static int hlua_http_req_rep_val(lua_State *L)
3125{
3126 struct hlua_txn *htxn;
3127
3128 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3129 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3130
Willy Tarreaueee5b512015-04-03 23:46:31 +02003131 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 +01003132}
3133
3134__LJMP static int hlua_http_res_rep_val(lua_State *L)
3135{
3136 struct hlua_txn *htxn;
3137
3138 MAY_LJMP(check_args(L, 4, "res_rep_val"));
3139 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3140
Willy Tarreaueee5b512015-04-03 23:46:31 +02003141 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 +01003142}
3143
3144/* This function deletes all the occurences of an header.
3145 * It is a wrapper for the 2 following functions.
3146 */
3147__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3148{
3149 size_t len;
3150 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3151 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02003152 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003153
3154 ctx.idx = 0;
3155 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
3156 http_remove_header2(msg, &txn->hdr_idx, &ctx);
3157 return 0;
3158}
3159
3160__LJMP static int hlua_http_req_del_hdr(lua_State *L)
3161{
3162 struct hlua_txn *htxn;
3163
3164 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3165 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3166
Willy Tarreaueee5b512015-04-03 23:46:31 +02003167 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003168}
3169
3170__LJMP static int hlua_http_res_del_hdr(lua_State *L)
3171{
3172 struct hlua_txn *htxn;
3173
3174 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3175 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3176
Willy Tarreaueee5b512015-04-03 23:46:31 +02003177 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003178}
3179
3180/* This function adds an header. It is a wrapper used by
3181 * the 2 following functions.
3182 */
3183__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3184{
3185 size_t name_len;
3186 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3187 size_t value_len;
3188 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
3189 char *p;
3190
3191 /* Check length. */
3192 trash.len = value_len + name_len + 2;
3193 if (trash.len > trash.size)
3194 return 0;
3195
3196 /* Creates the header string. */
3197 p = trash.str;
3198 memcpy(p, name, name_len);
3199 p += name_len;
3200 *p = ':';
3201 p++;
3202 *p = ' ';
3203 p++;
3204 memcpy(p, value, value_len);
3205
Willy Tarreaueee5b512015-04-03 23:46:31 +02003206 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003207 trash.str, trash.len) != 0);
3208
3209 return 0;
3210}
3211
3212__LJMP static int hlua_http_req_add_hdr(lua_State *L)
3213{
3214 struct hlua_txn *htxn;
3215
3216 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
3217 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3218
Willy Tarreaueee5b512015-04-03 23:46:31 +02003219 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003220}
3221
3222__LJMP static int hlua_http_res_add_hdr(lua_State *L)
3223{
3224 struct hlua_txn *htxn;
3225
3226 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
3227 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3228
Willy Tarreaueee5b512015-04-03 23:46:31 +02003229 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003230}
3231
3232static int hlua_http_req_set_hdr(lua_State *L)
3233{
3234 struct hlua_txn *htxn;
3235
3236 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
3237 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3238
Willy Tarreaueee5b512015-04-03 23:46:31 +02003239 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
3240 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003241}
3242
3243static int hlua_http_res_set_hdr(lua_State *L)
3244{
3245 struct hlua_txn *htxn;
3246
3247 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
3248 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3249
Willy Tarreaueee5b512015-04-03 23:46:31 +02003250 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
3251 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003252}
3253
3254/* This function set the method. */
3255static int hlua_http_req_set_meth(lua_State *L)
3256{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003257 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003258 size_t name_len;
3259 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003260
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003261 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003262 return 1;
3263}
3264
3265/* This function set the method. */
3266static int hlua_http_req_set_path(lua_State *L)
3267{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003268 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003269 size_t name_len;
3270 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003271 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003272 return 1;
3273}
3274
3275/* This function set the query-string. */
3276static int hlua_http_req_set_query(lua_State *L)
3277{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003278 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003279 size_t name_len;
3280 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003281
3282 /* Check length. */
3283 if (name_len > trash.size - 1) {
3284 lua_pushboolean(L, 0);
3285 return 1;
3286 }
3287
3288 /* Add the mark question as prefix. */
3289 chunk_reset(&trash);
3290 trash.str[trash.len++] = '?';
3291 memcpy(trash.str + trash.len, name, name_len);
3292 trash.len += name_len;
3293
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003294 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003295 return 1;
3296}
3297
3298/* This function set the uri. */
3299static int hlua_http_req_set_uri(lua_State *L)
3300{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003301 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003302 size_t name_len;
3303 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003304
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003305 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003306 return 1;
3307}
3308
3309/*
3310 *
3311 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003312 * Class TXN
3313 *
3314 *
3315 */
3316
3317/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003318 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003319 */
3320__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
3321{
3322 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
3323}
3324
Willy Tarreau59551662015-03-10 14:23:13 +01003325__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003326{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003327 struct hlua *hlua;
3328
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003329 MAY_LJMP(check_args(L, 2, "set_priv"));
3330
Willy Tarreau87b09662015-04-03 00:22:06 +02003331 /* It is useles to retrieve the stream, but this function
3332 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003333 */
3334 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003335 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003336
3337 /* Remove previous value. */
3338 if (hlua->Mref != -1)
3339 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3340
3341 /* Get and store new value. */
3342 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3343 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3344
3345 return 0;
3346}
3347
Willy Tarreau59551662015-03-10 14:23:13 +01003348__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003349{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003350 struct hlua *hlua;
3351
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003352 MAY_LJMP(check_args(L, 1, "get_priv"));
3353
Willy Tarreau87b09662015-04-03 00:22:06 +02003354 /* It is useles to retrieve the stream, but this function
3355 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003356 */
3357 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003358 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003359
3360 /* Push configuration index in the stack. */
3361 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3362
3363 return 1;
3364}
3365
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003366/* Create stack entry containing a class TXN. This function
3367 * return 0 if the stack does not contains free slots,
3368 * otherwise it returns 1.
3369 */
Willy Tarreau15e91e12015-04-04 00:52:09 +02003370static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003371{
Willy Tarreaude491382015-04-06 11:04:28 +02003372 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003373
3374 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003375 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003376 return 0;
3377
3378 /* NOTE: The allocation never fails. The failure
3379 * throw an error, and the function never returns.
3380 * if the throw is not avalaible, the process is aborted.
3381 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003382 /* Create the object: obj[0] = userdata. */
3383 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02003384 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003385 lua_rawseti(L, -2, 0);
3386
Willy Tarreaude491382015-04-06 11:04:28 +02003387 htxn->s = s;
3388 htxn->p = p;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003389
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003390 /* Create the "f" field that contains a list of fetches. */
3391 lua_pushstring(L, "f");
Willy Tarreaude491382015-04-06 11:04:28 +02003392 if (!hlua_fetches_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003393 return 0;
3394 lua_settable(L, -3);
3395
3396 /* Create the "sf" field that contains a list of stringsafe fetches. */
3397 lua_pushstring(L, "sf");
Willy Tarreaude491382015-04-06 11:04:28 +02003398 if (!hlua_fetches_new(L, htxn, 1))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003399 return 0;
3400 lua_settable(L, -3);
3401
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003402 /* Create the "c" field that contains a list of converters. */
3403 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02003404 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003405 return 0;
3406 lua_settable(L, -3);
3407
3408 /* Create the "sc" field that contains a list of stringsafe converters. */
3409 lua_pushstring(L, "sc");
Willy Tarreaude491382015-04-06 11:04:28 +02003410 if (!hlua_converters_new(L, htxn, 1))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003411 return 0;
3412 lua_settable(L, -3);
3413
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003414 /* Create the "req" field that contains the request channel object. */
3415 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003416 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003417 return 0;
3418 lua_settable(L, -3);
3419
3420 /* Create the "res" field that contains the response channel object. */
3421 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003422 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003423 return 0;
3424 lua_settable(L, -3);
3425
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003426 /* Creates the HTTP object is the current proxy allows http. */
3427 lua_pushstring(L, "http");
3428 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02003429 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003430 return 0;
3431 }
3432 else
3433 lua_pushnil(L);
3434 lua_settable(L, -3);
3435
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003436 /* Pop a class sesison metatable and affect it to the userdata. */
3437 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
3438 lua_setmetatable(L, -2);
3439
3440 return 1;
3441}
3442
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003443__LJMP static int hlua_txn_deflog(lua_State *L)
3444{
3445 const char *msg;
3446 struct hlua_txn *htxn;
3447
3448 MAY_LJMP(check_args(L, 2, "deflog"));
3449 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3450 msg = MAY_LJMP(luaL_checkstring(L, 2));
3451
3452 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
3453 return 0;
3454}
3455
3456__LJMP static int hlua_txn_log(lua_State *L)
3457{
3458 int level;
3459 const char *msg;
3460 struct hlua_txn *htxn;
3461
3462 MAY_LJMP(check_args(L, 3, "log"));
3463 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3464 level = MAY_LJMP(luaL_checkinteger(L, 2));
3465 msg = MAY_LJMP(luaL_checkstring(L, 3));
3466
3467 if (level < 0 || level >= NB_LOG_LEVELS)
3468 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3469
3470 hlua_sendlog(htxn->s->be, level, msg);
3471 return 0;
3472}
3473
3474__LJMP static int hlua_txn_log_debug(lua_State *L)
3475{
3476 const char *msg;
3477 struct hlua_txn *htxn;
3478
3479 MAY_LJMP(check_args(L, 2, "Debug"));
3480 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3481 msg = MAY_LJMP(luaL_checkstring(L, 2));
3482 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
3483 return 0;
3484}
3485
3486__LJMP static int hlua_txn_log_info(lua_State *L)
3487{
3488 const char *msg;
3489 struct hlua_txn *htxn;
3490
3491 MAY_LJMP(check_args(L, 2, "Info"));
3492 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3493 msg = MAY_LJMP(luaL_checkstring(L, 2));
3494 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
3495 return 0;
3496}
3497
3498__LJMP static int hlua_txn_log_warning(lua_State *L)
3499{
3500 const char *msg;
3501 struct hlua_txn *htxn;
3502
3503 MAY_LJMP(check_args(L, 2, "Warning"));
3504 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3505 msg = MAY_LJMP(luaL_checkstring(L, 2));
3506 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
3507 return 0;
3508}
3509
3510__LJMP static int hlua_txn_log_alert(lua_State *L)
3511{
3512 const char *msg;
3513 struct hlua_txn *htxn;
3514
3515 MAY_LJMP(check_args(L, 2, "Alert"));
3516 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3517 msg = MAY_LJMP(luaL_checkstring(L, 2));
3518 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
3519 return 0;
3520}
3521
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003522__LJMP static int hlua_txn_set_loglevel(lua_State *L)
3523{
3524 struct hlua_txn *htxn;
3525 int ll;
3526
3527 MAY_LJMP(check_args(L, 2, "set_loglevel"));
3528 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3529 ll = MAY_LJMP(luaL_checkinteger(L, 2));
3530
3531 if (ll < 0 || ll > 7)
3532 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
3533
3534 htxn->s->logs.level = ll;
3535 return 0;
3536}
3537
3538__LJMP static int hlua_txn_set_tos(lua_State *L)
3539{
3540 struct hlua_txn *htxn;
3541 struct connection *cli_conn;
3542 int tos;
3543
3544 MAY_LJMP(check_args(L, 2, "set_tos"));
3545 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3546 tos = MAY_LJMP(luaL_checkinteger(L, 2));
3547
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003548 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003549 inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, tos);
3550
3551 return 0;
3552}
3553
3554__LJMP static int hlua_txn_set_mark(lua_State *L)
3555{
3556#ifdef SO_MARK
3557 struct hlua_txn *htxn;
3558 struct connection *cli_conn;
3559 int mark;
3560
3561 MAY_LJMP(check_args(L, 2, "set_mark"));
3562 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3563 mark = MAY_LJMP(luaL_checkinteger(L, 2));
3564
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003565 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02003566 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003567#endif
3568 return 0;
3569}
3570
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003571/* This function is an Lua binding that send pending data
3572 * to the client, and close the stream interface.
3573 */
3574__LJMP static int hlua_txn_close(lua_State *L)
3575{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003576 struct hlua_txn *htxn;
Willy Tarreau81389672015-03-10 12:03:52 +01003577 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003578
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003579 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003580 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003581
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003582 ic = &htxn->s->req;
3583 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01003584
3585 channel_abort(ic);
3586 channel_auto_close(ic);
3587 channel_erase(ic);
3588 channel_auto_read(oc);
3589 channel_auto_close(oc);
3590 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003591
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003592 return 0;
3593}
3594
3595__LJMP static int hlua_log(lua_State *L)
3596{
3597 int level;
3598 const char *msg;
3599
3600 MAY_LJMP(check_args(L, 2, "log"));
3601 level = MAY_LJMP(luaL_checkinteger(L, 1));
3602 msg = MAY_LJMP(luaL_checkstring(L, 2));
3603
3604 if (level < 0 || level >= NB_LOG_LEVELS)
3605 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3606
3607 hlua_sendlog(NULL, level, msg);
3608 return 0;
3609}
3610
3611__LJMP static int hlua_log_debug(lua_State *L)
3612{
3613 const char *msg;
3614
3615 MAY_LJMP(check_args(L, 1, "debug"));
3616 msg = MAY_LJMP(luaL_checkstring(L, 1));
3617 hlua_sendlog(NULL, LOG_DEBUG, msg);
3618 return 0;
3619}
3620
3621__LJMP static int hlua_log_info(lua_State *L)
3622{
3623 const char *msg;
3624
3625 MAY_LJMP(check_args(L, 1, "info"));
3626 msg = MAY_LJMP(luaL_checkstring(L, 1));
3627 hlua_sendlog(NULL, LOG_INFO, msg);
3628 return 0;
3629}
3630
3631__LJMP static int hlua_log_warning(lua_State *L)
3632{
3633 const char *msg;
3634
3635 MAY_LJMP(check_args(L, 1, "warning"));
3636 msg = MAY_LJMP(luaL_checkstring(L, 1));
3637 hlua_sendlog(NULL, LOG_WARNING, msg);
3638 return 0;
3639}
3640
3641__LJMP static int hlua_log_alert(lua_State *L)
3642{
3643 const char *msg;
3644
3645 MAY_LJMP(check_args(L, 1, "alert"));
3646 msg = MAY_LJMP(luaL_checkstring(L, 1));
3647 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003648 return 0;
3649}
3650
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003651__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003652{
3653 int wakeup_ms = lua_tointeger(L, -1);
3654 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003655 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003656 return 0;
3657}
3658
3659__LJMP static int hlua_sleep(lua_State *L)
3660{
3661 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003662 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003663
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003664 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003665
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003666 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003667 wakeup_ms = tick_add(now_ms, delay);
3668 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003669
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003670 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3671 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003672}
3673
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003674__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003675{
3676 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003677 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003678
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003679 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003680
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003681 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003682 wakeup_ms = tick_add(now_ms, delay);
3683 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003684
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003685 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3686 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003687}
3688
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003689/* This functionis an LUA binding. it permits to give back
3690 * the hand at the HAProxy scheduler. It is used when the
3691 * LUA processing consumes a lot of time.
3692 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003693__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003694{
3695 return 0;
3696}
3697
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003698__LJMP static int hlua_yield(lua_State *L)
3699{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003700 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
3701 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003702}
3703
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003704/* This function change the nice of the currently executed
3705 * task. It is used set low or high priority at the current
3706 * task.
3707 */
Willy Tarreau59551662015-03-10 14:23:13 +01003708__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003709{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003710 struct hlua *hlua;
3711 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003712
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003713 MAY_LJMP(check_args(L, 1, "set_nice"));
3714 hlua = hlua_gethlua(L);
3715 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003716
3717 /* If he task is not set, I'm in a start mode. */
3718 if (!hlua || !hlua->task)
3719 return 0;
3720
3721 if (nice < -1024)
3722 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003723 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003724 nice = 1024;
3725
3726 hlua->task->nice = nice;
3727 return 0;
3728}
3729
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003730/* This function is used as a calback of a task. It is called by the
3731 * HAProxy task subsystem when the task is awaked. The LUA runtime can
3732 * return an E_AGAIN signal, the emmiter of this signal must set a
3733 * signal to wake the task.
3734 */
3735static struct task *hlua_process_task(struct task *task)
3736{
3737 struct hlua *hlua = task->context;
3738 enum hlua_exec status;
3739
3740 /* We need to remove the task from the wait queue before executing
3741 * the Lua code because we don't know if it needs to wait for
3742 * another timer or not in the case of E_AGAIN.
3743 */
3744 task_delete(task);
3745
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003746 /* If it is the first call to the task, we must initialize the
3747 * execution timeouts.
3748 */
3749 if (!HLUA_IS_RUNNING(hlua))
3750 hlua->expire = tick_add(now_ms, hlua_timeout_task);
3751
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003752 /* Execute the Lua code. */
3753 status = hlua_ctx_resume(hlua, 1);
3754
3755 switch (status) {
3756 /* finished or yield */
3757 case HLUA_E_OK:
3758 hlua_ctx_destroy(hlua);
3759 task_delete(task);
3760 task_free(task);
3761 break;
3762
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003763 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
3764 if (hlua->wake_time != TICK_ETERNITY)
3765 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003766 break;
3767
3768 /* finished with error. */
3769 case HLUA_E_ERRMSG:
3770 send_log(NULL, LOG_ERR, "Lua task: %s.", lua_tostring(hlua->T, -1));
3771 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3772 Alert("Lua task: %s.\n", lua_tostring(hlua->T, -1));
3773 hlua_ctx_destroy(hlua);
3774 task_delete(task);
3775 task_free(task);
3776 break;
3777
3778 case HLUA_E_ERR:
3779 default:
3780 send_log(NULL, LOG_ERR, "Lua task: unknown error.");
3781 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3782 Alert("Lua task: unknown error.\n");
3783 hlua_ctx_destroy(hlua);
3784 task_delete(task);
3785 task_free(task);
3786 break;
3787 }
3788 return NULL;
3789}
3790
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003791/* This function is an LUA binding that register LUA function to be
3792 * executed after the HAProxy configuration parsing and before the
3793 * HAProxy scheduler starts. This function expect only one LUA
3794 * argument that is a function. This function returns nothing, but
3795 * throws if an error is encountered.
3796 */
3797__LJMP static int hlua_register_init(lua_State *L)
3798{
3799 struct hlua_init_function *init;
3800 int ref;
3801
3802 MAY_LJMP(check_args(L, 1, "register_init"));
3803
3804 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3805
3806 init = malloc(sizeof(*init));
3807 if (!init)
3808 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3809
3810 init->function_ref = ref;
3811 LIST_ADDQ(&hlua_init_functions, &init->l);
3812 return 0;
3813}
3814
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003815/* This functio is an LUA binding. It permits to register a task
3816 * executed in parallel of the main HAroxy activity. The task is
3817 * created and it is set in the HAProxy scheduler. It can be called
3818 * from the "init" section, "post init" or during the runtime.
3819 *
3820 * Lua prototype:
3821 *
3822 * <none> core.register_task(<function>)
3823 */
3824static int hlua_register_task(lua_State *L)
3825{
3826 struct hlua *hlua;
3827 struct task *task;
3828 int ref;
3829
3830 MAY_LJMP(check_args(L, 1, "register_task"));
3831
3832 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3833
3834 hlua = malloc(sizeof(*hlua));
3835 if (!hlua)
3836 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3837
3838 task = task_new();
3839 task->context = hlua;
3840 task->process = hlua_process_task;
3841
3842 if (!hlua_ctx_init(hlua, task))
3843 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3844
3845 /* Restore the function in the stack. */
3846 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
3847 hlua->nargs = 0;
3848
3849 /* Schedule task. */
3850 task_schedule(task, now_ms);
3851
3852 return 0;
3853}
3854
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003855/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
3856 * doesn't allow "yield" functions because the HAProxy engine cannot
3857 * resume converters.
3858 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003859static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003860{
3861 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003862 struct stream *stream = smp->strm;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003863
Willy Tarreau87b09662015-04-03 00:22:06 +02003864 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003865 * Lua context can be not initialized. This behavior
3866 * permits to save performances because a systematic
3867 * Lua initialization cause 5% performances loss.
3868 */
Willy Tarreau87b09662015-04-03 00:22:06 +02003869 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
3870 send_log(stream->be, LOG_ERR, "Lua converter '%s': can't initialize Lua context.", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003871 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3872 Alert("Lua converter '%s': can't initialize Lua context.\n", fcn->name);
3873 return 0;
3874 }
3875
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003876 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003877 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003878 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003879 if (!lua_checkstack(stream->hlua.T, 1)) {
3880 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003881 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3882 Alert("Lua converter '%s': full stack.\n", fcn->name);
3883 return 0;
3884 }
3885
3886 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003887 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003888
3889 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003890 if (!lua_checkstack(stream->hlua.T, 1)) {
3891 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003892 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3893 Alert("Lua converter '%s': full stack.\n", fcn->name);
3894 return 0;
3895 }
Willy Tarreau87b09662015-04-03 00:22:06 +02003896 hlua_smp2lua(stream->hlua.T, smp);
3897 stream->hlua.nargs = 2;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003898
3899 /* push keywords in the stack. */
3900 if (arg_p) {
3901 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02003902 if (!lua_checkstack(stream->hlua.T, 1)) {
3903 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003904 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3905 Alert("Lua converter '%s': full stack.\n", fcn->name);
3906 return 0;
3907 }
Willy Tarreau87b09662015-04-03 00:22:06 +02003908 hlua_arg2lua(stream->hlua.T, arg_p);
3909 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003910 }
3911 }
3912
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003913 /* We must initialize the execution timeouts. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003914 stream->hlua.expire = tick_add(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003915
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003916 /* Set the currently running flag. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003917 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003918 }
3919
3920 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003921 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003922 /* finished. */
3923 case HLUA_E_OK:
3924 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003925 hlua_lua2smp(stream->hlua.T, -1, smp);
3926 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003927 return 1;
3928
3929 /* yield. */
3930 case HLUA_E_AGAIN:
Willy Tarreau87b09662015-04-03 00:22:06 +02003931 send_log(stream->be, LOG_ERR, "Lua converter '%s': cannot use yielded functions.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003932 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3933 Alert("Lua converter '%s': cannot use yielded functions.\n", fcn->name);
3934 return 0;
3935
3936 /* finished with error. */
3937 case HLUA_E_ERRMSG:
3938 /* Display log. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003939 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 +01003940 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Willy Tarreau87b09662015-04-03 00:22:06 +02003941 Alert("Lua converter '%s': %s.\n", fcn->name, lua_tostring(stream->hlua.T, -1));
3942 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003943 return 0;
3944
3945 case HLUA_E_ERR:
3946 /* Display log. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003947 send_log(stream->be, LOG_ERR, "Lua converter '%s' returns an unknown error.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003948 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3949 Alert("Lua converter '%s' returns an unknown error.\n", fcn->name);
3950
3951 default:
3952 return 0;
3953 }
3954}
3955
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003956/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
3957 * doesn't allow "yield" functions because the HAProxy engine cannot
3958 * resume sample-fetches.
3959 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003960static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
3961 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003962{
3963 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003964 struct stream *stream = smp->strm;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003965
Willy Tarreau87b09662015-04-03 00:22:06 +02003966 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003967 * Lua context can be not initialized. This behavior
3968 * permits to save performances because a systematic
3969 * Lua initialization cause 5% performances loss.
3970 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003971 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
3972 send_log(stream->be, LOG_ERR, "Lua sample-fetch '%s': can't initialize Lua context.", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003973 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3974 Alert("Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
3975 return 0;
3976 }
3977
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003978 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003979 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003980 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003981 if (!lua_checkstack(stream->hlua.T, 2)) {
3982 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003983 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3984 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3985 return 0;
3986 }
3987
3988 /* Restore the function in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003989 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003990
3991 /* push arguments in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003992 if (!hlua_txn_new(stream->hlua.T, stream, smp->px)) {
3993 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003994 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3995 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3996 return 0;
3997 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003998 stream->hlua.nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003999
4000 /* push keywords in the stack. */
4001 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
4002 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004003 if (!lua_checkstack(stream->hlua.T, 1)) {
4004 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004005 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4006 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4007 return 0;
4008 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004009 if (!lua_checkstack(stream->hlua.T, 1)) {
4010 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004011 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4012 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4013 return 0;
4014 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004015 hlua_arg2lua(stream->hlua.T, arg_p);
4016 stream->hlua.nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004017 }
4018
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004019 /* We must initialize the execution timeouts. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004020 stream->hlua.expire = tick_add(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004021
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004022 /* Set the currently running flag. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004023 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004024 }
4025
4026 /* Execute the function. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004027 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004028 /* finished. */
4029 case HLUA_E_OK:
4030 /* Convert the returned value in sample. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004031 hlua_lua2smp(stream->hlua.T, -1, smp);
4032 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004033
4034 /* Set the end of execution flag. */
4035 smp->flags &= ~SMP_F_MAY_CHANGE;
4036 return 1;
4037
4038 /* yield. */
4039 case HLUA_E_AGAIN:
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004040 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': cannot use yielded functions.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004041 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4042 Alert("Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
4043 return 0;
4044
4045 /* finished with error. */
4046 case HLUA_E_ERRMSG:
4047 /* Display log. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004048 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': %s.", fcn->name, lua_tostring(stream->hlua.T, -1));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004049 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004050 Alert("Lua sample-fetch '%s': %s.\n", fcn->name, lua_tostring(stream->hlua.T, -1));
4051 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004052 return 0;
4053
4054 case HLUA_E_ERR:
4055 /* Display log. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004056 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s' returns an unknown error.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004057 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4058 Alert("Lua sample-fetch '%s': returns an unknown error.\n", fcn->name);
4059
4060 default:
4061 return 0;
4062 }
4063}
4064
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004065/* This function is an LUA binding used for registering
4066 * "sample-conv" functions. It expects a converter name used
4067 * in the haproxy configuration file, and an LUA function.
4068 */
4069__LJMP static int hlua_register_converters(lua_State *L)
4070{
4071 struct sample_conv_kw_list *sck;
4072 const char *name;
4073 int ref;
4074 int len;
4075 struct hlua_function *fcn;
4076
4077 MAY_LJMP(check_args(L, 2, "register_converters"));
4078
4079 /* First argument : converter name. */
4080 name = MAY_LJMP(luaL_checkstring(L, 1));
4081
4082 /* Second argument : lua function. */
4083 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4084
4085 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004086 sck = malloc(sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004087 if (!sck)
4088 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4089 fcn = malloc(sizeof(*fcn));
4090 if (!fcn)
4091 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4092
4093 /* Fill fcn. */
4094 fcn->name = strdup(name);
4095 if (!fcn->name)
4096 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4097 fcn->function_ref = ref;
4098
4099 /* List head */
4100 sck->list.n = sck->list.p = NULL;
4101
4102 /* converter keyword. */
4103 len = strlen("lua.") + strlen(name) + 1;
4104 sck->kw[0].kw = malloc(len);
4105 if (!sck->kw[0].kw)
4106 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4107
4108 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
4109 sck->kw[0].process = hlua_sample_conv_wrapper;
4110 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4111 sck->kw[0].val_args = NULL;
4112 sck->kw[0].in_type = SMP_T_STR;
4113 sck->kw[0].out_type = SMP_T_STR;
4114 sck->kw[0].private = fcn;
4115
4116 /* End of array. */
4117 memset(&sck->kw[1], 0, sizeof(struct sample_conv));
4118
4119 /* Register this new converter */
4120 sample_register_convs(sck);
4121
4122 return 0;
4123}
4124
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004125/* This fucntion is an LUA binding used for registering
4126 * "sample-fetch" functions. It expects a converter name used
4127 * in the haproxy configuration file, and an LUA function.
4128 */
4129__LJMP static int hlua_register_fetches(lua_State *L)
4130{
4131 const char *name;
4132 int ref;
4133 int len;
4134 struct sample_fetch_kw_list *sfk;
4135 struct hlua_function *fcn;
4136
4137 MAY_LJMP(check_args(L, 2, "register_fetches"));
4138
4139 /* First argument : sample-fetch name. */
4140 name = MAY_LJMP(luaL_checkstring(L, 1));
4141
4142 /* Second argument : lua function. */
4143 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4144
4145 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004146 sfk = malloc(sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004147 if (!sfk)
4148 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4149 fcn = malloc(sizeof(*fcn));
4150 if (!fcn)
4151 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4152
4153 /* Fill fcn. */
4154 fcn->name = strdup(name);
4155 if (!fcn->name)
4156 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4157 fcn->function_ref = ref;
4158
4159 /* List head */
4160 sfk->list.n = sfk->list.p = NULL;
4161
4162 /* sample-fetch keyword. */
4163 len = strlen("lua.") + strlen(name) + 1;
4164 sfk->kw[0].kw = malloc(len);
4165 if (!sfk->kw[0].kw)
4166 return luaL_error(L, "lua out of memory error.");
4167
4168 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
4169 sfk->kw[0].process = hlua_sample_fetch_wrapper;
4170 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4171 sfk->kw[0].val_args = NULL;
4172 sfk->kw[0].out_type = SMP_T_STR;
4173 sfk->kw[0].use = SMP_USE_HTTP_ANY;
4174 sfk->kw[0].val = 0;
4175 sfk->kw[0].private = fcn;
4176
4177 /* End of array. */
4178 memset(&sfk->kw[1], 0, sizeof(struct sample_fetch));
4179
4180 /* Register this new fetch. */
4181 sample_register_fetches(sfk);
4182
4183 return 0;
4184}
4185
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004186/* global {tcp|http}-request parser. Return 1 in succes case, else return 0. */
4187static int hlua_parse_rule(const char **args, int *cur_arg, struct proxy *px,
4188 struct hlua_rule **rule_p, char **err)
4189{
4190 struct hlua_rule *rule;
4191
4192 /* Memory for the rule. */
4193 rule = malloc(sizeof(*rule));
4194 if (!rule) {
4195 memprintf(err, "out of memory error");
4196 return 0;
4197 }
4198 *rule_p = rule;
4199
4200 /* The requiered arg is a function name. */
4201 if (!args[*cur_arg]) {
4202 memprintf(err, "expect Lua function name");
4203 return 0;
4204 }
4205
4206 /* Lookup for the symbol, and check if it is a function. */
4207 lua_getglobal(gL.T, args[*cur_arg]);
4208 if (lua_isnil(gL.T, -1)) {
4209 lua_pop(gL.T, 1);
4210 memprintf(err, "Lua function '%s' not found", args[*cur_arg]);
4211 return 0;
4212 }
4213 if (!lua_isfunction(gL.T, -1)) {
4214 lua_pop(gL.T, 1);
4215 memprintf(err, "'%s' is not a function", args[*cur_arg]);
4216 return 0;
4217 }
4218
4219 /* Reference the Lua function and store the reference. */
4220 rule->fcn.function_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
4221 rule->fcn.name = strdup(args[*cur_arg]);
4222 if (!rule->fcn.name) {
4223 memprintf(err, "out of memory error.");
4224 return 0;
4225 }
4226 (*cur_arg)++;
4227
4228 /* TODO: later accept arguments. */
4229 rule->args = NULL;
4230
4231 return 1;
4232}
4233
4234/* This function is a wrapper to execute each LUA function declared
4235 * as an action wrapper during the initialisation period. This function
4236 * return 1 if the processing is finished (with oe without error) and
4237 * return 0 if the function must be called again because the LUA
4238 * returns a yield.
4239 */
4240static int hlua_request_act_wrapper(struct hlua_rule *rule, struct proxy *px,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004241 struct stream *s, unsigned int analyzer)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004242{
4243 char **arg;
4244
Willy Tarreau87b09662015-04-03 00:22:06 +02004245 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004246 * Lua context can be not initialized. This behavior
4247 * permits to save performances because a systematic
4248 * Lua initialization cause 5% performances loss.
4249 */
4250 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
4251 send_log(px, LOG_ERR, "Lua action '%s': can't initialize Lua context.", rule->fcn.name);
4252 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4253 Alert("Lua action '%s': can't initialize Lua context.\n", rule->fcn.name);
4254 return 0;
4255 }
4256
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004257 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004258 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004259 /* Check stack available size. */
4260 if (!lua_checkstack(s->hlua.T, 1)) {
4261 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
4262 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4263 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
4264 return 0;
4265 }
4266
4267 /* Restore the function in the stack. */
4268 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->fcn.function_ref);
4269
Willy Tarreau87b09662015-04-03 00:22:06 +02004270 /* Create and and push object stream in the stack. */
Willy Tarreau15e91e12015-04-04 00:52:09 +02004271 if (!hlua_txn_new(s->hlua.T, s, px)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004272 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
4273 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4274 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
4275 return 0;
4276 }
4277 s->hlua.nargs = 1;
4278
4279 /* push keywords in the stack. */
4280 for (arg = rule->args; arg && *arg; arg++) {
4281 if (!lua_checkstack(s->hlua.T, 1)) {
4282 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
4283 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4284 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
4285 return 0;
4286 }
4287 lua_pushstring(s->hlua.T, *arg);
4288 s->hlua.nargs++;
4289 }
4290
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004291 /* We must initialize the execution timeouts. */
4292 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
4293
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004294 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004295 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004296 }
4297
4298 /* Execute the function. */
4299 switch (hlua_ctx_resume(&s->hlua, 1)) {
4300 /* finished. */
4301 case HLUA_E_OK:
4302 return 1;
4303
4304 /* yield. */
4305 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004306 /* Set timeout in the required channel. */
4307 if (s->hlua.wake_time != TICK_ETERNITY) {
4308 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004309 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004310 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004311 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004312 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004313 /* Some actions can be wake up when a "write" event
4314 * is detected on a response channel. This is useful
4315 * only for actions targetted on the requests.
4316 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004317 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004318 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01004319 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004320 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004321 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004322 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004323 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004324 return 0;
4325
4326 /* finished with error. */
4327 case HLUA_E_ERRMSG:
4328 /* Display log. */
4329 send_log(px, LOG_ERR, "Lua function '%s': %s.", rule->fcn.name, lua_tostring(s->hlua.T, -1));
4330 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4331 Alert("Lua function '%s': %s.\n", rule->fcn.name, lua_tostring(s->hlua.T, -1));
4332 lua_pop(s->hlua.T, 1);
4333 return 1;
4334
4335 case HLUA_E_ERR:
4336 /* Display log. */
4337 send_log(px, LOG_ERR, "Lua function '%s' return an unknown error.", rule->fcn.name);
4338 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4339 Alert("Lua function '%s' return an unknown error.\n", rule->fcn.name);
4340
4341 default:
4342 return 1;
4343 }
4344}
4345
4346/* Lua execution wrapper for "tcp-request". This function uses
4347 * "hlua_request_act_wrapper" for executing the LUA code.
4348 */
4349int hlua_tcp_req_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
Willy Tarreau87b09662015-04-03 00:22:06 +02004350 struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004351{
4352 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004353 px, s, AN_REQ_INSPECT_FE);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004354}
4355
4356/* Lua execution wrapper for "tcp-response". This function uses
4357 * "hlua_request_act_wrapper" for executing the LUA code.
4358 */
4359int hlua_tcp_res_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
Willy Tarreau87b09662015-04-03 00:22:06 +02004360 struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004361{
4362 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004363 px, s, AN_RES_INSPECT);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004364}
4365
4366/* Lua execution wrapper for http-request.
4367 * This function uses "hlua_request_act_wrapper" for executing
4368 * the LUA code.
4369 */
4370int hlua_http_req_act_wrapper(struct http_req_rule *rule, struct proxy *px,
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004371 struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004372{
4373 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004374 s, AN_REQ_HTTP_PROCESS_FE);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004375}
4376
4377/* Lua execution wrapper for http-response.
4378 * This function uses "hlua_request_act_wrapper" for executing
4379 * the LUA code.
4380 */
4381int hlua_http_res_act_wrapper(struct http_res_rule *rule, struct proxy *px,
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004382 struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004383{
4384 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004385 s, AN_RES_HTTP_PROCESS_BE);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004386}
4387
4388/* tcp-request <*> configuration wrapper. */
4389static int tcp_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4390 struct tcp_rule *rule, char **err)
4391{
4392 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004393 return 0;
Thierry FOURNIER79318d72015-05-29 17:31:12 +02004394 rule->action = TCP_ACT_CUSTOM_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004395 rule->action_ptr = hlua_tcp_req_act_wrapper;
4396 return 1;
4397}
4398
4399/* tcp-response <*> configuration wrapper. */
4400static int tcp_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4401 struct tcp_rule *rule, char **err)
4402{
4403 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004404 return 0;
Thierry FOURNIER79318d72015-05-29 17:31:12 +02004405 rule->action = TCP_ACT_CUSTOM_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004406 rule->action_ptr = hlua_tcp_res_act_wrapper;
4407 return 1;
4408}
4409
4410/* http-request <*> configuration wrapper. */
4411static int http_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4412 struct http_req_rule *rule, char **err)
4413{
4414 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
4415 return -1;
4416 rule->action = HTTP_REQ_ACT_CUSTOM_CONT;
4417 rule->action_ptr = hlua_http_req_act_wrapper;
4418 return 1;
4419}
4420
4421/* http-response <*> configuration wrapper. */
4422static int http_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4423 struct http_res_rule *rule, char **err)
4424{
4425 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
4426 return -1;
4427 rule->action = HTTP_RES_ACT_CUSTOM_CONT;
4428 rule->action_ptr = hlua_http_res_act_wrapper;
4429 return 1;
4430}
4431
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004432static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
4433 struct proxy *defpx, const char *file, int line,
4434 char **err, unsigned int *timeout)
4435{
4436 const char *error;
4437
4438 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
4439 if (error && *error != '\0') {
4440 memprintf(err, "%s: invalid timeout", args[0]);
4441 return -1;
4442 }
4443 return 0;
4444}
4445
4446static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
4447 struct proxy *defpx, const char *file, int line,
4448 char **err)
4449{
4450 return hlua_read_timeout(args, section_type, curpx, defpx,
4451 file, line, err, &hlua_timeout_session);
4452}
4453
4454static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
4455 struct proxy *defpx, const char *file, int line,
4456 char **err)
4457{
4458 return hlua_read_timeout(args, section_type, curpx, defpx,
4459 file, line, err, &hlua_timeout_task);
4460}
4461
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004462static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
4463 struct proxy *defpx, const char *file, int line,
4464 char **err)
4465{
4466 char *error;
4467
4468 hlua_nb_instruction = strtoll(args[1], &error, 10);
4469 if (*error != '\0') {
4470 memprintf(err, "%s: invalid number", args[0]);
4471 return -1;
4472 }
4473 return 0;
4474}
4475
Willy Tarreau32f61e22015-03-18 17:54:59 +01004476static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
4477 struct proxy *defpx, const char *file, int line,
4478 char **err)
4479{
4480 char *error;
4481
4482 if (*(args[1]) == 0) {
4483 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
4484 return -1;
4485 }
4486 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
4487 if (*error != '\0') {
4488 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
4489 return -1;
4490 }
4491 return 0;
4492}
4493
4494
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004495/* This function is called by the main configuration key "lua-load". It loads and
4496 * execute an lua file during the parsing of the HAProxy configuration file. It is
4497 * the main lua entry point.
4498 *
4499 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
4500 * occured, otherwise it returns 0.
4501 *
4502 * In some error case, LUA set an error message in top of the stack. This function
4503 * returns this error message in the HAProxy logs and pop it from the stack.
4504 */
4505static int hlua_load(char **args, int section_type, struct proxy *curpx,
4506 struct proxy *defpx, const char *file, int line,
4507 char **err)
4508{
4509 int error;
4510
4511 /* Just load and compile the file. */
4512 error = luaL_loadfile(gL.T, args[1]);
4513 if (error) {
4514 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
4515 lua_pop(gL.T, 1);
4516 return -1;
4517 }
4518
4519 /* If no syntax error where detected, execute the code. */
4520 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
4521 switch (error) {
4522 case LUA_OK:
4523 break;
4524 case LUA_ERRRUN:
4525 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
4526 lua_pop(gL.T, 1);
4527 return -1;
4528 case LUA_ERRMEM:
4529 memprintf(err, "lua out of memory error\n");
4530 return -1;
4531 case LUA_ERRERR:
4532 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
4533 lua_pop(gL.T, 1);
4534 return -1;
4535 case LUA_ERRGCMM:
4536 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
4537 lua_pop(gL.T, 1);
4538 return -1;
4539 default:
4540 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
4541 lua_pop(gL.T, 1);
4542 return -1;
4543 }
4544
4545 return 0;
4546}
4547
4548/* configuration keywords declaration */
4549static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004550 { CFG_GLOBAL, "lua-load", hlua_load },
4551 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
4552 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004553 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01004554 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004555 { 0, NULL, NULL },
4556}};
4557
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004558static struct http_req_action_kw_list http_req_kws = {"lua", { }, {
4559 { "lua", http_req_action_register_lua },
4560 { NULL, NULL }
4561}};
4562
4563static struct http_res_action_kw_list http_res_kws = {"lua", { }, {
4564 { "lua", http_res_action_register_lua },
4565 { NULL, NULL }
4566}};
4567
4568static struct tcp_action_kw_list tcp_req_cont_kws = {"lua", { }, {
4569 { "lua", tcp_req_action_register_lua },
4570 { NULL, NULL }
4571}};
4572
4573static struct tcp_action_kw_list tcp_res_cont_kws = {"lua", { }, {
4574 { "lua", tcp_res_action_register_lua },
4575 { NULL, NULL }
4576}};
4577
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004578int hlua_post_init()
4579{
4580 struct hlua_init_function *init;
4581 const char *msg;
4582 enum hlua_exec ret;
4583
4584 list_for_each_entry(init, &hlua_init_functions, l) {
4585 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
4586 ret = hlua_ctx_resume(&gL, 0);
4587 switch (ret) {
4588 case HLUA_E_OK:
4589 lua_pop(gL.T, -1);
4590 return 1;
4591 case HLUA_E_AGAIN:
4592 Alert("lua init: yield not allowed.\n");
4593 return 0;
4594 case HLUA_E_ERRMSG:
4595 msg = lua_tostring(gL.T, -1);
4596 Alert("lua init: %s.\n", msg);
4597 return 0;
4598 case HLUA_E_ERR:
4599 default:
4600 Alert("lua init: unknown runtime error.\n");
4601 return 0;
4602 }
4603 }
4604 return 1;
4605}
4606
Willy Tarreau32f61e22015-03-18 17:54:59 +01004607/* The memory allocator used by the Lua stack. <ud> is a pointer to the
4608 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
4609 * is the previously allocated size or the kind of object in case of a new
4610 * allocation. <nsize> is the requested new size.
4611 */
4612static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
4613{
4614 struct hlua_mem_allocator *zone = ud;
4615
4616 if (nsize == 0) {
4617 /* it's a free */
4618 if (ptr)
4619 zone->allocated -= osize;
4620 free(ptr);
4621 return NULL;
4622 }
4623
4624 if (!ptr) {
4625 /* it's a new allocation */
4626 if (zone->limit && zone->allocated + nsize > zone->limit)
4627 return NULL;
4628
4629 ptr = malloc(nsize);
4630 if (ptr)
4631 zone->allocated += nsize;
4632 return ptr;
4633 }
4634
4635 /* it's a realloc */
4636 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
4637 return NULL;
4638
4639 ptr = realloc(ptr, nsize);
4640 if (ptr)
4641 zone->allocated += nsize - osize;
4642 return ptr;
4643}
4644
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01004645void hlua_init(void)
4646{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004647 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004648 int idx;
4649 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004650 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004651 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004652#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004653 struct srv_kw *kw;
4654 int tmp_error;
4655 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01004656 char *args[] = { /* SSL client configuration. */
4657 "ssl",
4658 "verify",
4659 "none",
4660 "force-sslv3",
4661 NULL
4662 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004663#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004664
Willy Tarreau87b09662015-04-03 00:22:06 +02004665 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004666 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
4667
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004668 /* Register configuration keywords. */
4669 cfg_register_keywords(&cfg_kws);
4670
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004671 /* Register custom HTTP rules. */
4672 http_req_keywords_register(&http_req_kws);
4673 http_res_keywords_register(&http_res_kws);
4674 tcp_req_cont_keywords_register(&tcp_req_cont_kws);
4675 tcp_res_cont_keywords_register(&tcp_res_cont_kws);
4676
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004677 /* Init main lua stack. */
4678 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004679 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004680 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004681 gL.T = luaL_newstate();
4682 hlua_sethlua(&gL);
4683 gL.Tref = LUA_REFNIL;
4684 gL.task = NULL;
4685
Willy Tarreau32f61e22015-03-18 17:54:59 +01004686 /* change the memory allocators to track memory usage */
4687 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
4688
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004689 /* Initialise lua. */
4690 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004691
4692 /*
4693 *
4694 * Create "core" object.
4695 *
4696 */
4697
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01004698 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004699 lua_newtable(gL.T);
4700
4701 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004702 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004703 hlua_class_const_int(gL.T, log_levels[i], i);
4704
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004705 /* Register special functions. */
4706 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004707 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004708 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004709 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004710 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01004711 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004712 hlua_class_function(gL.T, "sleep", hlua_sleep);
4713 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01004714 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
4715 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
4716 hlua_class_function(gL.T, "set_map", hlua_set_map);
4717 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004718 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004719 hlua_class_function(gL.T, "log", hlua_log);
4720 hlua_class_function(gL.T, "Debug", hlua_log_debug);
4721 hlua_class_function(gL.T, "Info", hlua_log_info);
4722 hlua_class_function(gL.T, "Warning", hlua_log_warning);
4723 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004724
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004725 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004726
4727 /*
4728 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02004729 * Register class Map
4730 *
4731 */
4732
4733 /* This table entry is the object "Map" base. */
4734 lua_newtable(gL.T);
4735
4736 /* register pattern types. */
4737 for (i=0; i<PAT_MATCH_NUM; i++)
4738 hlua_class_const_int(gL.T, pat_match_names[i], i);
4739
4740 /* register constructor. */
4741 hlua_class_function(gL.T, "new", hlua_map_new);
4742
4743 /* Create and fill the metatable. */
4744 lua_newtable(gL.T);
4745
4746 /* Create and fille the __index entry. */
4747 lua_pushstring(gL.T, "__index");
4748 lua_newtable(gL.T);
4749
4750 /* Register . */
4751 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
4752 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
4753
4754 lua_settable(gL.T, -3);
4755
4756 /* Register previous table in the registry with reference and named entry. */
4757 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4758 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4759 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_MAP); /* register class session. */
4760 class_map_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4761
4762 /* Assign the metatable to the mai Map object. */
4763 lua_setmetatable(gL.T, -2);
4764
4765 /* Set a name to the table. */
4766 lua_setglobal(gL.T, "Map");
4767
4768 /*
4769 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004770 * Register class Channel
4771 *
4772 */
4773
4774 /* Create and fill the metatable. */
4775 lua_newtable(gL.T);
4776
4777 /* Create and fille the __index entry. */
4778 lua_pushstring(gL.T, "__index");
4779 lua_newtable(gL.T);
4780
4781 /* Register . */
4782 hlua_class_function(gL.T, "get", hlua_channel_get);
4783 hlua_class_function(gL.T, "dup", hlua_channel_dup);
4784 hlua_class_function(gL.T, "getline", hlua_channel_getline);
4785 hlua_class_function(gL.T, "set", hlua_channel_set);
4786 hlua_class_function(gL.T, "append", hlua_channel_append);
4787 hlua_class_function(gL.T, "send", hlua_channel_send);
4788 hlua_class_function(gL.T, "forward", hlua_channel_forward);
4789 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
4790 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
4791
4792 lua_settable(gL.T, -3);
4793
4794 /* Register previous table in the registry with reference and named entry. */
4795 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4796 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
4797 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4798
4799 /*
4800 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004801 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004802 *
4803 */
4804
4805 /* Create and fill the metatable. */
4806 lua_newtable(gL.T);
4807
4808 /* Create and fille the __index entry. */
4809 lua_pushstring(gL.T, "__index");
4810 lua_newtable(gL.T);
4811
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004812 /* Browse existing fetches and create the associated
4813 * object method.
4814 */
4815 sf = NULL;
4816 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
4817
4818 /* Dont register the keywork if the arguments check function are
4819 * not safe during the runtime.
4820 */
4821 if ((sf->val_args != NULL) &&
4822 (sf->val_args != val_payload_lv) &&
4823 (sf->val_args != val_hdr))
4824 continue;
4825
4826 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4827 * by an underscore.
4828 */
4829 strncpy(trash.str, sf->kw, trash.size);
4830 trash.str[trash.size - 1] = '\0';
4831 for (p = trash.str; *p; p++)
4832 if (*p == '.' || *p == '-' || *p == '+')
4833 *p = '_';
4834
4835 /* Register the function. */
4836 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01004837 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004838 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
4839 lua_settable(gL.T, -3);
4840 }
4841
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004842 lua_settable(gL.T, -3);
4843
4844 /* Register previous table in the registry with reference and named entry. */
4845 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4846 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
4847 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4848
4849 /*
4850 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004851 * Register class Converters
4852 *
4853 */
4854
4855 /* Create and fill the metatable. */
4856 lua_newtable(gL.T);
4857
4858 /* Create and fill the __index entry. */
4859 lua_pushstring(gL.T, "__index");
4860 lua_newtable(gL.T);
4861
4862 /* Browse existing converters and create the associated
4863 * object method.
4864 */
4865 sc = NULL;
4866 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
4867 /* Dont register the keywork if the arguments check function are
4868 * not safe during the runtime.
4869 */
4870 if (sc->val_args != NULL)
4871 continue;
4872
4873 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4874 * by an underscore.
4875 */
4876 strncpy(trash.str, sc->kw, trash.size);
4877 trash.str[trash.size - 1] = '\0';
4878 for (p = trash.str; *p; p++)
4879 if (*p == '.' || *p == '-' || *p == '+')
4880 *p = '_';
4881
4882 /* Register the function. */
4883 lua_pushstring(gL.T, trash.str);
4884 lua_pushlightuserdata(gL.T, sc);
4885 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
4886 lua_settable(gL.T, -3);
4887 }
4888
4889 lua_settable(gL.T, -3);
4890
4891 /* Register previous table in the registry with reference and named entry. */
4892 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4893 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
4894 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4895
4896 /*
4897 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004898 * Register class HTTP
4899 *
4900 */
4901
4902 /* Create and fill the metatable. */
4903 lua_newtable(gL.T);
4904
4905 /* Create and fille the __index entry. */
4906 lua_pushstring(gL.T, "__index");
4907 lua_newtable(gL.T);
4908
4909 /* Register Lua functions. */
4910 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
4911 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
4912 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
4913 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
4914 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
4915 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
4916 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
4917 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
4918 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
4919 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
4920
4921 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
4922 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
4923 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
4924 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
4925 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
4926 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
4927
4928 lua_settable(gL.T, -3);
4929
4930 /* Register previous table in the registry with reference and named entry. */
4931 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4932 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_HTTP); /* register class session. */
4933 class_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4934
4935 /*
4936 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004937 * Register class TXN
4938 *
4939 */
4940
4941 /* Create and fill the metatable. */
4942 lua_newtable(gL.T);
4943
4944 /* Create and fille the __index entry. */
4945 lua_pushstring(gL.T, "__index");
4946 lua_newtable(gL.T);
4947
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004948 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01004949 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
4950 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004951 hlua_class_function(gL.T, "close", hlua_txn_close);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004952 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
4953 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
4954 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004955 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
4956 hlua_class_function(gL.T, "log", hlua_txn_log);
4957 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
4958 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
4959 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
4960 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004961
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004962 lua_settable(gL.T, -3);
4963
4964 /* Register previous table in the registry with reference and named entry. */
4965 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4966 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
4967 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004968
4969 /*
4970 *
4971 * Register class Socket
4972 *
4973 */
4974
4975 /* Create and fill the metatable. */
4976 lua_newtable(gL.T);
4977
4978 /* Create and fille the __index entry. */
4979 lua_pushstring(gL.T, "__index");
4980 lua_newtable(gL.T);
4981
Baptiste Assmann84bb4932015-03-02 21:40:06 +01004982#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004983 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01004984#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004985 hlua_class_function(gL.T, "connect", hlua_socket_connect);
4986 hlua_class_function(gL.T, "send", hlua_socket_send);
4987 hlua_class_function(gL.T, "receive", hlua_socket_receive);
4988 hlua_class_function(gL.T, "close", hlua_socket_close);
4989 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
4990 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
4991 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
4992 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
4993
4994 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
4995
4996 /* Register the garbage collector entry. */
4997 lua_pushstring(gL.T, "__gc");
4998 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
4999 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
5000
5001 /* Register previous table in the registry with reference and named entry. */
5002 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5003 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5004 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
5005 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
5006
5007 /* Proxy and server configuration initialisation. */
5008 memset(&socket_proxy, 0, sizeof(socket_proxy));
5009 init_new_proxy(&socket_proxy);
5010 socket_proxy.parent = NULL;
5011 socket_proxy.last_change = now.tv_sec;
5012 socket_proxy.id = "LUA-SOCKET";
5013 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
5014 socket_proxy.maxconn = 0;
5015 socket_proxy.accept = NULL;
5016 socket_proxy.options2 |= PR_O2_INDEPSTR;
5017 socket_proxy.srv = NULL;
5018 socket_proxy.conn_retries = 0;
5019 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
5020
5021 /* Init TCP server: unchanged parameters */
5022 memset(&socket_tcp, 0, sizeof(socket_tcp));
5023 socket_tcp.next = NULL;
5024 socket_tcp.proxy = &socket_proxy;
5025 socket_tcp.obj_type = OBJ_TYPE_SERVER;
5026 LIST_INIT(&socket_tcp.actconns);
5027 LIST_INIT(&socket_tcp.pendconns);
5028 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
5029 socket_tcp.last_change = 0;
5030 socket_tcp.id = "LUA-TCP-CONN";
5031 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5032 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5033 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
5034
5035 /* XXX: Copy default parameter from default server,
5036 * but the default server is not initialized.
5037 */
5038 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
5039 socket_tcp.minconn = socket_proxy.defsrv.minconn;
5040 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
5041 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
5042 socket_tcp.onerror = socket_proxy.defsrv.onerror;
5043 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5044 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
5045 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5046 socket_tcp.uweight = socket_proxy.defsrv.iweight;
5047 socket_tcp.iweight = socket_proxy.defsrv.iweight;
5048
5049 socket_tcp.check.status = HCHK_STATUS_INI;
5050 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
5051 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
5052 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
5053 socket_tcp.check.server = &socket_tcp;
5054
5055 socket_tcp.agent.status = HCHK_STATUS_INI;
5056 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
5057 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
5058 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
5059 socket_tcp.agent.server = &socket_tcp;
5060
5061 socket_tcp.xprt = &raw_sock;
5062
5063#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005064 /* Init TCP server: unchanged parameters */
5065 memset(&socket_ssl, 0, sizeof(socket_ssl));
5066 socket_ssl.next = NULL;
5067 socket_ssl.proxy = &socket_proxy;
5068 socket_ssl.obj_type = OBJ_TYPE_SERVER;
5069 LIST_INIT(&socket_ssl.actconns);
5070 LIST_INIT(&socket_ssl.pendconns);
5071 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
5072 socket_ssl.last_change = 0;
5073 socket_ssl.id = "LUA-SSL-CONN";
5074 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5075 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5076 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
5077
5078 /* XXX: Copy default parameter from default server,
5079 * but the default server is not initialized.
5080 */
5081 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
5082 socket_ssl.minconn = socket_proxy.defsrv.minconn;
5083 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
5084 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
5085 socket_ssl.onerror = socket_proxy.defsrv.onerror;
5086 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5087 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
5088 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5089 socket_ssl.uweight = socket_proxy.defsrv.iweight;
5090 socket_ssl.iweight = socket_proxy.defsrv.iweight;
5091
5092 socket_ssl.check.status = HCHK_STATUS_INI;
5093 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
5094 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
5095 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
5096 socket_ssl.check.server = &socket_ssl;
5097
5098 socket_ssl.agent.status = HCHK_STATUS_INI;
5099 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
5100 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
5101 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
5102 socket_ssl.agent.server = &socket_ssl;
5103
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005104 socket_ssl.use_ssl = 1;
5105 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005106
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005107 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005108 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
5109 /*
5110 *
5111 * If the keyword is not known, we can search in the registered
5112 * server keywords. This is usefull to configure special SSL
5113 * features like client certificates and ssl_verify.
5114 *
5115 */
5116 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
5117 if (tmp_error != 0) {
5118 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
5119 abort(); /* This must be never arrives because the command line
5120 not editable by the user. */
5121 }
5122 idx += kw->skip;
5123 }
5124 }
5125
5126 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005127 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005128#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01005129}