blob: 966ed5adb6980ae2489977bab1d81f29f824ee7f [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>
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01006#include <lauxlib.h>
7#include <lua.h>
8#include <lualib.h>
9
Thierry FOURNIER463119c2015-03-10 00:35:36 +010010#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
11#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010012#endif
13
Thierry FOURNIER380d0932015-01-23 14:27:52 +010014#include <ebpttree.h>
15
16#include <common/cfgparse.h>
17
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010018#include <types/connection.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010019#include <types/hlua.h>
20#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>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020041#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010042
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010043/* Lua uses longjmp to perform yield or throwing errors. This
44 * macro is used only for identifying the function that can
45 * not return because a longjmp is executed.
46 * __LJMP marks a prototype of hlua file that can use longjmp.
47 * WILL_LJMP() marks an lua function that will use longjmp.
48 * MAY_LJMP() marks an lua function that may use longjmp.
49 */
50#define __LJMP
51#define WILL_LJMP(func) func
52#define MAY_LJMP(func) func
53
Thierry FOURNIERbabae282015-09-17 11:36:37 +020054/* This couple of function executes securely some Lua calls outside of
55 * the lua runtime environment. Each Lua call can return a longjmp
56 * if it encounter a memory error.
57 *
58 * Lua documentation extract:
59 *
60 * If an error happens outside any protected environment, Lua calls
61 * a panic function (see lua_atpanic) and then calls abort, thus
62 * exiting the host application. Your panic function can avoid this
63 * exit by never returning (e.g., doing a long jump to your own
64 * recovery point outside Lua).
65 *
66 * The panic function runs as if it were a message handler (see
67 * §2.3); in particular, the error message is at the top of the
68 * stack. However, there is no guarantee about stack space. To push
69 * anything on the stack, the panic function must first check the
70 * available space (see §4.2).
71 *
72 * We must check all the Lua entry point. This includes:
73 * - The include/proto/hlua.h exported functions
74 * - the task wrapper function
75 * - The action wrapper function
76 * - The converters wrapper function
77 * - The sample-fetch wrapper functions
78 *
79 * It is tolerated that the initilisation function returns an abort.
80 * Before each Lua abort, an error message is writed on stderr.
81 *
82 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
83 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
84 * because they must be exists in the program stack when the longjmp
85 * is called.
86 */
87jmp_buf safe_ljmp_env;
88static int hlua_panic_safe(lua_State *L) { return 0; }
89static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
90
91#define SET_SAFE_LJMP(__L) \
92 ({ \
93 int ret; \
94 if (setjmp(safe_ljmp_env) != 0) { \
95 lua_atpanic(__L, hlua_panic_safe); \
96 ret = 0; \
97 } else { \
98 lua_atpanic(__L, hlua_panic_ljmp); \
99 ret = 1; \
100 } \
101 ret; \
102 })
103
104/* If we are the last function catching Lua errors, we
105 * must reset the panic function.
106 */
107#define RESET_SAFE_LJMP(__L) \
108 do { \
109 lua_atpanic(__L, hlua_panic_safe); \
110 } while(0)
111
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100112/* The main Lua execution context. */
113struct hlua gL;
114
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100115/* This is the memory pool containing all the signal structs. These
116 * struct are used to store each requiered signal between two tasks.
117 */
118struct pool_head *pool2_hlua_com;
119
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100120/* Used for Socket connection. */
121static struct proxy socket_proxy;
122static struct server socket_tcp;
123#ifdef USE_OPENSSL
124static struct server socket_ssl;
125#endif
126
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100127/* List head of the function called at the initialisation time. */
128struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
129
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100130/* The following variables contains the reference of the different
131 * Lua classes. These references are useful for identify metadata
132 * associated with an object.
133 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100134static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100135static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100136static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100137static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100138static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100139static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200140static int class_map_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100141
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100142/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200143 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100144 * short timeout. Lua linked with tasks doesn't have a timeout
145 * because a task may remain alive during all the haproxy execution.
146 */
147static unsigned int hlua_timeout_session = 4000; /* session timeout. */
148static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
149
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100150/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
151 * it is used for preventing infinite loops.
152 *
153 * I test the scheer with an infinite loop containing one incrementation
154 * and one test. I run this loop between 10 seconds, I raise a ceil of
155 * 710M loops from one interrupt each 9000 instructions, so I fix the value
156 * to one interrupt each 10 000 instructions.
157 *
158 * configured | Number of
159 * instructions | loops executed
160 * between two | in milions
161 * forced yields |
162 * ---------------+---------------
163 * 10 | 160
164 * 500 | 670
165 * 1000 | 680
166 * 5000 | 700
167 * 7000 | 700
168 * 8000 | 700
169 * 9000 | 710 <- ceil
170 * 10000 | 710
171 * 100000 | 710
172 * 1000000 | 710
173 *
174 */
175static unsigned int hlua_nb_instruction = 10000;
176
Willy Tarreau32f61e22015-03-18 17:54:59 +0100177/* Descriptor for the memory allocation state. If limit is not null, it will
178 * be enforced on any memory allocation.
179 */
180struct hlua_mem_allocator {
181 size_t allocated;
182 size_t limit;
183};
184
185static struct hlua_mem_allocator hlua_global_allocator;
186
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100187/* These functions converts types between HAProxy internal args or
188 * sample and LUA types. Another function permits to check if the
189 * LUA stack contains arguments according with an required ARG_T
190 * format.
191 */
192static int hlua_arg2lua(lua_State *L, const struct arg *arg);
193static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100194__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
195 unsigned int mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100196static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100197static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100198static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
199
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200200#define SEND_ERR(__be, __fmt, __args...) \
201 do { \
202 send_log(__be, LOG_ERR, __fmt, ## __args); \
203 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
204 Alert(__fmt, ## __args); \
205 } while (0)
206
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100207/* Used to check an Lua function type in the stack. It creates and
208 * returns a reference of the function. This function throws an
209 * error if the rgument is not a "function".
210 */
211__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
212{
213 if (!lua_isfunction(L, argno)) {
214 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
215 WILL_LJMP(luaL_argerror(L, argno, msg));
216 }
217 lua_pushvalue(L, argno);
218 return luaL_ref(L, LUA_REGISTRYINDEX);
219}
220
221/* The three following functions are useful for adding entries
222 * in a table. These functions takes a string and respectively an
223 * integer, a string or a function and add it to the table in the
224 * top of the stack.
225 *
226 * These functions throws an error if no more stack size is
227 * available.
228 */
229__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100230 int value)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100231{
232 if (!lua_checkstack(L, 2))
233 WILL_LJMP(luaL_error(L, "full stack"));
234 lua_pushstring(L, name);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100235 lua_pushinteger(L, value);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100236 lua_settable(L, -3);
237}
238__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
239 const char *value)
240{
241 if (!lua_checkstack(L, 2))
242 WILL_LJMP(luaL_error(L, "full stack"));
243 lua_pushstring(L, name);
244 lua_pushstring(L, value);
245 lua_settable(L, -3);
246}
247__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
248 int (*function)(lua_State *L))
249{
250 if (!lua_checkstack(L, 2))
251 WILL_LJMP(luaL_error(L, "full stack"));
252 lua_pushstring(L, name);
253 lua_pushcclosure(L, function, 0);
254 lua_settable(L, -3);
255}
256
257/* This function check the number of arguments available in the
258 * stack. If the number of arguments available is not the same
259 * then <nb> an error is throwed.
260 */
261__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
262{
263 if (lua_gettop(L) == nb)
264 return;
265 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
266}
267
268/* Return true if the data in stack[<ud>] is an object of
269 * type <class_ref>.
270 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100271static int hlua_metaistype(lua_State *L, int ud, int class_ref)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100272{
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100273 if (!lua_getmetatable(L, ud))
274 return 0;
275
276 lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
277 if (!lua_rawequal(L, -1, -2)) {
278 lua_pop(L, 2);
279 return 0;
280 }
281
282 lua_pop(L, 2);
283 return 1;
284}
285
286/* Return an object of the expected type, or throws an error. */
287__LJMP static void *hlua_checkudata(lua_State *L, int ud, int class_ref)
288{
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100289 void *p;
290
291 /* Check if the stack entry is an array. */
292 if (!lua_istable(L, ud))
293 WILL_LJMP(luaL_argerror(L, ud, NULL));
294 /* Check if the metadata have the expected type. */
295 if (!hlua_metaistype(L, ud, class_ref))
296 WILL_LJMP(luaL_argerror(L, ud, NULL));
297 /* Push on the stack at the entry [0] of the table. */
298 lua_rawgeti(L, ud, 0);
299 /* Check if this entry is userdata. */
300 p = lua_touserdata(L, -1);
301 if (!p)
302 WILL_LJMP(luaL_argerror(L, ud, NULL));
303 /* Remove the entry returned by lua_rawgeti(). */
304 lua_pop(L, 1);
305 /* Return the associated struct. */
306 return p;
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100307}
308
309/* This fucntion push an error string prefixed by the file name
310 * and the line number where the error is encountered.
311 */
312static int hlua_pusherror(lua_State *L, const char *fmt, ...)
313{
314 va_list argp;
315 va_start(argp, fmt);
316 luaL_where(L, 1);
317 lua_pushvfstring(L, fmt, argp);
318 va_end(argp);
319 lua_concat(L, 2);
320 return 1;
321}
322
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100323/* This function register a new signal. "lua" is the current lua
324 * execution context. It contains a pointer to the associated task.
325 * "link" is a list head attached to an other task that must be wake
326 * the lua task if an event occurs. This is useful with external
327 * events like TCP I/O or sleep functions. This funcion allocate
328 * memory for the signal.
329 */
330static int hlua_com_new(struct hlua *lua, struct list *link)
331{
332 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
333 if (!com)
334 return 0;
335 LIST_ADDQ(&lua->com, &com->purge_me);
336 LIST_ADDQ(link, &com->wake_me);
337 com->task = lua->task;
338 return 1;
339}
340
341/* This function purge all the pending signals when the LUA execution
342 * is finished. This prevent than a coprocess try to wake a deleted
343 * task. This function remove the memory associated to the signal.
344 */
345static void hlua_com_purge(struct hlua *lua)
346{
347 struct hlua_com *com, *back;
348
349 /* Delete all pending communication signals. */
350 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
351 LIST_DEL(&com->purge_me);
352 LIST_DEL(&com->wake_me);
353 pool_free2(pool2_hlua_com, com);
354 }
355}
356
357/* This function sends signals. It wakes all the tasks attached
358 * to a list head, and remove the signal, and free the used
359 * memory.
360 */
361static void hlua_com_wake(struct list *wake)
362{
363 struct hlua_com *com, *back;
364
365 /* Wake task and delete all pending communication signals. */
366 list_for_each_entry_safe(com, back, wake, wake_me) {
367 LIST_DEL(&com->purge_me);
368 LIST_DEL(&com->wake_me);
369 task_wakeup(com->task, TASK_WOKEN_MSG);
370 pool_free2(pool2_hlua_com, com);
371 }
372}
373
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100374/* This functions is used with sample fetch and converters. It
375 * converts the HAProxy configuration argument in a lua stack
376 * values.
377 *
378 * It takes an array of "arg", and each entry of the array is
379 * converted and pushed in the LUA stack.
380 */
381static int hlua_arg2lua(lua_State *L, const struct arg *arg)
382{
383 switch (arg->type) {
384 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100385 case ARGT_TIME:
386 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100387 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100388 break;
389
390 case ARGT_STR:
391 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
392 break;
393
394 case ARGT_IPV4:
395 case ARGT_IPV6:
396 case ARGT_MSK4:
397 case ARGT_MSK6:
398 case ARGT_FE:
399 case ARGT_BE:
400 case ARGT_TAB:
401 case ARGT_SRV:
402 case ARGT_USR:
403 case ARGT_MAP:
404 default:
405 lua_pushnil(L);
406 break;
407 }
408 return 1;
409}
410
411/* This function take one entrie in an LUA stack at the index "ud",
412 * and try to convert it in an HAProxy argument entry. This is useful
413 * with sample fetch wrappers. The input arguments are gived to the
414 * lua wrapper and converted as arg list by thi function.
415 */
416static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
417{
418 switch (lua_type(L, ud)) {
419
420 case LUA_TNUMBER:
421 case LUA_TBOOLEAN:
422 arg->type = ARGT_SINT;
423 arg->data.sint = lua_tointeger(L, ud);
424 break;
425
426 case LUA_TSTRING:
427 arg->type = ARGT_STR;
428 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
429 break;
430
431 case LUA_TUSERDATA:
432 case LUA_TNIL:
433 case LUA_TTABLE:
434 case LUA_TFUNCTION:
435 case LUA_TTHREAD:
436 case LUA_TLIGHTUSERDATA:
437 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200438 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100439 break;
440 }
441 return 1;
442}
443
444/* the following functions are used to convert a struct sample
445 * in Lua type. This useful to convert the return of the
446 * fetchs or converters.
447 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100448static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100449{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200450 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100451 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100452 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200453 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100454 break;
455
456 case SMP_T_BIN:
457 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200458 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100459 break;
460
461 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200462 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100463 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
464 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
465 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
466 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
467 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
468 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
469 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
470 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
471 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200472 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100473 break;
474 default:
475 lua_pushnil(L);
476 break;
477 }
478 break;
479
480 case SMP_T_IPV4:
481 case SMP_T_IPV6:
482 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200483 if (sample_casts[smp->data.type][SMP_T_STR] &&
484 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200485 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100486 else
487 lua_pushnil(L);
488 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100489 default:
490 lua_pushnil(L);
491 break;
492 }
493 return 1;
494}
495
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100496/* the following functions are used to convert a struct sample
497 * in Lua strings. This is useful to convert the return of the
498 * fetchs or converters.
499 */
500static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
501{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200502 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100503
504 case SMP_T_BIN:
505 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200506 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100507 break;
508
509 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200510 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100511 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
512 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
513 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
514 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
515 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
516 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
517 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
518 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
519 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200520 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100521 break;
522 default:
523 lua_pushstring(L, "");
524 break;
525 }
526 break;
527
528 case SMP_T_SINT:
529 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100530 case SMP_T_IPV4:
531 case SMP_T_IPV6:
532 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200533 if (sample_casts[smp->data.type][SMP_T_STR] &&
534 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200535 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100536 else
537 lua_pushstring(L, "");
538 break;
539 default:
540 lua_pushstring(L, "");
541 break;
542 }
543 return 1;
544}
545
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100546/* the following functions are used to convert an Lua type in a
547 * struct sample. This is useful to provide data from a converter
548 * to the LUA code.
549 */
550static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
551{
552 switch (lua_type(L, ud)) {
553
554 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200555 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200556 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100557 break;
558
559
560 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200561 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200562 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100563 break;
564
565 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200566 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100567 smp->flags |= SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200568 smp->data.u.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100569 break;
570
571 case LUA_TUSERDATA:
572 case LUA_TNIL:
573 case LUA_TTABLE:
574 case LUA_TFUNCTION:
575 case LUA_TTHREAD:
576 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200577 case LUA_TNONE:
578 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200579 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200580 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100581 break;
582 }
583 return 1;
584}
585
586/* This function check the "argp" builded by another conversion function
587 * is in accord with the expected argp defined by the "mask". The fucntion
588 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100589 *
590 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
591 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100592 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100593__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
594 unsigned int mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100595{
596 int min_arg;
597 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100598 struct proxy *px;
599 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100600
601 idx = 0;
602 min_arg = ARGM(mask);
603 mask >>= ARGM_BITS;
604
605 while (1) {
606
607 /* Check oversize. */
608 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100609 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100610 }
611
612 /* Check for mandatory arguments. */
613 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100614 if (idx < min_arg) {
615
616 /* If miss other argument than the first one, we return an error. */
617 if (idx > 0)
618 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
619
620 /* If first argument have a certain type, some default values
621 * may be used. See the function smp_resolve_args().
622 */
623 switch (mask & ARGT_MASK) {
624
625 case ARGT_FE:
626 if (!(p->cap & PR_CAP_FE))
627 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
628 argp[idx].data.prx = p;
629 argp[idx].type = ARGT_FE;
630 argp[idx+1].type = ARGT_STOP;
631 break;
632
633 case ARGT_BE:
634 if (!(p->cap & PR_CAP_BE))
635 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
636 argp[idx].data.prx = p;
637 argp[idx].type = ARGT_BE;
638 argp[idx+1].type = ARGT_STOP;
639 break;
640
641 case ARGT_TAB:
642 argp[idx].data.prx = p;
643 argp[idx].type = ARGT_TAB;
644 argp[idx+1].type = ARGT_STOP;
645 break;
646
647 default:
648 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
649 break;
650 }
651 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100652 return 0;
653 }
654
655 /* Check for exceed the number of requiered argument. */
656 if ((mask & ARGT_MASK) == ARGT_STOP &&
657 argp[idx].type != ARGT_STOP) {
658 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
659 }
660
661 if ((mask & ARGT_MASK) == ARGT_STOP &&
662 argp[idx].type == ARGT_STOP) {
663 return 0;
664 }
665
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100666 /* Convert some argument types. */
667 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100668 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100669 if (argp[idx].type != ARGT_SINT)
670 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
671 argp[idx].type = ARGT_SINT;
672 break;
673
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100674 case ARGT_TIME:
675 if (argp[idx].type != ARGT_SINT)
676 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200677 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100678 break;
679
680 case ARGT_SIZE:
681 if (argp[idx].type != ARGT_SINT)
682 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200683 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100684 break;
685
686 case ARGT_FE:
687 if (argp[idx].type != ARGT_STR)
688 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
689 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
690 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200691 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100692 if (!argp[idx].data.prx)
693 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
694 argp[idx].type = ARGT_FE;
695 break;
696
697 case ARGT_BE:
698 if (argp[idx].type != ARGT_STR)
699 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
700 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
701 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200702 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100703 if (!argp[idx].data.prx)
704 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
705 argp[idx].type = ARGT_BE;
706 break;
707
708 case ARGT_TAB:
709 if (argp[idx].type != ARGT_STR)
710 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
711 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
712 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200713 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100714 if (!argp[idx].data.prx)
715 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
716 argp[idx].type = ARGT_TAB;
717 break;
718
719 case ARGT_SRV:
720 if (argp[idx].type != ARGT_STR)
721 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
722 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
723 trash.str[argp[idx].data.str.len] = 0;
724 sname = strrchr(trash.str, '/');
725 if (sname) {
726 *sname++ = '\0';
727 pname = trash.str;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200728 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100729 if (!px)
730 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
731 }
732 else {
733 sname = trash.str;
734 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100735 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100736 argp[idx].data.srv = findserver(px, sname);
737 if (!argp[idx].data.srv)
738 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
739 argp[idx].type = ARGT_SRV;
740 break;
741
742 case ARGT_IPV4:
743 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
744 trash.str[argp[idx].data.str.len] = 0;
745 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
746 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
747 argp[idx].type = ARGT_IPV4;
748 break;
749
750 case ARGT_MSK4:
751 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
752 trash.str[argp[idx].data.str.len] = 0;
753 if (!str2mask(trash.str, &argp[idx].data.ipv4))
754 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
755 argp[idx].type = ARGT_MSK4;
756 break;
757
758 case ARGT_IPV6:
759 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
760 trash.str[argp[idx].data.str.len] = 0;
761 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
762 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
763 argp[idx].type = ARGT_IPV6;
764 break;
765
766 case ARGT_MSK6:
767 case ARGT_MAP:
768 case ARGT_REG:
769 case ARGT_USR:
770 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100771 break;
772 }
773
774 /* Check for type of argument. */
775 if ((mask & ARGT_MASK) != argp[idx].type) {
776 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
777 arg_type_names[(mask & ARGT_MASK)],
778 arg_type_names[argp[idx].type & ARGT_MASK]);
779 WILL_LJMP(luaL_argerror(L, first + idx, msg));
780 }
781
782 /* Next argument. */
783 mask >>= ARGT_BITS;
784 idx++;
785 }
786}
787
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100788/*
789 * The following functions are used to make correspondance between the the
790 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100791 *
792 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100793 * - hlua_sethlua : create the association between hlua context and lua_state.
794 */
795static inline struct hlua *hlua_gethlua(lua_State *L)
796{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100797 struct hlua **hlua = lua_getextraspace(L);
798 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100799}
800static inline void hlua_sethlua(struct hlua *hlua)
801{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100802 struct hlua **hlua_store = lua_getextraspace(hlua->T);
803 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100804}
805
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100806/* This function is used to send logs. It try to send on screen (stderr)
807 * and on the default syslog server.
808 */
809static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
810{
811 struct tm tm;
812 char *p;
813
814 /* Cleanup the log message. */
815 p = trash.str;
816 for (; *msg != '\0'; msg++, p++) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200817 if (p >= trash.str + trash.size - 1) {
818 /* Break the message if exceed the buffer size. */
819 *(p-4) = ' ';
820 *(p-3) = '.';
821 *(p-2) = '.';
822 *(p-1) = '.';
823 break;
824 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100825 if (isprint(*msg))
826 *p = *msg;
827 else
828 *p = '.';
829 }
830 *p = '\0';
831
Thierry FOURNIER5554e292015-09-09 11:21:37 +0200832 send_log(px, level, "%s\n", trash.str);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100833 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200834 get_localtime(date.tv_sec, &tm);
835 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100836 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
837 (int)getpid(), trash.str);
838 fflush(stderr);
839 }
840}
841
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100842/* This function just ensure that the yield will be always
843 * returned with a timeout and permit to set some flags
844 */
845__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100846 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100847{
848 struct hlua *hlua = hlua_gethlua(L);
849
850 /* Set the wake timeout. If timeout is required, we set
851 * the expiration time.
852 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100853 hlua->wake_time = tick_first(timeout, hlua->expire);
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100854
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100855 hlua->flags |= flags;
856
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100857 /* Process the yield. */
858 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
859}
860
Willy Tarreau87b09662015-04-03 00:22:06 +0200861/* This function initialises the Lua environment stored in the stream.
862 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100863 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200864 *
865 * This function is particular. it initialises a new Lua thread. If the
866 * initialisation fails (example: out of memory error), the lua function
867 * throws an error (longjmp).
868 *
869 * This function manipulates two Lua stack: the main and the thread. Only
870 * the main stack can fail. The thread is not manipulated. This function
871 * MUST NOT manipulate the created thread stack state, because is not
872 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100873 */
874int hlua_ctx_init(struct hlua *lua, struct task *task)
875{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200876 if (!SET_SAFE_LJMP(gL.T)) {
877 lua->Tref = LUA_REFNIL;
878 return 0;
879 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100880 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100881 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100882 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100883 lua->T = lua_newthread(gL.T);
884 if (!lua->T) {
885 lua->Tref = LUA_REFNIL;
886 return 0;
887 }
888 hlua_sethlua(lua);
889 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
890 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200891 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100892 return 1;
893}
894
Willy Tarreau87b09662015-04-03 00:22:06 +0200895/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100896 * is destroyed. The destroy also the memory context. The struct "lua"
897 * is not freed.
898 */
899void hlua_ctx_destroy(struct hlua *lua)
900{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100901 if (!lua->T)
902 return;
903
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100904 /* Purge all the pending signals. */
905 hlua_com_purge(lua);
906
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100907 /* The thread is garbage collected by Lua. */
908 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
909 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200910 lua->T = NULL;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100911}
912
913/* This function is used to restore the Lua context when a coroutine
914 * fails. This function copy the common memory between old coroutine
915 * and the new coroutine. The old coroutine is destroyed, and its
916 * replaced by the new coroutine.
917 * If the flag "keep_msg" is set, the last entry of the old is assumed
918 * as string error message and it is copied in the new stack.
919 */
920static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
921{
922 lua_State *T;
923 int new_ref;
924
925 /* Renew the main LUA stack doesn't have sense. */
926 if (lua == &gL)
927 return 0;
928
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100929 /* New Lua coroutine. */
930 T = lua_newthread(gL.T);
931 if (!T)
932 return 0;
933
934 /* Copy last error message. */
935 if (keep_msg)
936 lua_xmove(lua->T, T, 1);
937
938 /* Copy data between the coroutines. */
939 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
940 lua_xmove(lua->T, T, 1);
941 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
942
943 /* Destroy old data. */
944 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
945
946 /* The thread is garbage collected by Lua. */
947 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
948
949 /* Fill the struct with the new coroutine values. */
950 lua->Mref = new_ref;
951 lua->T = T;
952 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
953
954 /* Set context. */
955 hlua_sethlua(lua);
956
957 return 1;
958}
959
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100960void hlua_hook(lua_State *L, lua_Debug *ar)
961{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100962 struct hlua *hlua = hlua_gethlua(L);
963
964 /* Lua cannot yield when its returning from a function,
965 * so, we can fix the interrupt hook to 1 instruction,
966 * expecting that the function is finnished.
967 */
968 if (lua_gethookmask(L) & LUA_MASKRET) {
969 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
970 return;
971 }
972
973 /* restore the interrupt condition. */
974 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
975
976 /* If we interrupt the Lua processing in yieldable state, we yield.
977 * If the state is not yieldable, trying yield causes an error.
978 */
979 if (lua_isyieldable(L))
980 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
981
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +0100982 /* If we cannot yield, update the clock and check the timeout. */
983 tv_update_date(0, 1);
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100984 if (tick_is_expired(hlua->expire, now_ms)) {
985 lua_pushfstring(L, "execution timeout");
986 WILL_LJMP(lua_error(L));
987 }
988
989 /* Try to interrupt the process at the end of the current
990 * unyieldable function.
991 */
992 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100993}
994
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100995/* This function start or resumes the Lua stack execution. If the flag
996 * "yield_allowed" if no set and the LUA stack execution returns a yield
997 * The function return an error.
998 *
999 * The function can returns 4 values:
1000 * - HLUA_E_OK : The execution is terminated without any errors.
1001 * - HLUA_E_AGAIN : The execution must continue at the next associated
1002 * task wakeup.
1003 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
1004 * the top of the stack.
1005 * - HLUA_E_ERR : An error has occured without error message.
1006 *
1007 * If an error occured, the stack is renewed and it is ready to run new
1008 * LUA code.
1009 */
1010static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1011{
1012 int ret;
1013 const char *msg;
1014
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001015 HLUA_SET_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001016
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001017 /* If we want to resume the task, then check first the execution timeout.
1018 * if it is reached, we can interrupt the Lua processing.
1019 */
1020 if (tick_is_expired(lua->expire, now_ms))
1021 goto timeout_reached;
1022
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001023resume_execution:
1024
1025 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1026 * instructions. it is used for preventing infinite loops.
1027 */
1028 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1029
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001030 /* Remove all flags except the running flags. */
1031 lua->flags = HLUA_RUN;
1032
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001033 /* Call the function. */
1034 ret = lua_resume(lua->T, gL.T, lua->nargs);
1035 switch (ret) {
1036
1037 case LUA_OK:
1038 ret = HLUA_E_OK;
1039 break;
1040
1041 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001042 /* Check if the execution timeout is expired. It it is the case, we
1043 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001044 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001045 if (tick_is_expired(lua->expire, now_ms)) {
1046
1047timeout_reached:
1048
1049 lua_settop(lua->T, 0); /* Empty the stack. */
1050 if (!lua_checkstack(lua->T, 1)) {
1051 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001052 break;
1053 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001054 lua_pushfstring(lua->T, "execution timeout");
1055 ret = HLUA_E_ERRMSG;
1056 break;
1057 }
1058 /* Process the forced yield. if the general yield is not allowed or
1059 * if no task were associated this the current Lua execution
1060 * coroutine, we resume the execution. Else we want to return in the
1061 * scheduler and we want to be waked up again, to continue the
1062 * current Lua execution. So we schedule our own task.
1063 */
1064 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001065 if (!yield_allowed || !lua->task)
1066 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001067 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001068 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001069 if (!yield_allowed) {
1070 lua_settop(lua->T, 0); /* Empty the stack. */
1071 if (!lua_checkstack(lua->T, 1)) {
1072 ret = HLUA_E_ERR;
1073 break;
1074 }
1075 lua_pushfstring(lua->T, "yield not allowed");
1076 ret = HLUA_E_ERRMSG;
1077 break;
1078 }
1079 ret = HLUA_E_AGAIN;
1080 break;
1081
1082 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001083
1084 /* Special exit case. The traditionnal exit is returned as an error
1085 * because the errors ares the only one mean to return immediately
1086 * from and lua execution.
1087 */
1088 if (lua->flags & HLUA_EXIT) {
1089 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001090 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001091 break;
1092 }
1093
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001094 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001095 if (!lua_checkstack(lua->T, 1)) {
1096 ret = HLUA_E_ERR;
1097 break;
1098 }
1099 msg = lua_tostring(lua->T, -1);
1100 lua_settop(lua->T, 0); /* Empty the stack. */
1101 lua_pop(lua->T, 1);
1102 if (msg)
1103 lua_pushfstring(lua->T, "runtime error: %s", msg);
1104 else
1105 lua_pushfstring(lua->T, "unknown runtime error");
1106 ret = HLUA_E_ERRMSG;
1107 break;
1108
1109 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001110 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001111 lua_settop(lua->T, 0); /* Empty the stack. */
1112 if (!lua_checkstack(lua->T, 1)) {
1113 ret = HLUA_E_ERR;
1114 break;
1115 }
1116 lua_pushfstring(lua->T, "out of memory error");
1117 ret = HLUA_E_ERRMSG;
1118 break;
1119
1120 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001121 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001122 if (!lua_checkstack(lua->T, 1)) {
1123 ret = HLUA_E_ERR;
1124 break;
1125 }
1126 msg = lua_tostring(lua->T, -1);
1127 lua_settop(lua->T, 0); /* Empty the stack. */
1128 lua_pop(lua->T, 1);
1129 if (msg)
1130 lua_pushfstring(lua->T, "message handler error: %s", msg);
1131 else
1132 lua_pushfstring(lua->T, "message handler error");
1133 ret = HLUA_E_ERRMSG;
1134 break;
1135
1136 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001137 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001138 lua_settop(lua->T, 0); /* Empty the stack. */
1139 if (!lua_checkstack(lua->T, 1)) {
1140 ret = HLUA_E_ERR;
1141 break;
1142 }
1143 lua_pushfstring(lua->T, "unknonwn error");
1144 ret = HLUA_E_ERRMSG;
1145 break;
1146 }
1147
1148 switch (ret) {
1149 case HLUA_E_AGAIN:
1150 break;
1151
1152 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001153 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001154 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001155 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001156 break;
1157
1158 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001159 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001160 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001161 hlua_ctx_renew(lua, 0);
1162 break;
1163
1164 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001165 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001166 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001167 break;
1168 }
1169
1170 return ret;
1171}
1172
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001173/* This function exit the current code. */
1174__LJMP static int hlua_done(lua_State *L)
1175{
1176 struct hlua *hlua = hlua_gethlua(L);
1177
1178 hlua->flags |= HLUA_EXIT;
1179 WILL_LJMP(lua_error(L));
1180
1181 return 0;
1182}
1183
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001184/* This function is an LUA binding. It provides a function
1185 * for deleting ACL from a referenced ACL file.
1186 */
1187__LJMP static int hlua_del_acl(lua_State *L)
1188{
1189 const char *name;
1190 const char *key;
1191 struct pat_ref *ref;
1192
1193 MAY_LJMP(check_args(L, 2, "del_acl"));
1194
1195 name = MAY_LJMP(luaL_checkstring(L, 1));
1196 key = MAY_LJMP(luaL_checkstring(L, 2));
1197
1198 ref = pat_ref_lookup(name);
1199 if (!ref)
1200 WILL_LJMP(luaL_error(L, "'del_acl': unkown acl file '%s'", name));
1201
1202 pat_ref_delete(ref, key);
1203 return 0;
1204}
1205
1206/* This function is an LUA binding. It provides a function
1207 * for deleting map entry from a referenced map file.
1208 */
1209static int hlua_del_map(lua_State *L)
1210{
1211 const char *name;
1212 const char *key;
1213 struct pat_ref *ref;
1214
1215 MAY_LJMP(check_args(L, 2, "del_map"));
1216
1217 name = MAY_LJMP(luaL_checkstring(L, 1));
1218 key = MAY_LJMP(luaL_checkstring(L, 2));
1219
1220 ref = pat_ref_lookup(name);
1221 if (!ref)
1222 WILL_LJMP(luaL_error(L, "'del_map': unkown acl file '%s'", name));
1223
1224 pat_ref_delete(ref, key);
1225 return 0;
1226}
1227
1228/* This function is an LUA binding. It provides a function
1229 * for adding ACL pattern from a referenced ACL file.
1230 */
1231static int hlua_add_acl(lua_State *L)
1232{
1233 const char *name;
1234 const char *key;
1235 struct pat_ref *ref;
1236
1237 MAY_LJMP(check_args(L, 2, "add_acl"));
1238
1239 name = MAY_LJMP(luaL_checkstring(L, 1));
1240 key = MAY_LJMP(luaL_checkstring(L, 2));
1241
1242 ref = pat_ref_lookup(name);
1243 if (!ref)
1244 WILL_LJMP(luaL_error(L, "'add_acl': unkown acl file '%s'", name));
1245
1246 if (pat_ref_find_elt(ref, key) == NULL)
1247 pat_ref_add(ref, key, NULL, NULL);
1248 return 0;
1249}
1250
1251/* This function is an LUA binding. It provides a function
1252 * for setting map pattern and sample from a referenced map
1253 * file.
1254 */
1255static int hlua_set_map(lua_State *L)
1256{
1257 const char *name;
1258 const char *key;
1259 const char *value;
1260 struct pat_ref *ref;
1261
1262 MAY_LJMP(check_args(L, 3, "set_map"));
1263
1264 name = MAY_LJMP(luaL_checkstring(L, 1));
1265 key = MAY_LJMP(luaL_checkstring(L, 2));
1266 value = MAY_LJMP(luaL_checkstring(L, 3));
1267
1268 ref = pat_ref_lookup(name);
1269 if (!ref)
1270 WILL_LJMP(luaL_error(L, "'set_map': unkown map file '%s'", name));
1271
1272 if (pat_ref_find_elt(ref, key) != NULL)
1273 pat_ref_set(ref, key, value, NULL);
1274 else
1275 pat_ref_add(ref, key, value, NULL);
1276 return 0;
1277}
1278
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001279/* A class is a lot of memory that contain data. This data can be a table,
1280 * an integer or user data. This data is associated with a metatable. This
1281 * metatable have an original version registred in the global context with
1282 * the name of the object (_G[<name>] = <metable> ).
1283 *
1284 * A metable is a table that modify the standard behavior of a standard
1285 * access to the associated data. The entries of this new metatable are
1286 * defined as is:
1287 *
1288 * http://lua-users.org/wiki/MetatableEvents
1289 *
1290 * __index
1291 *
1292 * we access an absent field in a table, the result is nil. This is
1293 * true, but it is not the whole truth. Actually, such access triggers
1294 * the interpreter to look for an __index metamethod: If there is no
1295 * such method, as usually happens, then the access results in nil;
1296 * otherwise, the metamethod will provide the result.
1297 *
1298 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1299 * the key does not appear in the table, but the metatable has an __index
1300 * property:
1301 *
1302 * - if the value is a function, the function is called, passing in the
1303 * table and the key; the return value of that function is returned as
1304 * the result.
1305 *
1306 * - if the value is another table, the value of the key in that table is
1307 * asked for and returned (and if it doesn't exist in that table, but that
1308 * table's metatable has an __index property, then it continues on up)
1309 *
1310 * - Use "rawget(myTable,key)" to skip this metamethod.
1311 *
1312 * http://www.lua.org/pil/13.4.1.html
1313 *
1314 * __newindex
1315 *
1316 * Like __index, but control property assignment.
1317 *
1318 * __mode - Control weak references. A string value with one or both
1319 * of the characters 'k' and 'v' which specifies that the the
1320 * keys and/or values in the table are weak references.
1321 *
1322 * __call - Treat a table like a function. When a table is followed by
1323 * parenthesis such as "myTable( 'foo' )" and the metatable has
1324 * a __call key pointing to a function, that function is invoked
1325 * (passing any specified arguments) and the return value is
1326 * returned.
1327 *
1328 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1329 * called, if the metatable for myTable has a __metatable
1330 * key, the value of that key is returned instead of the
1331 * actual metatable.
1332 *
1333 * __tostring - Control string representation. When the builtin
1334 * "tostring( myTable )" function is called, if the metatable
1335 * for myTable has a __tostring property set to a function,
1336 * that function is invoked (passing myTable to it) and the
1337 * return value is used as the string representation.
1338 *
1339 * __len - Control table length. When the table length is requested using
1340 * the length operator ( '#' ), if the metatable for myTable has
1341 * a __len key pointing to a function, that function is invoked
1342 * (passing myTable to it) and the return value used as the value
1343 * of "#myTable".
1344 *
1345 * __gc - Userdata finalizer code. When userdata is set to be garbage
1346 * collected, if the metatable has a __gc field pointing to a
1347 * function, that function is first invoked, passing the userdata
1348 * to it. The __gc metamethod is not called for tables.
1349 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1350 *
1351 * Special metamethods for redefining standard operators:
1352 * http://www.lua.org/pil/13.1.html
1353 *
1354 * __add "+"
1355 * __sub "-"
1356 * __mul "*"
1357 * __div "/"
1358 * __unm "!"
1359 * __pow "^"
1360 * __concat ".."
1361 *
1362 * Special methods for redfining standar relations
1363 * http://www.lua.org/pil/13.2.html
1364 *
1365 * __eq "=="
1366 * __lt "<"
1367 * __le "<="
1368 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001369
1370/*
1371 *
1372 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001373 * Class Map
1374 *
1375 *
1376 */
1377
1378/* Returns a struct hlua_map if the stack entry "ud" is
1379 * a class session, otherwise it throws an error.
1380 */
1381__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1382{
1383 return (struct map_descriptor *)MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
1384}
1385
1386/* This function is the map constructor. It don't need
1387 * the class Map object. It creates and return a new Map
1388 * object. It must be called only during "body" or "init"
1389 * context because it process some filesystem accesses.
1390 */
1391__LJMP static int hlua_map_new(struct lua_State *L)
1392{
1393 const char *fn;
1394 int match = PAT_MATCH_STR;
1395 struct sample_conv conv;
1396 const char *file = "";
1397 int line = 0;
1398 lua_Debug ar;
1399 char *err = NULL;
1400 struct arg args[2];
1401
1402 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1403 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1404
1405 fn = MAY_LJMP(luaL_checkstring(L, 1));
1406
1407 if (lua_gettop(L) >= 2) {
1408 match = MAY_LJMP(luaL_checkinteger(L, 2));
1409 if (match < 0 || match >= PAT_MATCH_NUM)
1410 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1411 }
1412
1413 /* Get Lua filename and line number. */
1414 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1415 lua_getinfo(L, "Sl", &ar); /* get info about it */
1416 if (ar.currentline > 0) { /* is there info? */
1417 file = ar.short_src;
1418 line = ar.currentline;
1419 }
1420 }
1421
1422 /* fill fake sample_conv struct. */
1423 conv.kw = ""; /* unused. */
1424 conv.process = NULL; /* unused. */
1425 conv.arg_mask = 0; /* unused. */
1426 conv.val_args = NULL; /* unused. */
1427 conv.out_type = SMP_T_STR;
1428 conv.private = (void *)(long)match;
1429 switch (match) {
1430 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1431 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1432 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1433 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1434 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1435 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1436 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001437 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001438 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1439 default:
1440 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1441 }
1442
1443 /* fill fake args. */
1444 args[0].type = ARGT_STR;
1445 args[0].data.str.str = (char *)fn;
1446 args[1].type = ARGT_STOP;
1447
1448 /* load the map. */
1449 if (!sample_load_map(args, &conv, file, line, &err)) {
1450 /* error case: we cant use luaL_error because we must
1451 * free the err variable.
1452 */
1453 luaL_where(L, 1);
1454 lua_pushfstring(L, "'new': %s.", err);
1455 lua_concat(L, 2);
1456 free(err);
1457 WILL_LJMP(lua_error(L));
1458 }
1459
1460 /* create the lua object. */
1461 lua_newtable(L);
1462 lua_pushlightuserdata(L, args[0].data.map);
1463 lua_rawseti(L, -2, 0);
1464
1465 /* Pop a class Map metatable and affect it to the userdata. */
1466 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1467 lua_setmetatable(L, -2);
1468
1469
1470 return 1;
1471}
1472
1473__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1474{
1475 struct map_descriptor *desc;
1476 struct pattern *pat;
1477 struct sample smp;
1478
1479 MAY_LJMP(check_args(L, 2, "lookup"));
1480 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001481 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001482 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001483 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001484 }
1485 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001486 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001487 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001488 smp.data.u.str.str = (char *)MAY_LJMP(luaL_checklstring(L, 2, (size_t *)&smp.data.u.str.len));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001489 }
1490
1491 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001492 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001493 if (str)
1494 lua_pushstring(L, "");
1495 else
1496 lua_pushnil(L);
1497 return 1;
1498 }
1499
1500 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001501 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001502 return 1;
1503}
1504
1505__LJMP static int hlua_map_lookup(struct lua_State *L)
1506{
1507 return _hlua_map_lookup(L, 0);
1508}
1509
1510__LJMP static int hlua_map_slookup(struct lua_State *L)
1511{
1512 return _hlua_map_lookup(L, 1);
1513}
1514
1515/*
1516 *
1517 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001518 * Class Socket
1519 *
1520 *
1521 */
1522
1523__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1524{
1525 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1526}
1527
1528/* This function is the handler called for each I/O on the established
1529 * connection. It is used for notify space avalaible to send or data
1530 * received.
1531 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001532static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001533{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001534 struct stream_interface *si = appctx->owner;
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001535 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001536
Willy Tarreau87b09662015-04-03 00:22:06 +02001537 /* Wakeup the main stream if the client connection is closed. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001538 if (!c || channel_output_closed(si_ic(si)) || channel_input_closed(si_oc(si))) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001539 if (appctx->ctx.hlua.socket) {
1540 appctx->ctx.hlua.socket->s = NULL;
1541 appctx->ctx.hlua.socket = NULL;
1542 }
1543 si_shutw(si);
1544 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001545 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001546 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1547 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001548 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001549 }
1550
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001551 /* if the connection is not estabkished, inform the stream that we want
1552 * to be notified whenever the connection completes.
1553 */
1554 if (!(c->flags & CO_FL_CONNECTED)) {
1555 si_applet_cant_get(si);
1556 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001557 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001558 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001559
1560 /* This function is called after the connect. */
1561 appctx->ctx.hlua.connected = 1;
1562
1563 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001564 if (channel_may_recv(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001565 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1566
1567 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001568 if (channel_is_empty(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001569 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1570}
1571
Willy Tarreau87b09662015-04-03 00:22:06 +02001572/* This function is called when the "struct stream" is destroyed.
1573 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001574 * Wake all the pending signals.
1575 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001576static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001577{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001578 /* Remove my link in the original object. */
1579 if (appctx->ctx.hlua.socket)
1580 appctx->ctx.hlua.socket->s = NULL;
1581
1582 /* Wake all the task waiting for me. */
1583 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1584 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1585}
1586
1587/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001588 * uses this object. If the stream does not exists, just quit.
1589 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001590 * pending signal can rest in the read and write lists. destroy
1591 * it.
1592 */
1593__LJMP static int hlua_socket_gc(lua_State *L)
1594{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001595 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001596 struct appctx *appctx;
1597
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001598 MAY_LJMP(check_args(L, 1, "__gc"));
1599
1600 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001601 if (!socket->s)
1602 return 0;
1603
Willy Tarreau87b09662015-04-03 00:22:06 +02001604 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001605 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaue7dff022015-04-03 01:14:29 +02001606 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001607 socket->s = NULL;
1608 appctx->ctx.hlua.socket = NULL;
1609
1610 return 0;
1611}
1612
1613/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001614 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001615 */
1616__LJMP static int hlua_socket_close(lua_State *L)
1617{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001618 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001619 struct appctx *appctx;
1620
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001621 MAY_LJMP(check_args(L, 1, "close"));
1622
1623 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001624 if (!socket->s)
1625 return 0;
1626
Willy Tarreau87b09662015-04-03 00:22:06 +02001627 /* Close the stream and remove the associated stop task. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02001628 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001629 appctx = objt_appctx(socket->s->si[0].end);
1630 appctx->ctx.hlua.socket = NULL;
1631 socket->s = NULL;
1632
1633 return 0;
1634}
1635
1636/* This Lua function assumes that the stack contain three parameters.
1637 * 1 - USERDATA containing a struct socket
1638 * 2 - INTEGER with values of the macro defined below
1639 * If the integer is -1, we must read at most one line.
1640 * If the integer is -2, we ust read all the data until the
1641 * end of the stream.
1642 * If the integer is positive value, we must read a number of
1643 * bytes corresponding to this value.
1644 */
1645#define HLSR_READ_LINE (-1)
1646#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001647__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001648{
1649 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1650 int wanted = lua_tointeger(L, 2);
1651 struct hlua *hlua = hlua_gethlua(L);
1652 struct appctx *appctx;
1653 int len;
1654 int nblk;
1655 char *blk1;
1656 int len1;
1657 char *blk2;
1658 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001659 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001660 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001661
1662 /* Check if this lua stack is schedulable. */
1663 if (!hlua || !hlua->task)
1664 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1665 "'frontend', 'backend' or 'task'"));
1666
1667 /* check for connection closed. If some data where read, return it. */
1668 if (!socket->s)
1669 goto connection_closed;
1670
Willy Tarreau94aa6172015-03-13 14:19:06 +01001671 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001672 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001673 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001674 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001675 if (nblk < 0) /* Connection close. */
1676 goto connection_closed;
1677 if (nblk == 0) /* No data avalaible. */
1678 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001679
1680 /* remove final \r\n. */
1681 if (nblk == 1) {
1682 if (blk1[len1-1] == '\n') {
1683 len1--;
1684 skip_at_end++;
1685 if (blk1[len1-1] == '\r') {
1686 len1--;
1687 skip_at_end++;
1688 }
1689 }
1690 }
1691 else {
1692 if (blk2[len2-1] == '\n') {
1693 len2--;
1694 skip_at_end++;
1695 if (blk2[len2-1] == '\r') {
1696 len2--;
1697 skip_at_end++;
1698 }
1699 }
1700 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001701 }
1702
1703 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001704 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001705 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001706 if (nblk < 0) /* Connection close. */
1707 goto connection_closed;
1708 if (nblk == 0) /* No data avalaible. */
1709 goto connection_empty;
1710 }
1711
1712 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001713 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001714 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001715 if (nblk < 0) /* Connection close. */
1716 goto connection_closed;
1717 if (nblk == 0) /* No data avalaible. */
1718 goto connection_empty;
1719
1720 if (len1 > wanted) {
1721 nblk = 1;
1722 len1 = wanted;
1723 } if (nblk == 2 && len1 + len2 > wanted)
1724 len2 = wanted - len1;
1725 }
1726
1727 len = len1;
1728
1729 luaL_addlstring(&socket->b, blk1, len1);
1730 if (nblk == 2) {
1731 len += len2;
1732 luaL_addlstring(&socket->b, blk2, len2);
1733 }
1734
1735 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001736 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001737
1738 /* Don't wait anything. */
Willy Tarreauaa977ba2015-09-25 11:45:06 +02001739 si_applet_wake_cb(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001740
1741 /* If the pattern reclaim to read all the data
1742 * in the connection, got out.
1743 */
1744 if (wanted == HLSR_READ_ALL)
1745 goto connection_empty;
1746 else if (wanted >= 0 && len < wanted)
1747 goto connection_empty;
1748
1749 /* Return result. */
1750 luaL_pushresult(&socket->b);
1751 return 1;
1752
1753connection_closed:
1754
1755 /* If the buffer containds data. */
1756 if (socket->b.n > 0) {
1757 luaL_pushresult(&socket->b);
1758 return 1;
1759 }
1760 lua_pushnil(L);
1761 lua_pushstring(L, "connection closed.");
1762 return 2;
1763
1764connection_empty:
1765
1766 appctx = objt_appctx(socket->s->si[0].end);
1767 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1768 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001769 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001770 return 0;
1771}
1772
1773/* This Lus function gets two parameters. The first one can be string
1774 * or a number. If the string is "*l", the user require one line. If
1775 * the string is "*a", the user require all the content of the stream.
1776 * If the value is a number, the user require a number of bytes equal
1777 * to the value. The default value is "*l" (a line).
1778 *
1779 * This paraeter with a variable type is converted in integer. This
1780 * integer takes this values:
1781 * -1 : read a line
1782 * -2 : read all the stream
1783 * >0 : amount if bytes.
1784 *
1785 * The second parameter is optinal. It contains a string that must be
1786 * concatenated with the read data.
1787 */
1788__LJMP static int hlua_socket_receive(struct lua_State *L)
1789{
1790 int wanted = HLSR_READ_LINE;
1791 const char *pattern;
1792 int type;
1793 char *error;
1794 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001795 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001796
1797 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1798 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1799
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001800 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001801
1802 /* check for pattern. */
1803 if (lua_gettop(L) >= 2) {
1804 type = lua_type(L, 2);
1805 if (type == LUA_TSTRING) {
1806 pattern = lua_tostring(L, 2);
1807 if (strcmp(pattern, "*a") == 0)
1808 wanted = HLSR_READ_ALL;
1809 else if (strcmp(pattern, "*l") == 0)
1810 wanted = HLSR_READ_LINE;
1811 else {
1812 wanted = strtoll(pattern, &error, 10);
1813 if (*error != '\0')
1814 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1815 }
1816 }
1817 else if (type == LUA_TNUMBER) {
1818 wanted = lua_tointeger(L, 2);
1819 if (wanted < 0)
1820 WILL_LJMP(luaL_error(L, "Unsupported size."));
1821 }
1822 }
1823
1824 /* Set pattern. */
1825 lua_pushinteger(L, wanted);
1826 lua_replace(L, 2);
1827
1828 /* init bufffer, and fiil it wih prefix. */
1829 luaL_buffinit(L, &socket->b);
1830
1831 /* Check prefix. */
1832 if (lua_gettop(L) >= 3) {
1833 if (lua_type(L, 3) != LUA_TSTRING)
1834 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1835 pattern = lua_tolstring(L, 3, &len);
1836 luaL_addlstring(&socket->b, pattern, len);
1837 }
1838
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001839 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001840}
1841
1842/* Write the Lua input string in the output buffer.
1843 * This fucntion returns a yield if no space are available.
1844 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001845static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001846{
1847 struct hlua_socket *socket;
1848 struct hlua *hlua = hlua_gethlua(L);
1849 struct appctx *appctx;
1850 size_t buf_len;
1851 const char *buf;
1852 int len;
1853 int send_len;
1854 int sent;
1855
1856 /* Check if this lua stack is schedulable. */
1857 if (!hlua || !hlua->task)
1858 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1859 "'frontend', 'backend' or 'task'"));
1860
1861 /* Get object */
1862 socket = MAY_LJMP(hlua_checksocket(L, 1));
1863 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001864 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001865
1866 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001867 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001868 lua_pushinteger(L, -1);
1869 return 1;
1870 }
1871
1872 /* Update the input buffer data. */
1873 buf += sent;
1874 send_len = buf_len - sent;
1875
1876 /* All the data are sent. */
1877 if (sent >= buf_len)
1878 return 1; /* Implicitly return the length sent. */
1879
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001880 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1881 * the request buffer if its not required.
1882 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001883 if (socket->s->req.buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02001884 if (!stream_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001885 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001886 goto hlua_socket_write_yield_return;
1887 }
1888 }
1889
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001890 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001891 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001892 if (len <= 0)
1893 goto hlua_socket_write_yield_return;
1894
1895 /* send data */
1896 if (len < send_len)
1897 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001898 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001899
1900 /* "Not enough space" (-1), "Buffer too little to contain
1901 * the data" (-2) are not expected because the available length
1902 * is tested.
1903 * Other unknown error are also not expected.
1904 */
1905 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001906 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001907 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001908
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001909 MAY_LJMP(hlua_socket_close(L));
1910 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001911 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001912 return 1;
1913 }
1914
1915 /* update buffers. */
Willy Tarreauaa977ba2015-09-25 11:45:06 +02001916 si_applet_wake_cb(&socket->s->si[0]);
Willy Tarreau94aa6172015-03-13 14:19:06 +01001917 socket->s->req.rex = TICK_ETERNITY;
1918 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001919
1920 /* Update length sent. */
1921 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001922 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001923
1924 /* All the data buffer is sent ? */
1925 if (sent + len >= buf_len)
1926 return 1;
1927
1928hlua_socket_write_yield_return:
1929 appctx = objt_appctx(socket->s->si[0].end);
1930 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1931 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001932 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001933 return 0;
1934}
1935
1936/* This function initiate the send of data. It just check the input
1937 * parameters and push an integer in the Lua stack that contain the
1938 * amount of data writed in the buffer. This is used by the function
1939 * "hlua_socket_write_yield" that can yield.
1940 *
1941 * The Lua function gets between 3 and 4 parameters. The first one is
1942 * the associated object. The second is a string buffer. The third is
1943 * a facultative integer that represents where is the buffer position
1944 * of the start of the data that can send. The first byte is the
1945 * position "1". The default value is "1". The fourth argument is a
1946 * facultative integer that represents where is the buffer position
1947 * of the end of the data that can send. The default is the last byte.
1948 */
1949static int hlua_socket_send(struct lua_State *L)
1950{
1951 int i;
1952 int j;
1953 const char *buf;
1954 size_t buf_len;
1955
1956 /* Check number of arguments. */
1957 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1958 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1959
1960 /* Get the string. */
1961 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1962
1963 /* Get and check j. */
1964 if (lua_gettop(L) == 4) {
1965 j = MAY_LJMP(luaL_checkinteger(L, 4));
1966 if (j < 0)
1967 j = buf_len + j + 1;
1968 if (j > buf_len)
1969 j = buf_len + 1;
1970 lua_pop(L, 1);
1971 }
1972 else
1973 j = buf_len;
1974
1975 /* Get and check i. */
1976 if (lua_gettop(L) == 3) {
1977 i = MAY_LJMP(luaL_checkinteger(L, 3));
1978 if (i < 0)
1979 i = buf_len + i + 1;
1980 if (i > buf_len)
1981 i = buf_len + 1;
1982 lua_pop(L, 1);
1983 } else
1984 i = 1;
1985
1986 /* Check bth i and j. */
1987 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001988 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001989 return 1;
1990 }
1991 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001992 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001993 return 1;
1994 }
1995 if (i == 0)
1996 i = 1;
1997 if (j == 0)
1998 j = 1;
1999
2000 /* Pop the string. */
2001 lua_pop(L, 1);
2002
2003 /* Update the buffer length. */
2004 buf += i - 1;
2005 buf_len = j - i + 1;
2006 lua_pushlstring(L, buf, buf_len);
2007
2008 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002009 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002010
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002011 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002012}
2013
Willy Tarreau22b0a682015-06-17 19:43:49 +02002014#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002015__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2016{
2017 static char buffer[SOCKET_INFO_MAX_LEN];
2018 int ret;
2019 int len;
2020 char *p;
2021
2022 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2023 if (ret <= 0) {
2024 lua_pushnil(L);
2025 return 1;
2026 }
2027
2028 if (ret == AF_UNIX) {
2029 lua_pushstring(L, buffer+1);
2030 return 1;
2031 }
2032 else if (ret == AF_INET6) {
2033 buffer[0] = '[';
2034 len = strlen(buffer);
2035 buffer[len] = ']';
2036 len++;
2037 buffer[len] = ':';
2038 len++;
2039 p = buffer;
2040 }
2041 else if (ret == AF_INET) {
2042 p = buffer + 1;
2043 len = strlen(p);
2044 p[len] = ':';
2045 len++;
2046 }
2047 else {
2048 lua_pushnil(L);
2049 return 1;
2050 }
2051
2052 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2053 lua_pushnil(L);
2054 return 1;
2055 }
2056
2057 lua_pushstring(L, p);
2058 return 1;
2059}
2060
2061/* Returns information about the peer of the connection. */
2062__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2063{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002064 struct hlua_socket *socket;
2065 struct connection *conn;
2066
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002067 MAY_LJMP(check_args(L, 1, "getpeername"));
2068
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002069 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002070
2071 /* Check if the tcp object is avalaible. */
2072 if (!socket->s) {
2073 lua_pushnil(L);
2074 return 1;
2075 }
2076
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002077 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002078 if (!conn) {
2079 lua_pushnil(L);
2080 return 1;
2081 }
2082
2083 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
2084 unsigned int salen = sizeof(conn->addr.to);
2085 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
2086 lua_pushnil(L);
2087 return 1;
2088 }
2089 conn->flags |= CO_FL_ADDR_TO_SET;
2090 }
2091
2092 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2093}
2094
2095/* Returns information about my connection side. */
2096static int hlua_socket_getsockname(struct lua_State *L)
2097{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002098 struct hlua_socket *socket;
2099 struct connection *conn;
2100
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002101 MAY_LJMP(check_args(L, 1, "getsockname"));
2102
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002103 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002104
2105 /* Check if the tcp object is avalaible. */
2106 if (!socket->s) {
2107 lua_pushnil(L);
2108 return 1;
2109 }
2110
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002111 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002112 if (!conn) {
2113 lua_pushnil(L);
2114 return 1;
2115 }
2116
2117 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
2118 unsigned int salen = sizeof(conn->addr.from);
2119 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
2120 lua_pushnil(L);
2121 return 1;
2122 }
2123 conn->flags |= CO_FL_ADDR_FROM_SET;
2124 }
2125
2126 return hlua_socket_info(L, &conn->addr.from);
2127}
2128
2129/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002130static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002131 .obj_type = OBJ_TYPE_APPLET,
2132 .name = "<LUA_TCP>",
2133 .fct = hlua_socket_handler,
2134 .release = hlua_socket_release,
2135};
2136
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002137__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002138{
2139 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2140 struct hlua *hlua = hlua_gethlua(L);
2141 struct appctx *appctx;
2142
2143 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002144 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002145 lua_pushnil(L);
2146 lua_pushstring(L, "Can't connect");
2147 return 2;
2148 }
2149
2150 appctx = objt_appctx(socket->s->si[0].end);
2151
2152 /* Check for connection established. */
2153 if (appctx->ctx.hlua.connected) {
2154 lua_pushinteger(L, 1);
2155 return 1;
2156 }
2157
2158 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2159 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002160 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002161 return 0;
2162}
2163
2164/* This function fail or initite the connection. */
2165__LJMP static int hlua_socket_connect(struct lua_State *L)
2166{
2167 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002168 int port;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002169 const char *ip;
2170 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002171 struct hlua *hlua;
2172 struct appctx *appctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002173
2174 MAY_LJMP(check_args(L, 3, "connect"));
2175
2176 /* Get args. */
2177 socket = MAY_LJMP(hlua_checksocket(L, 1));
2178 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002179 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002180
Willy Tarreau973a5422015-08-05 21:47:23 +02002181 conn = si_alloc_conn(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002182 if (!conn)
2183 WILL_LJMP(luaL_error(L, "connect: internal error"));
2184
2185 /* Parse ip address. */
2186 conn->addr.to.ss_family = AF_UNSPEC;
2187 if (!str2ip2(ip, &conn->addr.to, 0))
2188 WILL_LJMP(luaL_error(L, "connect: cannot parse ip address '%s'", ip));
2189
2190 /* Set port. */
2191 if (conn->addr.to.ss_family == AF_INET)
2192 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2193 else if (conn->addr.to.ss_family == AF_INET6)
2194 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2195
2196 /* it is important not to call the wakeup function directly but to
2197 * pass through task_wakeup(), because this one knows how to apply
2198 * priorities to tasks.
2199 */
2200 task_wakeup(socket->s->task, TASK_WOKEN_INIT);
2201
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002202 hlua = hlua_gethlua(L);
2203 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002204
2205 /* inform the stream that we want to be notified whenever the
2206 * connection completes.
2207 */
2208 si_applet_cant_get(&socket->s->si[0]);
2209 si_applet_cant_put(&socket->s->si[0]);
2210
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002211 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2212 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002213 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002214
2215 return 0;
2216}
2217
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002218#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002219__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2220{
2221 struct hlua_socket *socket;
2222
2223 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2224 socket = MAY_LJMP(hlua_checksocket(L, 1));
2225 socket->s->target = &socket_ssl.obj_type;
2226 return MAY_LJMP(hlua_socket_connect(L));
2227}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002228#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002229
2230__LJMP static int hlua_socket_setoption(struct lua_State *L)
2231{
2232 return 0;
2233}
2234
2235__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2236{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002237 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002238 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002239
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002240 MAY_LJMP(check_args(L, 2, "settimeout"));
2241
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002242 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002243 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002244
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002245 socket->s->req.rto = tmout;
2246 socket->s->req.wto = tmout;
2247 socket->s->res.rto = tmout;
2248 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002249
2250 return 0;
2251}
2252
2253__LJMP static int hlua_socket_new(lua_State *L)
2254{
2255 struct hlua_socket *socket;
2256 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002257 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002258 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002259 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002260
2261 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002262 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002263 hlua_pusherror(L, "socket: full stack");
2264 goto out_fail_conf;
2265 }
2266
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002267 /* Create the object: obj[0] = userdata. */
2268 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002269 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002270 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002271 memset(socket, 0, sizeof(*socket));
2272
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002273 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002274 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002275 hlua_pusherror(L, "socket: uninitialized pools.");
2276 goto out_fail_conf;
2277 }
2278
Willy Tarreau87b09662015-04-03 00:22:06 +02002279 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002280 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2281 lua_setmetatable(L, -2);
2282
Willy Tarreaud420a972015-04-06 00:39:18 +02002283 /* Create the applet context */
2284 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002285 if (!appctx) {
2286 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002287 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002288 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002289
Willy Tarreaud420a972015-04-06 00:39:18 +02002290 appctx->ctx.hlua.socket = socket;
2291 appctx->ctx.hlua.connected = 0;
2292 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2293 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002294
Willy Tarreaud420a972015-04-06 00:39:18 +02002295 /* Now create a session, task and stream for this applet */
2296 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2297 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002298 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002299 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002300 }
2301
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002302 task = task_new();
2303 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002304 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002305 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002306 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002307 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002308
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002309 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002310 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002311 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002312 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002313 }
2314
Willy Tarreaud420a972015-04-06 00:39:18 +02002315 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002316 socket->s = strm;
2317 strm->hlua.T = NULL;
2318 strm->hlua.Tref = LUA_REFNIL;
2319 strm->hlua.Mref = LUA_REFNIL;
2320 strm->hlua.nargs = 0;
2321 strm->hlua.flags = 0;
2322 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002323
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002324 /* Configure "right" stream interface. this "si" is used to connect
2325 * and retrieve data from the server. The connection is initialized
2326 * with the "struct server".
2327 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002328 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002329
2330 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002331 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2332 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002333
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002334 /* Update statistics counters. */
2335 socket_proxy.feconn++; /* beconn will be increased later */
2336 jobs++;
2337 totalconn++;
2338
2339 /* Return yield waiting for connection. */
2340 return 1;
2341
Willy Tarreaud420a972015-04-06 00:39:18 +02002342 out_fail_stream:
2343 task_free(task);
2344 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002345 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002346 out_fail_sess:
2347 appctx_free(appctx);
2348 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002349 WILL_LJMP(lua_error(L));
2350 return 0;
2351}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002352
2353/*
2354 *
2355 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002356 * Class Channel
2357 *
2358 *
2359 */
2360
2361/* Returns the struct hlua_channel join to the class channel in the
2362 * stack entry "ud" or throws an argument error.
2363 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002364__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002365{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002366 return (struct channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002367}
2368
Willy Tarreau47860ed2015-03-10 14:07:50 +01002369/* Pushes the channel onto the top of the stack. If the stask does not have a
2370 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002371 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002372static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002373{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002374 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002375 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002376 return 0;
2377
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002378 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002379 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002380 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002381
2382 /* Pop a class sesison metatable and affect it to the userdata. */
2383 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2384 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002385 return 1;
2386}
2387
2388/* Duplicate all the data present in the input channel and put it
2389 * in a string LUA variables. Returns -1 and push a nil value in
2390 * the stack if the channel is closed and all the data are consumed,
2391 * returns 0 if no data are available, otherwise it returns the length
2392 * of the builded string.
2393 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002394static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002395{
2396 char *blk1;
2397 char *blk2;
2398 int len1;
2399 int len2;
2400 int ret;
2401 luaL_Buffer b;
2402
Willy Tarreau47860ed2015-03-10 14:07:50 +01002403 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002404 if (unlikely(ret == 0))
2405 return 0;
2406
2407 if (unlikely(ret < 0)) {
2408 lua_pushnil(L);
2409 return -1;
2410 }
2411
2412 luaL_buffinit(L, &b);
2413 luaL_addlstring(&b, blk1, len1);
2414 if (unlikely(ret == 2))
2415 luaL_addlstring(&b, blk2, len2);
2416 luaL_pushresult(&b);
2417
2418 if (unlikely(ret == 2))
2419 return len1 + len2;
2420 return len1;
2421}
2422
2423/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2424 * a yield. This function keep the data in the buffer.
2425 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002426__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002427{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002428 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002429
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002430 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2431
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002432 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002433 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002434 return 1;
2435}
2436
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002437/* Check arguments for the function "hlua_channel_dup_yield". */
2438__LJMP static int hlua_channel_dup(lua_State *L)
2439{
2440 MAY_LJMP(check_args(L, 1, "dup"));
2441 MAY_LJMP(hlua_checkchannel(L, 1));
2442 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2443}
2444
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002445/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2446 * a yield. This function consumes the data in the buffer. It returns
2447 * a string containing the data or a nil pointer if no data are available
2448 * and the channel is closed.
2449 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002450__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002451{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002452 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002453 int ret;
2454
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002455 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002456
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002457 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002458 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002459 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002460
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002461 if (unlikely(ret == -1))
2462 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002463
Willy Tarreau47860ed2015-03-10 14:07:50 +01002464 chn->buf->i -= ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002465 return 1;
2466}
2467
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002468/* Check arguments for the fucntion "hlua_channel_get_yield". */
2469__LJMP static int hlua_channel_get(lua_State *L)
2470{
2471 MAY_LJMP(check_args(L, 1, "get"));
2472 MAY_LJMP(hlua_checkchannel(L, 1));
2473 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2474}
2475
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002476/* This functions consumes and returns one line. If the channel is closed,
2477 * and the last data does not contains a final '\n', the data are returned
2478 * without the final '\n'. When no more data are avalaible, it returns nil
2479 * value.
2480 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002481__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002482{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002483 char *blk1;
2484 char *blk2;
2485 int len1;
2486 int len2;
2487 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002488 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002489 int ret;
2490 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002491
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002492 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2493
Willy Tarreau47860ed2015-03-10 14:07:50 +01002494 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002495 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002496 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002497
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002498 if (ret == -1) {
2499 lua_pushnil(L);
2500 return 1;
2501 }
2502
2503 luaL_buffinit(L, &b);
2504 luaL_addlstring(&b, blk1, len1);
2505 len = len1;
2506 if (unlikely(ret == 2)) {
2507 luaL_addlstring(&b, blk2, len2);
2508 len += len2;
2509 }
2510 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002511 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002512 return 1;
2513}
2514
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002515/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2516__LJMP static int hlua_channel_getline(lua_State *L)
2517{
2518 MAY_LJMP(check_args(L, 1, "getline"));
2519 MAY_LJMP(hlua_checkchannel(L, 1));
2520 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2521}
2522
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002523/* This function takes a string as input, and append it at the
2524 * input side of channel. If the data is too big, but a space
2525 * is probably available after sending some data, the function
2526 * yield. If the data is bigger than the buffer, or if the
2527 * channel is closed, it returns -1. otherwise, it returns the
2528 * amount of data writed.
2529 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002530__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002531{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002532 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002533 size_t len;
2534 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2535 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2536 int ret;
2537 int max;
2538
Willy Tarreau47860ed2015-03-10 14:07:50 +01002539 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002540 if (max > len - l)
2541 max = len - l;
2542
Willy Tarreau47860ed2015-03-10 14:07:50 +01002543 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002544 if (ret == -2 || ret == -3) {
2545 lua_pushinteger(L, -1);
2546 return 1;
2547 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002548 if (ret == -1) {
2549 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002550 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002551 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002552 l += ret;
2553 lua_pop(L, 1);
2554 lua_pushinteger(L, l);
2555
Willy Tarreau47860ed2015-03-10 14:07:50 +01002556 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2557 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002558 /* There are no space avalaible, and the output buffer is empty.
2559 * in this case, we cannot add more data, so we cannot yield,
2560 * we return the amount of copyied data.
2561 */
2562 return 1;
2563 }
2564 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002565 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002566 return 1;
2567}
2568
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002569/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002570 * of the writed string, or -1 if the channel is closed or if the
2571 * buffer size is too little for the data.
2572 */
2573__LJMP static int hlua_channel_append(lua_State *L)
2574{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002575 size_t len;
2576
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002577 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002578 MAY_LJMP(hlua_checkchannel(L, 1));
2579 MAY_LJMP(luaL_checklstring(L, 2, &len));
2580 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002581 lua_pushinteger(L, 0);
2582
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002583 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002584}
2585
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002586/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002587 * his process by cleaning the buffer. The result is a replacement
2588 * of the current data. It returns the length of the writed string,
2589 * or -1 if the channel is closed or if the buffer size is too
2590 * little for the data.
2591 */
2592__LJMP static int hlua_channel_set(lua_State *L)
2593{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002594 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002595
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002596 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002597 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002598 lua_pushinteger(L, 0);
2599
Willy Tarreau47860ed2015-03-10 14:07:50 +01002600 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002601
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002602 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002603}
2604
2605/* Append data in the output side of the buffer. This data is immediatly
2606 * sent. The fcuntion returns the ammount of data writed. If the buffer
2607 * cannot contains the data, the function yield. The function returns -1
2608 * if the channel is closed.
2609 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002610__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002611{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002612 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002613 size_t len;
2614 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2615 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2616 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002617 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002618
Willy Tarreau47860ed2015-03-10 14:07:50 +01002619 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002620 lua_pushinteger(L, -1);
2621 return 1;
2622 }
2623
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002624 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2625 * the request buffer if its not required.
2626 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002627 if (chn->buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02002628 if (!stream_alloc_recv_buffer(chn)) {
Willy Tarreau47860ed2015-03-10 14:07:50 +01002629 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002630 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002631 }
2632 }
2633
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002634 /* the writed data will be immediatly sent, so we can check
2635 * the avalaible space without taking in account the reserve.
2636 * The reserve is guaranted for the processing of incoming
2637 * data, because the buffer will be flushed.
2638 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002639 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002640
2641 /* If there are no space avalaible, and the output buffer is empty.
2642 * in this case, we cannot add more data, so we cannot yield,
2643 * we return the amount of copyied data.
2644 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002645 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002646 return 1;
2647
2648 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002649 if (max > len - l)
2650 max = len - l;
2651
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002652 /* The buffer avalaible size may be not contiguous. This test
2653 * detects a non contiguous buffer and realign it.
2654 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002655 if (bi_space_for_replace(chn->buf) < max)
2656 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002657
2658 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002659 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002660
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002661 /* buffer replace considers that the input part is filled.
2662 * so, I must forward these new data in the output part.
2663 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002664 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002665
2666 l += max;
2667 lua_pop(L, 1);
2668 lua_pushinteger(L, l);
2669
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002670 /* If there are no space avalaible, and the output buffer is empty.
2671 * in this case, we cannot add more data, so we cannot yield,
2672 * we return the amount of copyied data.
2673 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002674 max = chn->buf->size - buffer_len(chn->buf);
2675 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002676 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002677
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002678 if (l < len) {
2679 /* If we are waiting for space in the response buffer, we
2680 * must set the flag WAKERESWR. This flag required the task
2681 * wake up if any activity is detected on the response buffer.
2682 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002683 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002684 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002685 else
2686 HLUA_SET_WAKEREQWR(hlua);
2687 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002688 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002689
2690 return 1;
2691}
2692
2693/* Just a wraper of "_hlua_channel_send". This wrapper permits
2694 * yield the LUA process, and resume it without checking the
2695 * input arguments.
2696 */
2697__LJMP static int hlua_channel_send(lua_State *L)
2698{
2699 MAY_LJMP(check_args(L, 2, "send"));
2700 lua_pushinteger(L, 0);
2701
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002702 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002703}
2704
2705/* This function forward and amount of butes. The data pass from
2706 * the input side of the buffer to the output side, and can be
2707 * forwarded. This function never fails.
2708 *
2709 * The Lua function takes an amount of bytes to be forwarded in
2710 * imput. It returns the number of bytes forwarded.
2711 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002712__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002713{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002714 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002715 int len;
2716 int l;
2717 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002718 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002719
2720 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2721 len = MAY_LJMP(luaL_checkinteger(L, 2));
2722 l = MAY_LJMP(luaL_checkinteger(L, -1));
2723
2724 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002725 if (max > chn->buf->i)
2726 max = chn->buf->i;
2727 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002728 l += max;
2729
2730 lua_pop(L, 1);
2731 lua_pushinteger(L, l);
2732
2733 /* Check if it miss bytes to forward. */
2734 if (l < len) {
2735 /* The the input channel or the output channel are closed, we
2736 * must return the amount of data forwarded.
2737 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002738 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002739 return 1;
2740
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002741 /* If we are waiting for space data in the response buffer, we
2742 * must set the flag WAKERESWR. This flag required the task
2743 * wake up if any activity is detected on the response buffer.
2744 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002745 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002746 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002747 else
2748 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002749
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002750 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002751 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002752 }
2753
2754 return 1;
2755}
2756
2757/* Just check the input and prepare the stack for the previous
2758 * function "hlua_channel_forward_yield"
2759 */
2760__LJMP static int hlua_channel_forward(lua_State *L)
2761{
2762 MAY_LJMP(check_args(L, 2, "forward"));
2763 MAY_LJMP(hlua_checkchannel(L, 1));
2764 MAY_LJMP(luaL_checkinteger(L, 2));
2765
2766 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002767 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002768}
2769
2770/* Just returns the number of bytes available in the input
2771 * side of the buffer. This function never fails.
2772 */
2773__LJMP static int hlua_channel_get_in_len(lua_State *L)
2774{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002775 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002776
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002777 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002778 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002779 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002780 return 1;
2781}
2782
2783/* Just returns the number of bytes available in the output
2784 * side of the buffer. This function never fails.
2785 */
2786__LJMP static int hlua_channel_get_out_len(lua_State *L)
2787{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002788 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002789
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002790 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002791 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002792 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002793 return 1;
2794}
2795
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002796/*
2797 *
2798 *
2799 * Class Fetches
2800 *
2801 *
2802 */
2803
2804/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002805 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002806 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002807__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002808{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002809 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002810}
2811
2812/* This function creates and push in the stack a fetch object according
2813 * with a current TXN.
2814 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002815static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002816{
Willy Tarreau7073c472015-04-06 11:15:40 +02002817 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002818
2819 /* Check stack size. */
2820 if (!lua_checkstack(L, 3))
2821 return 0;
2822
2823 /* Create the object: obj[0] = userdata.
2824 * Note that the base of the Fetches object is the
2825 * transaction object.
2826 */
2827 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002828 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002829 lua_rawseti(L, -2, 0);
2830
Willy Tarreau7073c472015-04-06 11:15:40 +02002831 hsmp->s = txn->s;
2832 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002833 hsmp->stringsafe = stringsafe;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002834
2835 /* Pop a class sesison metatable and affect it to the userdata. */
2836 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2837 lua_setmetatable(L, -2);
2838
2839 return 1;
2840}
2841
2842/* This function is an LUA binding. It is called with each sample-fetch.
2843 * It uses closure argument to store the associated sample-fetch. It
2844 * returns only one argument or throws an error. An error is thrown
2845 * only if an error is encountered during the argument parsing. If
2846 * the "sample-fetch" function fails, nil is returned.
2847 */
2848__LJMP static int hlua_run_sample_fetch(lua_State *L)
2849{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002850 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002851 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002852 struct arg args[ARGM_NBARGS + 1];
2853 int i;
2854 struct sample smp;
2855
2856 /* Get closure arguments. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002857 f = (struct sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002858
2859 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002860 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002861
2862 /* Get extra arguments. */
2863 for (i = 0; i < lua_gettop(L) - 1; i++) {
2864 if (i >= ARGM_NBARGS)
2865 break;
2866 hlua_lua2arg(L, i + 2, &args[i]);
2867 }
2868 args[i].type = ARGT_STOP;
2869
2870 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002871 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002872
2873 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002874 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002875 lua_pushfstring(L, "error in arguments");
2876 WILL_LJMP(lua_error(L));
2877 }
2878
2879 /* Initialise the sample. */
2880 memset(&smp, 0, sizeof(smp));
2881
2882 /* Run the sample fetch process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02002883 smp.px = hsmp->p;
2884 smp.sess = hsmp->s->sess;
2885 smp.strm = hsmp->s;
Thierry FOURNIER1d33b882015-05-11 15:25:29 +02002886 smp.opt = 0;
Thierry FOURNIER0786d052015-05-11 15:42:45 +02002887 if (!f->process(args, &smp, f->kw, f->private)) {
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002888 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002889 lua_pushstring(L, "");
2890 else
2891 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002892 return 1;
2893 }
2894
2895 /* Convert the returned sample in lua value. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002896 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002897 hlua_smp2lua_str(L, &smp);
2898 else
2899 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002900 return 1;
2901}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002902
2903/*
2904 *
2905 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002906 * Class Converters
2907 *
2908 *
2909 */
2910
2911/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002912 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002913 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002914__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002915{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002916 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002917}
2918
2919/* This function creates and push in the stack a Converters object
2920 * according with a current TXN.
2921 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002922static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002923{
Willy Tarreau7073c472015-04-06 11:15:40 +02002924 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002925
2926 /* Check stack size. */
2927 if (!lua_checkstack(L, 3))
2928 return 0;
2929
2930 /* Create the object: obj[0] = userdata.
2931 * Note that the base of the Converters object is the
2932 * same than the TXN object.
2933 */
2934 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002935 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002936 lua_rawseti(L, -2, 0);
2937
Willy Tarreau7073c472015-04-06 11:15:40 +02002938 hsmp->s = txn->s;
2939 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002940 hsmp->stringsafe = stringsafe;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002941
Willy Tarreau87b09662015-04-03 00:22:06 +02002942 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002943 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
2944 lua_setmetatable(L, -2);
2945
2946 return 1;
2947}
2948
2949/* This function is an LUA binding. It is called with each converter.
2950 * It uses closure argument to store the associated converter. It
2951 * returns only one argument or throws an error. An error is thrown
2952 * only if an error is encountered during the argument parsing. If
2953 * the converter function function fails, nil is returned.
2954 */
2955__LJMP static int hlua_run_sample_conv(lua_State *L)
2956{
Willy Tarreauda5f1082015-04-06 11:17:13 +02002957 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002958 struct sample_conv *conv;
2959 struct arg args[ARGM_NBARGS + 1];
2960 int i;
2961 struct sample smp;
2962
2963 /* Get closure arguments. */
2964 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
2965
2966 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002967 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002968
2969 /* Get extra arguments. */
2970 for (i = 0; i < lua_gettop(L) - 2; i++) {
2971 if (i >= ARGM_NBARGS)
2972 break;
2973 hlua_lua2arg(L, i + 3, &args[i]);
2974 }
2975 args[i].type = ARGT_STOP;
2976
2977 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002978 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002979
2980 /* Run the special args checker. */
2981 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
2982 hlua_pusherror(L, "error in arguments");
2983 WILL_LJMP(lua_error(L));
2984 }
2985
2986 /* Initialise the sample. */
2987 if (!hlua_lua2smp(L, 2, &smp)) {
2988 hlua_pusherror(L, "error in the input argument");
2989 WILL_LJMP(lua_error(L));
2990 }
2991
2992 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002993 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002994 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002995 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002996 WILL_LJMP(lua_error(L));
2997 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002998 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
2999 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003000 hlua_pusherror(L, "error during the input argument casting");
3001 WILL_LJMP(lua_error(L));
3002 }
3003
3004 /* Run the sample conversion process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02003005 smp.px = hsmp->p;
3006 smp.sess = hsmp->s->sess;
3007 smp.strm = hsmp->s;
Thierry FOURNIER1d33b882015-05-11 15:25:29 +02003008 smp.opt = 0;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003009 if (!conv->process(args, &smp, conv->private)) {
Willy Tarreauda5f1082015-04-06 11:17:13 +02003010 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003011 lua_pushstring(L, "");
3012 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003013 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003014 return 1;
3015 }
3016
3017 /* Convert the returned sample in lua value. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003018 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003019 hlua_smp2lua_str(L, &smp);
3020 else
3021 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003022 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003023}
3024
3025/*
3026 *
3027 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003028 * Class HTTP
3029 *
3030 *
3031 */
3032
3033/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003034 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003035 */
3036__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
3037{
3038 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
3039}
3040
3041/* This function creates and push in the stack a HTTP object
3042 * according with a current TXN.
3043 */
3044static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
3045{
Willy Tarreau9a8ad862015-04-06 11:14:06 +02003046 struct hlua_txn *htxn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003047
3048 /* Check stack size. */
3049 if (!lua_checkstack(L, 3))
3050 return 0;
3051
3052 /* Create the object: obj[0] = userdata.
3053 * Note that the base of the Converters object is the
3054 * same than the TXN object.
3055 */
3056 lua_newtable(L);
Willy Tarreau9a8ad862015-04-06 11:14:06 +02003057 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003058 lua_rawseti(L, -2, 0);
3059
Willy Tarreau9a8ad862015-04-06 11:14:06 +02003060 htxn->s = txn->s;
3061 htxn->p = txn->p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003062
Willy Tarreau87b09662015-04-03 00:22:06 +02003063 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003064 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
3065 lua_setmetatable(L, -2);
3066
3067 return 1;
3068}
3069
3070/* This function creates ans returns an array of HTTP headers.
3071 * This function does not fails. It is used as wrapper with the
3072 * 2 following functions.
3073 */
3074__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3075{
3076 const char *cur_ptr, *cur_next, *p;
3077 int old_idx, cur_idx;
3078 struct hdr_idx_elem *cur_hdr;
3079 const char *hn, *hv;
3080 int hnl, hvl;
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003081 int type;
3082 const char *in;
3083 char *out;
3084 int len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003085
3086 /* Create the table. */
3087 lua_newtable(L);
3088
Willy Tarreaueee5b512015-04-03 23:46:31 +02003089 if (!htxn->s->txn)
3090 return 1;
3091
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003092 /* Build array of headers. */
3093 old_idx = 0;
Willy Tarreaueee5b512015-04-03 23:46:31 +02003094 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003095
3096 while (1) {
Willy Tarreaueee5b512015-04-03 23:46:31 +02003097 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003098 if (!cur_idx)
3099 break;
3100 old_idx = cur_idx;
3101
Willy Tarreaueee5b512015-04-03 23:46:31 +02003102 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003103 cur_ptr = cur_next;
3104 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
3105
3106 /* Now we have one full header at cur_ptr of len cur_hdr->len,
3107 * and the next header starts at cur_next. We'll check
3108 * this header in the list as well as against the default
3109 * rule.
3110 */
3111
3112 /* look for ': *'. */
3113 hn = cur_ptr;
3114 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
3115 if (p >= cur_ptr+cur_hdr->len)
3116 continue;
3117 hnl = p - hn;
3118 p++;
3119 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
3120 p++;
3121 if (p >= cur_ptr+cur_hdr->len)
3122 continue;
3123 hv = p;
3124 hvl = cur_ptr+cur_hdr->len-p;
3125
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003126 /* Lowercase the key. Don't check the size of trash, it have
3127 * the size of one buffer and the input data contains in one
3128 * buffer.
3129 */
3130 out = trash.str;
3131 for (in=hn; in<hn+hnl; in++, out++)
3132 *out = tolower(*in);
3133 *out = '\0';
3134
3135 /* Check for existing entry:
3136 * assume that the table is on the top of the stack, and
3137 * push the key in the stack, the function lua_gettable()
3138 * perform the lookup.
3139 */
3140 lua_pushlstring(L, trash.str, hnl);
3141 lua_gettable(L, -2);
3142 type = lua_type(L, -1);
3143
3144 switch (type) {
3145 case LUA_TNIL:
3146 /* Table not found, create it. */
3147 lua_pop(L, 1); /* remove the nil value. */
3148 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
3149 lua_newtable(L); /* create and push empty table. */
3150 lua_pushlstring(L, hv, hvl); /* push header value. */
3151 lua_rawseti(L, -2, 0); /* index header value (pop it). */
3152 lua_rawset(L, -3); /* index new table with header name (pop the values). */
3153 break;
3154
3155 case LUA_TTABLE:
3156 /* Entry found: push the value in the table. */
3157 len = lua_rawlen(L, -1);
3158 lua_pushlstring(L, hv, hvl); /* push header value. */
3159 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
3160 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
3161 break;
3162
3163 default:
3164 /* Other cases are errors. */
3165 hlua_pusherror(L, "internal error during the parsing of headers.");
3166 WILL_LJMP(lua_error(L));
3167 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003168 }
3169
3170 return 1;
3171}
3172
3173__LJMP static int hlua_http_req_get_headers(lua_State *L)
3174{
3175 struct hlua_txn *htxn;
3176
3177 MAY_LJMP(check_args(L, 1, "req_get_headers"));
3178 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3179
Willy Tarreaueee5b512015-04-03 23:46:31 +02003180 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003181}
3182
3183__LJMP static int hlua_http_res_get_headers(lua_State *L)
3184{
3185 struct hlua_txn *htxn;
3186
3187 MAY_LJMP(check_args(L, 1, "res_get_headers"));
3188 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3189
Willy Tarreaueee5b512015-04-03 23:46:31 +02003190 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003191}
3192
3193/* This function replace full header, or just a value in
3194 * the request or in the response. It is a wrapper fir the
3195 * 4 following functions.
3196 */
3197__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
3198 struct http_msg *msg, int action)
3199{
3200 size_t name_len;
3201 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3202 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
3203 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
3204 struct my_regex re;
3205
3206 if (!regex_comp(reg, &re, 1, 1, NULL))
3207 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
3208
3209 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
3210 regex_free(&re);
3211 return 0;
3212}
3213
3214__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
3215{
3216 struct hlua_txn *htxn;
3217
3218 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3219 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3220
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003221 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003222}
3223
3224__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
3225{
3226 struct hlua_txn *htxn;
3227
3228 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
3229 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3230
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003231 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003232}
3233
3234__LJMP static int hlua_http_req_rep_val(lua_State *L)
3235{
3236 struct hlua_txn *htxn;
3237
3238 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3239 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3240
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003241 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003242}
3243
3244__LJMP static int hlua_http_res_rep_val(lua_State *L)
3245{
3246 struct hlua_txn *htxn;
3247
3248 MAY_LJMP(check_args(L, 4, "res_rep_val"));
3249 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3250
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003251 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003252}
3253
3254/* This function deletes all the occurences of an header.
3255 * It is a wrapper for the 2 following functions.
3256 */
3257__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3258{
3259 size_t len;
3260 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3261 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02003262 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003263
3264 ctx.idx = 0;
3265 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
3266 http_remove_header2(msg, &txn->hdr_idx, &ctx);
3267 return 0;
3268}
3269
3270__LJMP static int hlua_http_req_del_hdr(lua_State *L)
3271{
3272 struct hlua_txn *htxn;
3273
3274 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3275 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3276
Willy Tarreaueee5b512015-04-03 23:46:31 +02003277 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003278}
3279
3280__LJMP static int hlua_http_res_del_hdr(lua_State *L)
3281{
3282 struct hlua_txn *htxn;
3283
3284 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3285 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3286
Willy Tarreaueee5b512015-04-03 23:46:31 +02003287 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003288}
3289
3290/* This function adds an header. It is a wrapper used by
3291 * the 2 following functions.
3292 */
3293__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3294{
3295 size_t name_len;
3296 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3297 size_t value_len;
3298 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
3299 char *p;
3300
3301 /* Check length. */
3302 trash.len = value_len + name_len + 2;
3303 if (trash.len > trash.size)
3304 return 0;
3305
3306 /* Creates the header string. */
3307 p = trash.str;
3308 memcpy(p, name, name_len);
3309 p += name_len;
3310 *p = ':';
3311 p++;
3312 *p = ' ';
3313 p++;
3314 memcpy(p, value, value_len);
3315
Willy Tarreaueee5b512015-04-03 23:46:31 +02003316 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003317 trash.str, trash.len) != 0);
3318
3319 return 0;
3320}
3321
3322__LJMP static int hlua_http_req_add_hdr(lua_State *L)
3323{
3324 struct hlua_txn *htxn;
3325
3326 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
3327 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3328
Willy Tarreaueee5b512015-04-03 23:46:31 +02003329 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003330}
3331
3332__LJMP static int hlua_http_res_add_hdr(lua_State *L)
3333{
3334 struct hlua_txn *htxn;
3335
3336 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
3337 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3338
Willy Tarreaueee5b512015-04-03 23:46:31 +02003339 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003340}
3341
3342static int hlua_http_req_set_hdr(lua_State *L)
3343{
3344 struct hlua_txn *htxn;
3345
3346 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
3347 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3348
Willy Tarreaueee5b512015-04-03 23:46:31 +02003349 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
3350 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003351}
3352
3353static int hlua_http_res_set_hdr(lua_State *L)
3354{
3355 struct hlua_txn *htxn;
3356
3357 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
3358 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3359
Willy Tarreaueee5b512015-04-03 23:46:31 +02003360 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
3361 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003362}
3363
3364/* This function set the method. */
3365static int hlua_http_req_set_meth(lua_State *L)
3366{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003367 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003368 size_t name_len;
3369 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003370
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003371 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003372 return 1;
3373}
3374
3375/* This function set the method. */
3376static int hlua_http_req_set_path(lua_State *L)
3377{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003378 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003379 size_t name_len;
3380 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003381 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003382 return 1;
3383}
3384
3385/* This function set the query-string. */
3386static int hlua_http_req_set_query(lua_State *L)
3387{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003388 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003389 size_t name_len;
3390 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003391
3392 /* Check length. */
3393 if (name_len > trash.size - 1) {
3394 lua_pushboolean(L, 0);
3395 return 1;
3396 }
3397
3398 /* Add the mark question as prefix. */
3399 chunk_reset(&trash);
3400 trash.str[trash.len++] = '?';
3401 memcpy(trash.str + trash.len, name, name_len);
3402 trash.len += name_len;
3403
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003404 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003405 return 1;
3406}
3407
3408/* This function set the uri. */
3409static int hlua_http_req_set_uri(lua_State *L)
3410{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003411 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003412 size_t name_len;
3413 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003414
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003415 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003416 return 1;
3417}
3418
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02003419/* This function set the response code. */
3420static int hlua_http_res_set_status(lua_State *L)
3421{
3422 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3423 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
3424
3425 http_set_status(code, htxn->s);
3426 return 0;
3427}
3428
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003429/*
3430 *
3431 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003432 * Class TXN
3433 *
3434 *
3435 */
3436
3437/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003438 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003439 */
3440__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
3441{
3442 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
3443}
3444
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02003445__LJMP static int hlua_set_var(lua_State *L)
3446{
3447 struct hlua_txn *htxn;
3448 const char *name;
3449 size_t len;
3450 struct sample smp;
3451
3452 MAY_LJMP(check_args(L, 3, "set_var"));
3453
3454 /* It is useles to retrieve the stream, but this function
3455 * runs only in a stream context.
3456 */
3457 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3458 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3459
3460 /* Converts the third argument in a sample. */
3461 hlua_lua2smp(L, 3, &smp);
3462
3463 /* Store the sample in a variable. */
3464 vars_set_by_name(name, len, htxn->s, &smp);
3465 return 0;
3466}
3467
3468__LJMP static int hlua_get_var(lua_State *L)
3469{
3470 struct hlua_txn *htxn;
3471 const char *name;
3472 size_t len;
3473 struct sample smp;
3474
3475 MAY_LJMP(check_args(L, 2, "get_var"));
3476
3477 /* It is useles to retrieve the stream, but this function
3478 * runs only in a stream context.
3479 */
3480 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3481 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3482
3483 if (!vars_get_by_name(name, len, htxn->s, &smp)) {
3484 lua_pushnil(L);
3485 return 1;
3486 }
3487
3488 return hlua_smp2lua(L, &smp);
3489}
3490
Willy Tarreau59551662015-03-10 14:23:13 +01003491__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003492{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003493 struct hlua *hlua;
3494
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003495 MAY_LJMP(check_args(L, 2, "set_priv"));
3496
Willy Tarreau87b09662015-04-03 00:22:06 +02003497 /* It is useles to retrieve the stream, but this function
3498 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003499 */
3500 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003501 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003502
3503 /* Remove previous value. */
3504 if (hlua->Mref != -1)
3505 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3506
3507 /* Get and store new value. */
3508 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3509 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3510
3511 return 0;
3512}
3513
Willy Tarreau59551662015-03-10 14:23:13 +01003514__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003515{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003516 struct hlua *hlua;
3517
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003518 MAY_LJMP(check_args(L, 1, "get_priv"));
3519
Willy Tarreau87b09662015-04-03 00:22:06 +02003520 /* It is useles to retrieve the stream, but this function
3521 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003522 */
3523 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003524 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003525
3526 /* Push configuration index in the stack. */
3527 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3528
3529 return 1;
3530}
3531
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003532/* Create stack entry containing a class TXN. This function
3533 * return 0 if the stack does not contains free slots,
3534 * otherwise it returns 1.
3535 */
Willy Tarreau15e91e12015-04-04 00:52:09 +02003536static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003537{
Willy Tarreaude491382015-04-06 11:04:28 +02003538 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003539
3540 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003541 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003542 return 0;
3543
3544 /* NOTE: The allocation never fails. The failure
3545 * throw an error, and the function never returns.
3546 * if the throw is not avalaible, the process is aborted.
3547 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003548 /* Create the object: obj[0] = userdata. */
3549 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02003550 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003551 lua_rawseti(L, -2, 0);
3552
Willy Tarreaude491382015-04-06 11:04:28 +02003553 htxn->s = s;
3554 htxn->p = p;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003555
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003556 /* Create the "f" field that contains a list of fetches. */
3557 lua_pushstring(L, "f");
Willy Tarreaude491382015-04-06 11:04:28 +02003558 if (!hlua_fetches_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003559 return 0;
3560 lua_settable(L, -3);
3561
3562 /* Create the "sf" field that contains a list of stringsafe fetches. */
3563 lua_pushstring(L, "sf");
Willy Tarreaude491382015-04-06 11:04:28 +02003564 if (!hlua_fetches_new(L, htxn, 1))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003565 return 0;
3566 lua_settable(L, -3);
3567
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003568 /* Create the "c" field that contains a list of converters. */
3569 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02003570 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003571 return 0;
3572 lua_settable(L, -3);
3573
3574 /* Create the "sc" field that contains a list of stringsafe converters. */
3575 lua_pushstring(L, "sc");
Willy Tarreaude491382015-04-06 11:04:28 +02003576 if (!hlua_converters_new(L, htxn, 1))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003577 return 0;
3578 lua_settable(L, -3);
3579
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003580 /* Create the "req" field that contains the request channel object. */
3581 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003582 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003583 return 0;
3584 lua_settable(L, -3);
3585
3586 /* Create the "res" field that contains the response channel object. */
3587 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003588 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003589 return 0;
3590 lua_settable(L, -3);
3591
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003592 /* Creates the HTTP object is the current proxy allows http. */
3593 lua_pushstring(L, "http");
3594 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02003595 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003596 return 0;
3597 }
3598 else
3599 lua_pushnil(L);
3600 lua_settable(L, -3);
3601
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003602 /* Pop a class sesison metatable and affect it to the userdata. */
3603 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
3604 lua_setmetatable(L, -2);
3605
3606 return 1;
3607}
3608
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003609__LJMP static int hlua_txn_deflog(lua_State *L)
3610{
3611 const char *msg;
3612 struct hlua_txn *htxn;
3613
3614 MAY_LJMP(check_args(L, 2, "deflog"));
3615 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3616 msg = MAY_LJMP(luaL_checkstring(L, 2));
3617
3618 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
3619 return 0;
3620}
3621
3622__LJMP static int hlua_txn_log(lua_State *L)
3623{
3624 int level;
3625 const char *msg;
3626 struct hlua_txn *htxn;
3627
3628 MAY_LJMP(check_args(L, 3, "log"));
3629 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3630 level = MAY_LJMP(luaL_checkinteger(L, 2));
3631 msg = MAY_LJMP(luaL_checkstring(L, 3));
3632
3633 if (level < 0 || level >= NB_LOG_LEVELS)
3634 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3635
3636 hlua_sendlog(htxn->s->be, level, msg);
3637 return 0;
3638}
3639
3640__LJMP static int hlua_txn_log_debug(lua_State *L)
3641{
3642 const char *msg;
3643 struct hlua_txn *htxn;
3644
3645 MAY_LJMP(check_args(L, 2, "Debug"));
3646 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3647 msg = MAY_LJMP(luaL_checkstring(L, 2));
3648 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
3649 return 0;
3650}
3651
3652__LJMP static int hlua_txn_log_info(lua_State *L)
3653{
3654 const char *msg;
3655 struct hlua_txn *htxn;
3656
3657 MAY_LJMP(check_args(L, 2, "Info"));
3658 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3659 msg = MAY_LJMP(luaL_checkstring(L, 2));
3660 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
3661 return 0;
3662}
3663
3664__LJMP static int hlua_txn_log_warning(lua_State *L)
3665{
3666 const char *msg;
3667 struct hlua_txn *htxn;
3668
3669 MAY_LJMP(check_args(L, 2, "Warning"));
3670 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3671 msg = MAY_LJMP(luaL_checkstring(L, 2));
3672 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
3673 return 0;
3674}
3675
3676__LJMP static int hlua_txn_log_alert(lua_State *L)
3677{
3678 const char *msg;
3679 struct hlua_txn *htxn;
3680
3681 MAY_LJMP(check_args(L, 2, "Alert"));
3682 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3683 msg = MAY_LJMP(luaL_checkstring(L, 2));
3684 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
3685 return 0;
3686}
3687
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003688__LJMP static int hlua_txn_set_loglevel(lua_State *L)
3689{
3690 struct hlua_txn *htxn;
3691 int ll;
3692
3693 MAY_LJMP(check_args(L, 2, "set_loglevel"));
3694 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3695 ll = MAY_LJMP(luaL_checkinteger(L, 2));
3696
3697 if (ll < 0 || ll > 7)
3698 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
3699
3700 htxn->s->logs.level = ll;
3701 return 0;
3702}
3703
3704__LJMP static int hlua_txn_set_tos(lua_State *L)
3705{
3706 struct hlua_txn *htxn;
3707 struct connection *cli_conn;
3708 int tos;
3709
3710 MAY_LJMP(check_args(L, 2, "set_tos"));
3711 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3712 tos = MAY_LJMP(luaL_checkinteger(L, 2));
3713
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003714 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003715 inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, tos);
3716
3717 return 0;
3718}
3719
3720__LJMP static int hlua_txn_set_mark(lua_State *L)
3721{
3722#ifdef SO_MARK
3723 struct hlua_txn *htxn;
3724 struct connection *cli_conn;
3725 int mark;
3726
3727 MAY_LJMP(check_args(L, 2, "set_mark"));
3728 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3729 mark = MAY_LJMP(luaL_checkinteger(L, 2));
3730
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003731 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02003732 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003733#endif
3734 return 0;
3735}
3736
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003737/* This function is an Lua binding that send pending data
3738 * to the client, and close the stream interface.
3739 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02003740__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003741{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003742 struct hlua_txn *htxn;
Willy Tarreau81389672015-03-10 12:03:52 +01003743 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003744
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003745 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003746 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003747
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003748 ic = &htxn->s->req;
3749 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01003750
Willy Tarreau630ef452015-08-28 10:06:15 +02003751 if (htxn->s->txn) {
3752 /* HTTP mode, let's stay in sync with the stream */
3753 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
3754 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
3755 htxn->s->txn->req.sov = 0;
3756 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
3757 oc->analysers = AN_RES_HTTP_XFER_BODY;
3758 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
3759 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
3760
3761 /* Trim any possible response */
3762 oc->buf->i = 0;
3763 htxn->s->txn->rsp.next = htxn->s->txn->rsp.sov = 0;
3764
3765 /* Note that if we want to support keep-alive, we need
3766 * to bypass the close/shutr_now calls below, but that
3767 * may only be done if the HTTP request was already
3768 * processed and the connection header is known (ie
3769 * not during TCP rules).
3770 */
3771 }
3772
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02003773 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01003774 channel_abort(ic);
3775 channel_auto_close(ic);
3776 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02003777
3778 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01003779 channel_auto_read(oc);
3780 channel_auto_close(oc);
3781 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003782
Willy Tarreau0458b082015-08-28 09:40:04 +02003783 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02003784
3785 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003786 return 0;
3787}
3788
3789__LJMP static int hlua_log(lua_State *L)
3790{
3791 int level;
3792 const char *msg;
3793
3794 MAY_LJMP(check_args(L, 2, "log"));
3795 level = MAY_LJMP(luaL_checkinteger(L, 1));
3796 msg = MAY_LJMP(luaL_checkstring(L, 2));
3797
3798 if (level < 0 || level >= NB_LOG_LEVELS)
3799 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3800
3801 hlua_sendlog(NULL, level, msg);
3802 return 0;
3803}
3804
3805__LJMP static int hlua_log_debug(lua_State *L)
3806{
3807 const char *msg;
3808
3809 MAY_LJMP(check_args(L, 1, "debug"));
3810 msg = MAY_LJMP(luaL_checkstring(L, 1));
3811 hlua_sendlog(NULL, LOG_DEBUG, msg);
3812 return 0;
3813}
3814
3815__LJMP static int hlua_log_info(lua_State *L)
3816{
3817 const char *msg;
3818
3819 MAY_LJMP(check_args(L, 1, "info"));
3820 msg = MAY_LJMP(luaL_checkstring(L, 1));
3821 hlua_sendlog(NULL, LOG_INFO, msg);
3822 return 0;
3823}
3824
3825__LJMP static int hlua_log_warning(lua_State *L)
3826{
3827 const char *msg;
3828
3829 MAY_LJMP(check_args(L, 1, "warning"));
3830 msg = MAY_LJMP(luaL_checkstring(L, 1));
3831 hlua_sendlog(NULL, LOG_WARNING, msg);
3832 return 0;
3833}
3834
3835__LJMP static int hlua_log_alert(lua_State *L)
3836{
3837 const char *msg;
3838
3839 MAY_LJMP(check_args(L, 1, "alert"));
3840 msg = MAY_LJMP(luaL_checkstring(L, 1));
3841 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003842 return 0;
3843}
3844
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003845__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003846{
3847 int wakeup_ms = lua_tointeger(L, -1);
3848 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003849 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003850 return 0;
3851}
3852
3853__LJMP static int hlua_sleep(lua_State *L)
3854{
3855 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003856 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003857
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003858 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003859
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003860 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003861 wakeup_ms = tick_add(now_ms, delay);
3862 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003863
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003864 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3865 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003866}
3867
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003868__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003869{
3870 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003871 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003872
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003873 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003874
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003875 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003876 wakeup_ms = tick_add(now_ms, delay);
3877 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003878
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003879 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3880 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003881}
3882
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003883/* This functionis an LUA binding. it permits to give back
3884 * the hand at the HAProxy scheduler. It is used when the
3885 * LUA processing consumes a lot of time.
3886 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003887__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003888{
3889 return 0;
3890}
3891
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003892__LJMP static int hlua_yield(lua_State *L)
3893{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003894 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
3895 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003896}
3897
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003898/* This function change the nice of the currently executed
3899 * task. It is used set low or high priority at the current
3900 * task.
3901 */
Willy Tarreau59551662015-03-10 14:23:13 +01003902__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003903{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003904 struct hlua *hlua;
3905 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003906
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003907 MAY_LJMP(check_args(L, 1, "set_nice"));
3908 hlua = hlua_gethlua(L);
3909 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003910
3911 /* If he task is not set, I'm in a start mode. */
3912 if (!hlua || !hlua->task)
3913 return 0;
3914
3915 if (nice < -1024)
3916 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003917 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003918 nice = 1024;
3919
3920 hlua->task->nice = nice;
3921 return 0;
3922}
3923
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003924/* This function is used as a calback of a task. It is called by the
3925 * HAProxy task subsystem when the task is awaked. The LUA runtime can
3926 * return an E_AGAIN signal, the emmiter of this signal must set a
3927 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02003928 *
3929 * Task wrapper are longjmp safe because the only one Lua code
3930 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003931 */
3932static struct task *hlua_process_task(struct task *task)
3933{
3934 struct hlua *hlua = task->context;
3935 enum hlua_exec status;
3936
3937 /* We need to remove the task from the wait queue before executing
3938 * the Lua code because we don't know if it needs to wait for
3939 * another timer or not in the case of E_AGAIN.
3940 */
3941 task_delete(task);
3942
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003943 /* If it is the first call to the task, we must initialize the
3944 * execution timeouts.
3945 */
3946 if (!HLUA_IS_RUNNING(hlua))
Camilo Lopez685c0142015-08-02 19:07:28 -04003947 hlua->expire = tick_add_ifset(now_ms, hlua_timeout_task);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003948
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003949 /* Execute the Lua code. */
3950 status = hlua_ctx_resume(hlua, 1);
3951
3952 switch (status) {
3953 /* finished or yield */
3954 case HLUA_E_OK:
3955 hlua_ctx_destroy(hlua);
3956 task_delete(task);
3957 task_free(task);
3958 break;
3959
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003960 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
3961 if (hlua->wake_time != TICK_ETERNITY)
3962 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003963 break;
3964
3965 /* finished with error. */
3966 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02003967 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003968 hlua_ctx_destroy(hlua);
3969 task_delete(task);
3970 task_free(task);
3971 break;
3972
3973 case HLUA_E_ERR:
3974 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02003975 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003976 hlua_ctx_destroy(hlua);
3977 task_delete(task);
3978 task_free(task);
3979 break;
3980 }
3981 return NULL;
3982}
3983
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003984/* This function is an LUA binding that register LUA function to be
3985 * executed after the HAProxy configuration parsing and before the
3986 * HAProxy scheduler starts. This function expect only one LUA
3987 * argument that is a function. This function returns nothing, but
3988 * throws if an error is encountered.
3989 */
3990__LJMP static int hlua_register_init(lua_State *L)
3991{
3992 struct hlua_init_function *init;
3993 int ref;
3994
3995 MAY_LJMP(check_args(L, 1, "register_init"));
3996
3997 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3998
3999 init = malloc(sizeof(*init));
4000 if (!init)
4001 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4002
4003 init->function_ref = ref;
4004 LIST_ADDQ(&hlua_init_functions, &init->l);
4005 return 0;
4006}
4007
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004008/* This functio is an LUA binding. It permits to register a task
4009 * executed in parallel of the main HAroxy activity. The task is
4010 * created and it is set in the HAProxy scheduler. It can be called
4011 * from the "init" section, "post init" or during the runtime.
4012 *
4013 * Lua prototype:
4014 *
4015 * <none> core.register_task(<function>)
4016 */
4017static int hlua_register_task(lua_State *L)
4018{
4019 struct hlua *hlua;
4020 struct task *task;
4021 int ref;
4022
4023 MAY_LJMP(check_args(L, 1, "register_task"));
4024
4025 ref = MAY_LJMP(hlua_checkfunction(L, 1));
4026
4027 hlua = malloc(sizeof(*hlua));
4028 if (!hlua)
4029 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4030
4031 task = task_new();
4032 task->context = hlua;
4033 task->process = hlua_process_task;
4034
4035 if (!hlua_ctx_init(hlua, task))
4036 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4037
4038 /* Restore the function in the stack. */
4039 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
4040 hlua->nargs = 0;
4041
4042 /* Schedule task. */
4043 task_schedule(task, now_ms);
4044
4045 return 0;
4046}
4047
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004048/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
4049 * doesn't allow "yield" functions because the HAProxy engine cannot
4050 * resume converters.
4051 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004052static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004053{
4054 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004055 struct stream *stream = smp->strm;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004056
Willy Tarreau87b09662015-04-03 00:22:06 +02004057 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004058 * Lua context can be not initialized. This behavior
4059 * permits to save performances because a systematic
4060 * Lua initialization cause 5% performances loss.
4061 */
Willy Tarreau87b09662015-04-03 00:22:06 +02004062 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004063 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004064 return 0;
4065 }
4066
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004067 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004068 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004069
4070 /* The following Lua calls can fail. */
4071 if (!SET_SAFE_LJMP(stream->hlua.T)) {
4072 SEND_ERR(stream->be, "Lua converter '%s': critical error.\n", fcn->name);
4073 return 0;
4074 }
4075
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004076 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004077 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004078 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004079 return 0;
4080 }
4081
4082 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004083 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004084
4085 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004086 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004087 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004088 return 0;
4089 }
Willy Tarreau87b09662015-04-03 00:22:06 +02004090 hlua_smp2lua(stream->hlua.T, smp);
4091 stream->hlua.nargs = 2;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004092
4093 /* push keywords in the stack. */
4094 if (arg_p) {
4095 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02004096 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004097 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004098 return 0;
4099 }
Willy Tarreau87b09662015-04-03 00:22:06 +02004100 hlua_arg2lua(stream->hlua.T, arg_p);
4101 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004102 }
4103 }
4104
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004105 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02004106 stream->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004107
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004108 /* At this point the execution is safe. */
4109 RESET_SAFE_LJMP(stream->hlua.T);
4110
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004111 /* Set the currently running flag. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004112 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004113 }
4114
4115 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004116 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004117 /* finished. */
4118 case HLUA_E_OK:
4119 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004120 hlua_lua2smp(stream->hlua.T, -1, smp);
4121 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004122 return 1;
4123
4124 /* yield. */
4125 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004126 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004127 return 0;
4128
4129 /* finished with error. */
4130 case HLUA_E_ERRMSG:
4131 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004132 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
4133 fcn->name, lua_tostring(stream->hlua.T, -1));
Willy Tarreau87b09662015-04-03 00:22:06 +02004134 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004135 return 0;
4136
4137 case HLUA_E_ERR:
4138 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004139 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004140
4141 default:
4142 return 0;
4143 }
4144}
4145
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004146/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
4147 * doesn't allow "yield" functions because the HAProxy engine cannot
4148 * resume sample-fetches.
4149 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004150static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
4151 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004152{
4153 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004154 struct stream *stream = smp->strm;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004155
Willy Tarreau87b09662015-04-03 00:22:06 +02004156 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004157 * Lua context can be not initialized. This behavior
4158 * permits to save performances because a systematic
4159 * Lua initialization cause 5% performances loss.
4160 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004161 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004162 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004163 return 0;
4164 }
4165
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004166 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004167 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004168
4169 /* The following Lua calls can fail. */
4170 if (!SET_SAFE_LJMP(stream->hlua.T)) {
4171 SEND_ERR(smp->px, "Lua sample-fetch '%s': critical error.\n", fcn->name);
4172 return 0;
4173 }
4174
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004175 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004176 if (!lua_checkstack(stream->hlua.T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004177 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004178 return 0;
4179 }
4180
4181 /* Restore the function in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004182 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004183
4184 /* push arguments in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004185 if (!hlua_txn_new(stream->hlua.T, stream, smp->px)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004186 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004187 return 0;
4188 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004189 stream->hlua.nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004190
4191 /* push keywords in the stack. */
4192 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
4193 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004194 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004195 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004196 return 0;
4197 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004198 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004199 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004200 return 0;
4201 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004202 hlua_arg2lua(stream->hlua.T, arg_p);
4203 stream->hlua.nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004204 }
4205
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004206 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02004207 stream->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004208
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004209 /* At this point the execution is safe. */
4210 RESET_SAFE_LJMP(stream->hlua.T);
4211
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004212 /* Set the currently running flag. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004213 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004214 }
4215
4216 /* Execute the function. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004217 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004218 /* finished. */
4219 case HLUA_E_OK:
4220 /* Convert the returned value in sample. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004221 hlua_lua2smp(stream->hlua.T, -1, smp);
4222 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004223
4224 /* Set the end of execution flag. */
4225 smp->flags &= ~SMP_F_MAY_CHANGE;
4226 return 1;
4227
4228 /* yield. */
4229 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004230 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004231 return 0;
4232
4233 /* finished with error. */
4234 case HLUA_E_ERRMSG:
4235 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004236 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
4237 fcn->name, lua_tostring(stream->hlua.T, -1));
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004238 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004239 return 0;
4240
4241 case HLUA_E_ERR:
4242 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004243 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004244
4245 default:
4246 return 0;
4247 }
4248}
4249
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004250/* This function is an LUA binding used for registering
4251 * "sample-conv" functions. It expects a converter name used
4252 * in the haproxy configuration file, and an LUA function.
4253 */
4254__LJMP static int hlua_register_converters(lua_State *L)
4255{
4256 struct sample_conv_kw_list *sck;
4257 const char *name;
4258 int ref;
4259 int len;
4260 struct hlua_function *fcn;
4261
4262 MAY_LJMP(check_args(L, 2, "register_converters"));
4263
4264 /* First argument : converter name. */
4265 name = MAY_LJMP(luaL_checkstring(L, 1));
4266
4267 /* Second argument : lua function. */
4268 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4269
4270 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004271 sck = malloc(sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004272 if (!sck)
4273 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4274 fcn = malloc(sizeof(*fcn));
4275 if (!fcn)
4276 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4277
4278 /* Fill fcn. */
4279 fcn->name = strdup(name);
4280 if (!fcn->name)
4281 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4282 fcn->function_ref = ref;
4283
4284 /* List head */
4285 sck->list.n = sck->list.p = NULL;
4286
4287 /* converter keyword. */
4288 len = strlen("lua.") + strlen(name) + 1;
4289 sck->kw[0].kw = malloc(len);
4290 if (!sck->kw[0].kw)
4291 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4292
4293 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
4294 sck->kw[0].process = hlua_sample_conv_wrapper;
4295 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4296 sck->kw[0].val_args = NULL;
4297 sck->kw[0].in_type = SMP_T_STR;
4298 sck->kw[0].out_type = SMP_T_STR;
4299 sck->kw[0].private = fcn;
4300
4301 /* End of array. */
4302 memset(&sck->kw[1], 0, sizeof(struct sample_conv));
4303
4304 /* Register this new converter */
4305 sample_register_convs(sck);
4306
4307 return 0;
4308}
4309
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004310/* This fucntion is an LUA binding used for registering
4311 * "sample-fetch" functions. It expects a converter name used
4312 * in the haproxy configuration file, and an LUA function.
4313 */
4314__LJMP static int hlua_register_fetches(lua_State *L)
4315{
4316 const char *name;
4317 int ref;
4318 int len;
4319 struct sample_fetch_kw_list *sfk;
4320 struct hlua_function *fcn;
4321
4322 MAY_LJMP(check_args(L, 2, "register_fetches"));
4323
4324 /* First argument : sample-fetch name. */
4325 name = MAY_LJMP(luaL_checkstring(L, 1));
4326
4327 /* Second argument : lua function. */
4328 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4329
4330 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004331 sfk = malloc(sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004332 if (!sfk)
4333 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4334 fcn = malloc(sizeof(*fcn));
4335 if (!fcn)
4336 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4337
4338 /* Fill fcn. */
4339 fcn->name = strdup(name);
4340 if (!fcn->name)
4341 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4342 fcn->function_ref = ref;
4343
4344 /* List head */
4345 sfk->list.n = sfk->list.p = NULL;
4346
4347 /* sample-fetch keyword. */
4348 len = strlen("lua.") + strlen(name) + 1;
4349 sfk->kw[0].kw = malloc(len);
4350 if (!sfk->kw[0].kw)
4351 return luaL_error(L, "lua out of memory error.");
4352
4353 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
4354 sfk->kw[0].process = hlua_sample_fetch_wrapper;
4355 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4356 sfk->kw[0].val_args = NULL;
4357 sfk->kw[0].out_type = SMP_T_STR;
4358 sfk->kw[0].use = SMP_USE_HTTP_ANY;
4359 sfk->kw[0].val = 0;
4360 sfk->kw[0].private = fcn;
4361
4362 /* End of array. */
4363 memset(&sfk->kw[1], 0, sizeof(struct sample_fetch));
4364
4365 /* Register this new fetch. */
4366 sample_register_fetches(sfk);
4367
4368 return 0;
4369}
4370
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004371/* This function is a wrapper to execute each LUA function declared
4372 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004373 * return ACT_RET_CONT if the processing is finished (with or without
4374 * error) and return ACT_RET_YIELD if the function must be called again
4375 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004376 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004377static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
4378 struct session *sess, struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004379{
4380 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004381 unsigned int analyzer;
4382
4383 switch (rule->from) {
4384 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; break;
4385 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; break;
4386 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; break;
4387 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; break;
4388 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004389 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004390 return ACT_RET_CONT;
4391 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004392
Willy Tarreau87b09662015-04-03 00:22:06 +02004393 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004394 * Lua context can be not initialized. This behavior
4395 * permits to save performances because a systematic
4396 * Lua initialization cause 5% performances loss.
4397 */
4398 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004399 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004400 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004401 return ACT_RET_CONT;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004402 }
4403
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004404 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004405 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004406
4407 /* The following Lua calls can fail. */
4408 if (!SET_SAFE_LJMP(s->hlua.T)) {
4409 SEND_ERR(px, "Lua function '%s': critical error.\n",
4410 rule->arg.hlua_rule->fcn.name);
4411 return ACT_RET_CONT;
4412 }
4413
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004414 /* Check stack available size. */
4415 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004416 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004417 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004418 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004419 }
4420
4421 /* Restore the function in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004422 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004423
Willy Tarreau87b09662015-04-03 00:22:06 +02004424 /* Create and and push object stream in the stack. */
Willy Tarreau15e91e12015-04-04 00:52:09 +02004425 if (!hlua_txn_new(s->hlua.T, s, px)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004426 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004427 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004428 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004429 }
4430 s->hlua.nargs = 1;
4431
4432 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004433 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004434 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004435 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004436 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004437 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004438 }
4439 lua_pushstring(s->hlua.T, *arg);
4440 s->hlua.nargs++;
4441 }
4442
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004443 /* Now the execution is safe. */
4444 RESET_SAFE_LJMP(s->hlua.T);
4445
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004446 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02004447 s->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004448
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004449 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004450 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004451 }
4452
4453 /* Execute the function. */
4454 switch (hlua_ctx_resume(&s->hlua, 1)) {
4455 /* finished. */
4456 case HLUA_E_OK:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004457 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004458
4459 /* yield. */
4460 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004461 /* Set timeout in the required channel. */
4462 if (s->hlua.wake_time != TICK_ETERNITY) {
4463 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004464 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004465 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004466 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004467 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004468 /* Some actions can be wake up when a "write" event
4469 * is detected on a response channel. This is useful
4470 * only for actions targetted on the requests.
4471 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004472 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004473 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01004474 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004475 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004476 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004477 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004478 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004479 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004480
4481 /* finished with error. */
4482 case HLUA_E_ERRMSG:
4483 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004484 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004485 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004486 lua_pop(s->hlua.T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004487 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004488
4489 case HLUA_E_ERR:
4490 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004491 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004492 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004493
4494 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004495 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004496 }
4497}
4498
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004499/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
4500 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004501 *
4502 * This function can fail with an abort() due to an Lua critical error.
4503 * We are in the configuration parsing process of HAProxy, this abort() is
4504 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004505 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004506static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4507 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004508{
Thierry FOURNIER8255a752015-09-23 21:03:35 +02004509 struct hlua_function *fcn = (struct hlua_function *)rule->kw->private;
4510
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004511 /* Memory for the rule. */
4512 rule->arg.hlua_rule = malloc(sizeof(*rule->arg.hlua_rule));
4513 if (!rule->arg.hlua_rule) {
4514 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004515 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004516 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004517
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004518 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02004519 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004520
4521 /* TODO: later accept arguments. */
4522 rule->arg.hlua_rule->args = NULL;
4523
Thierry FOURNIER42148732015-09-02 17:17:33 +02004524 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004525 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004526 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004527}
4528
Thierry FOURNIER8255a752015-09-23 21:03:35 +02004529/* This function is an LUA binding used for registering
4530 * "sample-conv" functions. It expects a converter name used
4531 * in the haproxy configuration file, and an LUA function.
4532 */
4533__LJMP static int hlua_register_action(lua_State *L)
4534{
4535 struct action_kw_list *akl;
4536 const char *name;
4537 int ref;
4538 int len;
4539 struct hlua_function *fcn;
4540
4541 MAY_LJMP(check_args(L, 3, "register_service"));
4542
4543 /* First argument : converter name. */
4544 name = MAY_LJMP(luaL_checkstring(L, 1));
4545
4546 /* Second argument : environment. */
4547 if (lua_type(L, 2) != LUA_TTABLE)
4548 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
4549
4550 /* Third argument : lua function. */
4551 ref = MAY_LJMP(hlua_checkfunction(L, 3));
4552
4553 /* browse the second argulent as an array. */
4554 lua_pushnil(L);
4555 while (lua_next(L, 2) != 0) {
4556 if (lua_type(L, -1) != LUA_TSTRING)
4557 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
4558
4559 /* Check required environment. Only accepted "http" or "tcp". */
4560 /* Allocate and fill the sample fetch keyword struct. */
4561 akl = malloc(sizeof(*akl) + sizeof(struct action_kw) * 2);
4562 if (!akl)
4563 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4564 fcn = malloc(sizeof(*fcn));
4565 if (!fcn)
4566 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4567
4568 /* Fill fcn. */
4569 fcn->name = strdup(name);
4570 if (!fcn->name)
4571 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4572 fcn->function_ref = ref;
4573
4574 /* List head */
4575 akl->list.n = akl->list.p = NULL;
4576
4577 /* End of array. */
4578 memset(&akl->kw[1], 0, sizeof(*akl->kw));
4579
4580 /* action keyword. */
4581 len = strlen("lua.") + strlen(name) + 1;
4582 akl->kw[0].kw = malloc(len);
4583 if (!akl->kw[0].kw)
4584 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4585
4586 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
4587
4588 akl->kw[0].match_pfx = 0;
4589 akl->kw[0].private = fcn;
4590 akl->kw[0].parse = action_register_lua;
4591
4592 /* select the action registering point. */
4593 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
4594 tcp_req_cont_keywords_register(akl);
4595 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
4596 tcp_res_cont_keywords_register(akl);
4597 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
4598 http_req_keywords_register(akl);
4599 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
4600 http_res_keywords_register(akl);
4601 else
4602 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
4603 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
4604 "are expected.", lua_tostring(L, -1)));
4605
4606 /* pop the environment string. */
4607 lua_pop(L, 1);
4608 }
4609
4610 return 0;
4611}
4612
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004613static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
4614 struct proxy *defpx, const char *file, int line,
4615 char **err, unsigned int *timeout)
4616{
4617 const char *error;
4618
4619 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
4620 if (error && *error != '\0') {
4621 memprintf(err, "%s: invalid timeout", args[0]);
4622 return -1;
4623 }
4624 return 0;
4625}
4626
4627static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
4628 struct proxy *defpx, const char *file, int line,
4629 char **err)
4630{
4631 return hlua_read_timeout(args, section_type, curpx, defpx,
4632 file, line, err, &hlua_timeout_session);
4633}
4634
4635static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
4636 struct proxy *defpx, const char *file, int line,
4637 char **err)
4638{
4639 return hlua_read_timeout(args, section_type, curpx, defpx,
4640 file, line, err, &hlua_timeout_task);
4641}
4642
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004643static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
4644 struct proxy *defpx, const char *file, int line,
4645 char **err)
4646{
4647 char *error;
4648
4649 hlua_nb_instruction = strtoll(args[1], &error, 10);
4650 if (*error != '\0') {
4651 memprintf(err, "%s: invalid number", args[0]);
4652 return -1;
4653 }
4654 return 0;
4655}
4656
Willy Tarreau32f61e22015-03-18 17:54:59 +01004657static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
4658 struct proxy *defpx, const char *file, int line,
4659 char **err)
4660{
4661 char *error;
4662
4663 if (*(args[1]) == 0) {
4664 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
4665 return -1;
4666 }
4667 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
4668 if (*error != '\0') {
4669 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
4670 return -1;
4671 }
4672 return 0;
4673}
4674
4675
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004676/* This function is called by the main configuration key "lua-load". It loads and
4677 * execute an lua file during the parsing of the HAProxy configuration file. It is
4678 * the main lua entry point.
4679 *
4680 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
4681 * occured, otherwise it returns 0.
4682 *
4683 * In some error case, LUA set an error message in top of the stack. This function
4684 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004685 *
4686 * This function can fail with an abort() due to an Lua critical error.
4687 * We are in the configuration parsing process of HAProxy, this abort() is
4688 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004689 */
4690static int hlua_load(char **args, int section_type, struct proxy *curpx,
4691 struct proxy *defpx, const char *file, int line,
4692 char **err)
4693{
4694 int error;
4695
4696 /* Just load and compile the file. */
4697 error = luaL_loadfile(gL.T, args[1]);
4698 if (error) {
4699 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
4700 lua_pop(gL.T, 1);
4701 return -1;
4702 }
4703
4704 /* If no syntax error where detected, execute the code. */
4705 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
4706 switch (error) {
4707 case LUA_OK:
4708 break;
4709 case LUA_ERRRUN:
4710 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
4711 lua_pop(gL.T, 1);
4712 return -1;
4713 case LUA_ERRMEM:
4714 memprintf(err, "lua out of memory error\n");
4715 return -1;
4716 case LUA_ERRERR:
4717 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
4718 lua_pop(gL.T, 1);
4719 return -1;
4720 case LUA_ERRGCMM:
4721 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
4722 lua_pop(gL.T, 1);
4723 return -1;
4724 default:
4725 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
4726 lua_pop(gL.T, 1);
4727 return -1;
4728 }
4729
4730 return 0;
4731}
4732
4733/* configuration keywords declaration */
4734static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004735 { CFG_GLOBAL, "lua-load", hlua_load },
4736 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
4737 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004738 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01004739 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004740 { 0, NULL, NULL },
4741}};
4742
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004743/* This function can fail with an abort() due to an Lua critical error.
4744 * We are in the initialisation process of HAProxy, this abort() is
4745 * tolerated.
4746 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004747int hlua_post_init()
4748{
4749 struct hlua_init_function *init;
4750 const char *msg;
4751 enum hlua_exec ret;
4752
4753 list_for_each_entry(init, &hlua_init_functions, l) {
4754 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
4755 ret = hlua_ctx_resume(&gL, 0);
4756 switch (ret) {
4757 case HLUA_E_OK:
4758 lua_pop(gL.T, -1);
4759 return 1;
4760 case HLUA_E_AGAIN:
4761 Alert("lua init: yield not allowed.\n");
4762 return 0;
4763 case HLUA_E_ERRMSG:
4764 msg = lua_tostring(gL.T, -1);
4765 Alert("lua init: %s.\n", msg);
4766 return 0;
4767 case HLUA_E_ERR:
4768 default:
4769 Alert("lua init: unknown runtime error.\n");
4770 return 0;
4771 }
4772 }
4773 return 1;
4774}
4775
Willy Tarreau32f61e22015-03-18 17:54:59 +01004776/* The memory allocator used by the Lua stack. <ud> is a pointer to the
4777 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
4778 * is the previously allocated size or the kind of object in case of a new
4779 * allocation. <nsize> is the requested new size.
4780 */
4781static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
4782{
4783 struct hlua_mem_allocator *zone = ud;
4784
4785 if (nsize == 0) {
4786 /* it's a free */
4787 if (ptr)
4788 zone->allocated -= osize;
4789 free(ptr);
4790 return NULL;
4791 }
4792
4793 if (!ptr) {
4794 /* it's a new allocation */
4795 if (zone->limit && zone->allocated + nsize > zone->limit)
4796 return NULL;
4797
4798 ptr = malloc(nsize);
4799 if (ptr)
4800 zone->allocated += nsize;
4801 return ptr;
4802 }
4803
4804 /* it's a realloc */
4805 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
4806 return NULL;
4807
4808 ptr = realloc(ptr, nsize);
4809 if (ptr)
4810 zone->allocated += nsize - osize;
4811 return ptr;
4812}
4813
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004814/* Ithis function can fail with an abort() due to an Lua critical error.
4815 * We are in the initialisation process of HAProxy, this abort() is
4816 * tolerated.
4817 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01004818void hlua_init(void)
4819{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004820 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004821 int idx;
4822 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004823 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004824 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004825#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004826 struct srv_kw *kw;
4827 int tmp_error;
4828 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01004829 char *args[] = { /* SSL client configuration. */
4830 "ssl",
4831 "verify",
4832 "none",
4833 "force-sslv3",
4834 NULL
4835 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004836#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004837
Willy Tarreau87b09662015-04-03 00:22:06 +02004838 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004839 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
4840
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004841 /* Register configuration keywords. */
4842 cfg_register_keywords(&cfg_kws);
4843
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004844 /* Init main lua stack. */
4845 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004846 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004847 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004848 gL.T = luaL_newstate();
4849 hlua_sethlua(&gL);
4850 gL.Tref = LUA_REFNIL;
4851 gL.task = NULL;
4852
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004853 /* From this point, until the end of the initialisation fucntion,
4854 * the Lua function can fail with an abort. We are in the initialisation
4855 * process of HAProxy, this abort() is tolerated.
4856 */
4857
Willy Tarreau32f61e22015-03-18 17:54:59 +01004858 /* change the memory allocators to track memory usage */
4859 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
4860
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004861 /* Initialise lua. */
4862 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004863
4864 /*
4865 *
4866 * Create "core" object.
4867 *
4868 */
4869
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01004870 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004871 lua_newtable(gL.T);
4872
4873 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004874 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004875 hlua_class_const_int(gL.T, log_levels[i], i);
4876
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004877 /* Register special functions. */
4878 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004879 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004880 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004881 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02004882 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004883 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01004884 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004885 hlua_class_function(gL.T, "sleep", hlua_sleep);
4886 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01004887 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
4888 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
4889 hlua_class_function(gL.T, "set_map", hlua_set_map);
4890 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004891 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004892 hlua_class_function(gL.T, "log", hlua_log);
4893 hlua_class_function(gL.T, "Debug", hlua_log_debug);
4894 hlua_class_function(gL.T, "Info", hlua_log_info);
4895 hlua_class_function(gL.T, "Warning", hlua_log_warning);
4896 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02004897 hlua_class_function(gL.T, "done", hlua_done);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004898
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004899 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004900
4901 /*
4902 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02004903 * Register class Map
4904 *
4905 */
4906
4907 /* This table entry is the object "Map" base. */
4908 lua_newtable(gL.T);
4909
4910 /* register pattern types. */
4911 for (i=0; i<PAT_MATCH_NUM; i++)
4912 hlua_class_const_int(gL.T, pat_match_names[i], i);
4913
4914 /* register constructor. */
4915 hlua_class_function(gL.T, "new", hlua_map_new);
4916
4917 /* Create and fill the metatable. */
4918 lua_newtable(gL.T);
4919
4920 /* Create and fille the __index entry. */
4921 lua_pushstring(gL.T, "__index");
4922 lua_newtable(gL.T);
4923
4924 /* Register . */
4925 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
4926 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
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_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4933 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_MAP); /* register class session. */
4934 class_map_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4935
4936 /* Assign the metatable to the mai Map object. */
4937 lua_setmetatable(gL.T, -2);
4938
4939 /* Set a name to the table. */
4940 lua_setglobal(gL.T, "Map");
4941
4942 /*
4943 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004944 * Register class Channel
4945 *
4946 */
4947
4948 /* Create and fill the metatable. */
4949 lua_newtable(gL.T);
4950
4951 /* Create and fille the __index entry. */
4952 lua_pushstring(gL.T, "__index");
4953 lua_newtable(gL.T);
4954
4955 /* Register . */
4956 hlua_class_function(gL.T, "get", hlua_channel_get);
4957 hlua_class_function(gL.T, "dup", hlua_channel_dup);
4958 hlua_class_function(gL.T, "getline", hlua_channel_getline);
4959 hlua_class_function(gL.T, "set", hlua_channel_set);
4960 hlua_class_function(gL.T, "append", hlua_channel_append);
4961 hlua_class_function(gL.T, "send", hlua_channel_send);
4962 hlua_class_function(gL.T, "forward", hlua_channel_forward);
4963 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
4964 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
4965
4966 lua_settable(gL.T, -3);
4967
4968 /* Register previous table in the registry with reference and named entry. */
4969 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4970 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
4971 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4972
4973 /*
4974 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004975 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004976 *
4977 */
4978
4979 /* Create and fill the metatable. */
4980 lua_newtable(gL.T);
4981
4982 /* Create and fille the __index entry. */
4983 lua_pushstring(gL.T, "__index");
4984 lua_newtable(gL.T);
4985
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004986 /* Browse existing fetches and create the associated
4987 * object method.
4988 */
4989 sf = NULL;
4990 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
4991
4992 /* Dont register the keywork if the arguments check function are
4993 * not safe during the runtime.
4994 */
4995 if ((sf->val_args != NULL) &&
4996 (sf->val_args != val_payload_lv) &&
4997 (sf->val_args != val_hdr))
4998 continue;
4999
5000 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
5001 * by an underscore.
5002 */
5003 strncpy(trash.str, sf->kw, trash.size);
5004 trash.str[trash.size - 1] = '\0';
5005 for (p = trash.str; *p; p++)
5006 if (*p == '.' || *p == '-' || *p == '+')
5007 *p = '_';
5008
5009 /* Register the function. */
5010 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01005011 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01005012 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
5013 lua_settable(gL.T, -3);
5014 }
5015
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005016 lua_settable(gL.T, -3);
5017
5018 /* Register previous table in the registry with reference and named entry. */
5019 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5020 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
5021 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
5022
5023 /*
5024 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005025 * Register class Converters
5026 *
5027 */
5028
5029 /* Create and fill the metatable. */
5030 lua_newtable(gL.T);
5031
5032 /* Create and fill the __index entry. */
5033 lua_pushstring(gL.T, "__index");
5034 lua_newtable(gL.T);
5035
5036 /* Browse existing converters and create the associated
5037 * object method.
5038 */
5039 sc = NULL;
5040 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
5041 /* Dont register the keywork if the arguments check function are
5042 * not safe during the runtime.
5043 */
5044 if (sc->val_args != NULL)
5045 continue;
5046
5047 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
5048 * by an underscore.
5049 */
5050 strncpy(trash.str, sc->kw, trash.size);
5051 trash.str[trash.size - 1] = '\0';
5052 for (p = trash.str; *p; p++)
5053 if (*p == '.' || *p == '-' || *p == '+')
5054 *p = '_';
5055
5056 /* Register the function. */
5057 lua_pushstring(gL.T, trash.str);
5058 lua_pushlightuserdata(gL.T, sc);
5059 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
5060 lua_settable(gL.T, -3);
5061 }
5062
5063 lua_settable(gL.T, -3);
5064
5065 /* Register previous table in the registry with reference and named entry. */
5066 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5067 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
5068 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
5069
5070 /*
5071 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005072 * Register class HTTP
5073 *
5074 */
5075
5076 /* Create and fill the metatable. */
5077 lua_newtable(gL.T);
5078
5079 /* Create and fille the __index entry. */
5080 lua_pushstring(gL.T, "__index");
5081 lua_newtable(gL.T);
5082
5083 /* Register Lua functions. */
5084 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
5085 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
5086 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
5087 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
5088 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
5089 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
5090 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
5091 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
5092 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
5093 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
5094
5095 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
5096 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
5097 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
5098 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
5099 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
5100 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005101 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005102
5103 lua_settable(gL.T, -3);
5104
5105 /* Register previous table in the registry with reference and named entry. */
5106 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5107 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_HTTP); /* register class session. */
5108 class_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
5109
5110 /*
5111 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005112 * Register class TXN
5113 *
5114 */
5115
5116 /* Create and fill the metatable. */
5117 lua_newtable(gL.T);
5118
5119 /* Create and fille the __index entry. */
5120 lua_pushstring(gL.T, "__index");
5121 lua_newtable(gL.T);
5122
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005123 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01005124 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
5125 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005126 hlua_class_function(gL.T, "set_var", hlua_set_var);
5127 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005128 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005129 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
5130 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
5131 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005132 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
5133 hlua_class_function(gL.T, "log", hlua_txn_log);
5134 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
5135 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
5136 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
5137 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005138
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005139 lua_settable(gL.T, -3);
5140
5141 /* Register previous table in the registry with reference and named entry. */
5142 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5143 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
5144 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005145
5146 /*
5147 *
5148 * Register class Socket
5149 *
5150 */
5151
5152 /* Create and fill the metatable. */
5153 lua_newtable(gL.T);
5154
5155 /* Create and fille the __index entry. */
5156 lua_pushstring(gL.T, "__index");
5157 lua_newtable(gL.T);
5158
Baptiste Assmann84bb4932015-03-02 21:40:06 +01005159#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005160 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01005161#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005162 hlua_class_function(gL.T, "connect", hlua_socket_connect);
5163 hlua_class_function(gL.T, "send", hlua_socket_send);
5164 hlua_class_function(gL.T, "receive", hlua_socket_receive);
5165 hlua_class_function(gL.T, "close", hlua_socket_close);
5166 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
5167 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
5168 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
5169 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
5170
5171 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
5172
5173 /* Register the garbage collector entry. */
5174 lua_pushstring(gL.T, "__gc");
5175 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
5176 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
5177
5178 /* Register previous table in the registry with reference and named entry. */
5179 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5180 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5181 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
5182 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
5183
5184 /* Proxy and server configuration initialisation. */
5185 memset(&socket_proxy, 0, sizeof(socket_proxy));
5186 init_new_proxy(&socket_proxy);
5187 socket_proxy.parent = NULL;
5188 socket_proxy.last_change = now.tv_sec;
5189 socket_proxy.id = "LUA-SOCKET";
5190 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
5191 socket_proxy.maxconn = 0;
5192 socket_proxy.accept = NULL;
5193 socket_proxy.options2 |= PR_O2_INDEPSTR;
5194 socket_proxy.srv = NULL;
5195 socket_proxy.conn_retries = 0;
5196 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
5197
5198 /* Init TCP server: unchanged parameters */
5199 memset(&socket_tcp, 0, sizeof(socket_tcp));
5200 socket_tcp.next = NULL;
5201 socket_tcp.proxy = &socket_proxy;
5202 socket_tcp.obj_type = OBJ_TYPE_SERVER;
5203 LIST_INIT(&socket_tcp.actconns);
5204 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02005205 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02005206 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02005207 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005208 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
5209 socket_tcp.last_change = 0;
5210 socket_tcp.id = "LUA-TCP-CONN";
5211 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5212 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5213 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
5214
5215 /* XXX: Copy default parameter from default server,
5216 * but the default server is not initialized.
5217 */
5218 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
5219 socket_tcp.minconn = socket_proxy.defsrv.minconn;
5220 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
5221 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
5222 socket_tcp.onerror = socket_proxy.defsrv.onerror;
5223 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5224 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
5225 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5226 socket_tcp.uweight = socket_proxy.defsrv.iweight;
5227 socket_tcp.iweight = socket_proxy.defsrv.iweight;
5228
5229 socket_tcp.check.status = HCHK_STATUS_INI;
5230 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
5231 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
5232 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
5233 socket_tcp.check.server = &socket_tcp;
5234
5235 socket_tcp.agent.status = HCHK_STATUS_INI;
5236 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
5237 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
5238 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
5239 socket_tcp.agent.server = &socket_tcp;
5240
5241 socket_tcp.xprt = &raw_sock;
5242
5243#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005244 /* Init TCP server: unchanged parameters */
5245 memset(&socket_ssl, 0, sizeof(socket_ssl));
5246 socket_ssl.next = NULL;
5247 socket_ssl.proxy = &socket_proxy;
5248 socket_ssl.obj_type = OBJ_TYPE_SERVER;
5249 LIST_INIT(&socket_ssl.actconns);
5250 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02005251 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02005252 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02005253 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005254 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
5255 socket_ssl.last_change = 0;
5256 socket_ssl.id = "LUA-SSL-CONN";
5257 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5258 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5259 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
5260
5261 /* XXX: Copy default parameter from default server,
5262 * but the default server is not initialized.
5263 */
5264 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
5265 socket_ssl.minconn = socket_proxy.defsrv.minconn;
5266 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
5267 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
5268 socket_ssl.onerror = socket_proxy.defsrv.onerror;
5269 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5270 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
5271 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5272 socket_ssl.uweight = socket_proxy.defsrv.iweight;
5273 socket_ssl.iweight = socket_proxy.defsrv.iweight;
5274
5275 socket_ssl.check.status = HCHK_STATUS_INI;
5276 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
5277 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
5278 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
5279 socket_ssl.check.server = &socket_ssl;
5280
5281 socket_ssl.agent.status = HCHK_STATUS_INI;
5282 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
5283 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
5284 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
5285 socket_ssl.agent.server = &socket_ssl;
5286
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005287 socket_ssl.use_ssl = 1;
5288 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005289
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005290 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005291 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
5292 /*
5293 *
5294 * If the keyword is not known, we can search in the registered
5295 * server keywords. This is usefull to configure special SSL
5296 * features like client certificates and ssl_verify.
5297 *
5298 */
5299 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
5300 if (tmp_error != 0) {
5301 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
5302 abort(); /* This must be never arrives because the command line
5303 not editable by the user. */
5304 }
5305 idx += kw->skip;
5306 }
5307 }
5308
5309 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005310 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005311#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01005312}