blob: 5ee233727ec0d18cff1d05ef2d0b8c37b002f4c1 [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 FOURNIERf0a64b62015-09-19 12:36:17 +0200112/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200113#define APPLET_DONE 0x01 /* applet processing is done. */
114#define APPLET_100C 0x02 /* 100 continue expected. */
115#define APPLET_HDR_SENT 0x04 /* Response header sent. */
116#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
117#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
118
119#define HTTP_100C "HTTP/1.1 100 Continue\r\n\r\n"
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200120
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100121/* The main Lua execution context. */
122struct hlua gL;
123
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100124/* This is the memory pool containing all the signal structs. These
125 * struct are used to store each requiered signal between two tasks.
126 */
127struct pool_head *pool2_hlua_com;
128
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100129/* Used for Socket connection. */
130static struct proxy socket_proxy;
131static struct server socket_tcp;
132#ifdef USE_OPENSSL
133static struct server socket_ssl;
134#endif
135
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100136/* List head of the function called at the initialisation time. */
137struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
138
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100139/* The following variables contains the reference of the different
140 * Lua classes. These references are useful for identify metadata
141 * associated with an object.
142 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100143static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100144static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100145static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100146static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100147static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100148static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200149static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200150static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200151static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100152
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100153/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200154 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100155 * short timeout. Lua linked with tasks doesn't have a timeout
156 * because a task may remain alive during all the haproxy execution.
157 */
158static unsigned int hlua_timeout_session = 4000; /* session timeout. */
159static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200160static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100161
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100162/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
163 * it is used for preventing infinite loops.
164 *
165 * I test the scheer with an infinite loop containing one incrementation
166 * and one test. I run this loop between 10 seconds, I raise a ceil of
167 * 710M loops from one interrupt each 9000 instructions, so I fix the value
168 * to one interrupt each 10 000 instructions.
169 *
170 * configured | Number of
171 * instructions | loops executed
172 * between two | in milions
173 * forced yields |
174 * ---------------+---------------
175 * 10 | 160
176 * 500 | 670
177 * 1000 | 680
178 * 5000 | 700
179 * 7000 | 700
180 * 8000 | 700
181 * 9000 | 710 <- ceil
182 * 10000 | 710
183 * 100000 | 710
184 * 1000000 | 710
185 *
186 */
187static unsigned int hlua_nb_instruction = 10000;
188
Willy Tarreau32f61e22015-03-18 17:54:59 +0100189/* Descriptor for the memory allocation state. If limit is not null, it will
190 * be enforced on any memory allocation.
191 */
192struct hlua_mem_allocator {
193 size_t allocated;
194 size_t limit;
195};
196
197static struct hlua_mem_allocator hlua_global_allocator;
198
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200199static const char error_500[] =
200 "HTTP/1.0 500 Server Error\r\n"
201 "Cache-Control: no-cache\r\n"
202 "Connection: close\r\n"
203 "Content-Type: text/html\r\n"
204 "\r\n"
205 "<html><body><h1>500 Server Error</h1>\nAn internal server error occured.\n</body></html>\n";
206
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100207/* These functions converts types between HAProxy internal args or
208 * sample and LUA types. Another function permits to check if the
209 * LUA stack contains arguments according with an required ARG_T
210 * format.
211 */
212static int hlua_arg2lua(lua_State *L, const struct arg *arg);
213static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100214__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
215 unsigned int mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100216static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100217static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100218static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
219
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200220__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
221
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200222#define SEND_ERR(__be, __fmt, __args...) \
223 do { \
224 send_log(__be, LOG_ERR, __fmt, ## __args); \
225 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
226 Alert(__fmt, ## __args); \
227 } while (0)
228
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100229/* Used to check an Lua function type in the stack. It creates and
230 * returns a reference of the function. This function throws an
231 * error if the rgument is not a "function".
232 */
233__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
234{
235 if (!lua_isfunction(L, argno)) {
236 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
237 WILL_LJMP(luaL_argerror(L, argno, msg));
238 }
239 lua_pushvalue(L, argno);
240 return luaL_ref(L, LUA_REGISTRYINDEX);
241}
242
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200243/* Return the string that is of the top of the stack. */
244const char *hlua_get_top_error_string(lua_State *L)
245{
246 if (lua_gettop(L) < 1)
247 return "unknown error";
248 if (lua_type(L, -1) != LUA_TSTRING)
249 return "unknown error";
250 return lua_tostring(L, -1);
251}
252
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100253/* The three following functions are useful for adding entries
254 * in a table. These functions takes a string and respectively an
255 * integer, a string or a function and add it to the table in the
256 * top of the stack.
257 *
258 * These functions throws an error if no more stack size is
259 * available.
260 */
261__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100262 int value)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100263{
264 if (!lua_checkstack(L, 2))
265 WILL_LJMP(luaL_error(L, "full stack"));
266 lua_pushstring(L, name);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100267 lua_pushinteger(L, value);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +0200268 lua_rawset(L, -3);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100269}
270__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
271 const char *value)
272{
273 if (!lua_checkstack(L, 2))
274 WILL_LJMP(luaL_error(L, "full stack"));
275 lua_pushstring(L, name);
276 lua_pushstring(L, value);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +0200277 lua_rawset(L, -3);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100278}
279__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
280 int (*function)(lua_State *L))
281{
282 if (!lua_checkstack(L, 2))
283 WILL_LJMP(luaL_error(L, "full stack"));
284 lua_pushstring(L, name);
285 lua_pushcclosure(L, function, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +0200286 lua_rawset(L, -3);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100287}
288
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +0200289__LJMP static int hlua_dump_object(struct lua_State *L)
290{
291 const char *name = (const char *)lua_tostring(L, lua_upvalueindex(1));
292 lua_pushfstring(L, "HAProxy class %s", name);
293 return 1;
294}
295
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100296/* This function check the number of arguments available in the
297 * stack. If the number of arguments available is not the same
298 * then <nb> an error is throwed.
299 */
300__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
301{
302 if (lua_gettop(L) == nb)
303 return;
304 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
305}
306
307/* Return true if the data in stack[<ud>] is an object of
308 * type <class_ref>.
309 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100310static int hlua_metaistype(lua_State *L, int ud, int class_ref)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100311{
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100312 if (!lua_getmetatable(L, ud))
313 return 0;
314
315 lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
316 if (!lua_rawequal(L, -1, -2)) {
317 lua_pop(L, 2);
318 return 0;
319 }
320
321 lua_pop(L, 2);
322 return 1;
323}
324
325/* Return an object of the expected type, or throws an error. */
326__LJMP static void *hlua_checkudata(lua_State *L, int ud, int class_ref)
327{
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100328 void *p;
329
330 /* Check if the stack entry is an array. */
331 if (!lua_istable(L, ud))
332 WILL_LJMP(luaL_argerror(L, ud, NULL));
333 /* Check if the metadata have the expected type. */
334 if (!hlua_metaistype(L, ud, class_ref))
335 WILL_LJMP(luaL_argerror(L, ud, NULL));
336 /* Push on the stack at the entry [0] of the table. */
337 lua_rawgeti(L, ud, 0);
338 /* Check if this entry is userdata. */
339 p = lua_touserdata(L, -1);
340 if (!p)
341 WILL_LJMP(luaL_argerror(L, ud, NULL));
342 /* Remove the entry returned by lua_rawgeti(). */
343 lua_pop(L, 1);
344 /* Return the associated struct. */
345 return p;
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100346}
347
348/* This fucntion push an error string prefixed by the file name
349 * and the line number where the error is encountered.
350 */
351static int hlua_pusherror(lua_State *L, const char *fmt, ...)
352{
353 va_list argp;
354 va_start(argp, fmt);
355 luaL_where(L, 1);
356 lua_pushvfstring(L, fmt, argp);
357 va_end(argp);
358 lua_concat(L, 2);
359 return 1;
360}
361
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100362/* This function register a new signal. "lua" is the current lua
363 * execution context. It contains a pointer to the associated task.
364 * "link" is a list head attached to an other task that must be wake
365 * the lua task if an event occurs. This is useful with external
366 * events like TCP I/O or sleep functions. This funcion allocate
367 * memory for the signal.
368 */
369static int hlua_com_new(struct hlua *lua, struct list *link)
370{
371 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
372 if (!com)
373 return 0;
374 LIST_ADDQ(&lua->com, &com->purge_me);
375 LIST_ADDQ(link, &com->wake_me);
376 com->task = lua->task;
377 return 1;
378}
379
380/* This function purge all the pending signals when the LUA execution
381 * is finished. This prevent than a coprocess try to wake a deleted
382 * task. This function remove the memory associated to the signal.
383 */
384static void hlua_com_purge(struct hlua *lua)
385{
386 struct hlua_com *com, *back;
387
388 /* Delete all pending communication signals. */
389 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
390 LIST_DEL(&com->purge_me);
391 LIST_DEL(&com->wake_me);
392 pool_free2(pool2_hlua_com, com);
393 }
394}
395
396/* This function sends signals. It wakes all the tasks attached
397 * to a list head, and remove the signal, and free the used
398 * memory.
399 */
400static void hlua_com_wake(struct list *wake)
401{
402 struct hlua_com *com, *back;
403
404 /* Wake task and delete all pending communication signals. */
405 list_for_each_entry_safe(com, back, wake, wake_me) {
406 LIST_DEL(&com->purge_me);
407 LIST_DEL(&com->wake_me);
408 task_wakeup(com->task, TASK_WOKEN_MSG);
409 pool_free2(pool2_hlua_com, com);
410 }
411}
412
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100413/* This functions is used with sample fetch and converters. It
414 * converts the HAProxy configuration argument in a lua stack
415 * values.
416 *
417 * It takes an array of "arg", and each entry of the array is
418 * converted and pushed in the LUA stack.
419 */
420static int hlua_arg2lua(lua_State *L, const struct arg *arg)
421{
422 switch (arg->type) {
423 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100424 case ARGT_TIME:
425 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100426 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100427 break;
428
429 case ARGT_STR:
430 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
431 break;
432
433 case ARGT_IPV4:
434 case ARGT_IPV6:
435 case ARGT_MSK4:
436 case ARGT_MSK6:
437 case ARGT_FE:
438 case ARGT_BE:
439 case ARGT_TAB:
440 case ARGT_SRV:
441 case ARGT_USR:
442 case ARGT_MAP:
443 default:
444 lua_pushnil(L);
445 break;
446 }
447 return 1;
448}
449
450/* This function take one entrie in an LUA stack at the index "ud",
451 * and try to convert it in an HAProxy argument entry. This is useful
452 * with sample fetch wrappers. The input arguments are gived to the
453 * lua wrapper and converted as arg list by thi function.
454 */
455static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
456{
457 switch (lua_type(L, ud)) {
458
459 case LUA_TNUMBER:
460 case LUA_TBOOLEAN:
461 arg->type = ARGT_SINT;
462 arg->data.sint = lua_tointeger(L, ud);
463 break;
464
465 case LUA_TSTRING:
466 arg->type = ARGT_STR;
467 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
468 break;
469
470 case LUA_TUSERDATA:
471 case LUA_TNIL:
472 case LUA_TTABLE:
473 case LUA_TFUNCTION:
474 case LUA_TTHREAD:
475 case LUA_TLIGHTUSERDATA:
476 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200477 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100478 break;
479 }
480 return 1;
481}
482
483/* the following functions are used to convert a struct sample
484 * in Lua type. This useful to convert the return of the
485 * fetchs or converters.
486 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100487static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100488{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200489 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100490 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100491 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200492 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100493 break;
494
495 case SMP_T_BIN:
496 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200497 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100498 break;
499
500 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200501 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100502 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
503 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
504 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
505 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
506 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
507 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
508 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
509 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
510 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200511 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100512 break;
513 default:
514 lua_pushnil(L);
515 break;
516 }
517 break;
518
519 case SMP_T_IPV4:
520 case SMP_T_IPV6:
521 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200522 if (sample_casts[smp->data.type][SMP_T_STR] &&
523 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200524 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100525 else
526 lua_pushnil(L);
527 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100528 default:
529 lua_pushnil(L);
530 break;
531 }
532 return 1;
533}
534
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100535/* the following functions are used to convert a struct sample
536 * in Lua strings. This is useful to convert the return of the
537 * fetchs or converters.
538 */
539static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
540{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200541 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100542
543 case SMP_T_BIN:
544 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200545 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100546 break;
547
548 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200549 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100550 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
551 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
552 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
553 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
554 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
555 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
556 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
557 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
558 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200559 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100560 break;
561 default:
562 lua_pushstring(L, "");
563 break;
564 }
565 break;
566
567 case SMP_T_SINT:
568 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100569 case SMP_T_IPV4:
570 case SMP_T_IPV6:
571 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200572 if (sample_casts[smp->data.type][SMP_T_STR] &&
573 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200574 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100575 else
576 lua_pushstring(L, "");
577 break;
578 default:
579 lua_pushstring(L, "");
580 break;
581 }
582 return 1;
583}
584
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100585/* the following functions are used to convert an Lua type in a
586 * struct sample. This is useful to provide data from a converter
587 * to the LUA code.
588 */
589static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
590{
591 switch (lua_type(L, ud)) {
592
593 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200594 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200595 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100596 break;
597
598
599 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200600 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200601 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100602 break;
603
604 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200605 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100606 smp->flags |= SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200607 smp->data.u.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100608 break;
609
610 case LUA_TUSERDATA:
611 case LUA_TNIL:
612 case LUA_TTABLE:
613 case LUA_TFUNCTION:
614 case LUA_TTHREAD:
615 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200616 case LUA_TNONE:
617 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200618 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200619 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100620 break;
621 }
622 return 1;
623}
624
625/* This function check the "argp" builded by another conversion function
626 * is in accord with the expected argp defined by the "mask". The fucntion
627 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100628 *
629 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
630 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100631 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100632__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
633 unsigned int mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100634{
635 int min_arg;
636 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100637 struct proxy *px;
638 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100639
640 idx = 0;
641 min_arg = ARGM(mask);
642 mask >>= ARGM_BITS;
643
644 while (1) {
645
646 /* Check oversize. */
647 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100648 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100649 }
650
651 /* Check for mandatory arguments. */
652 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100653 if (idx < min_arg) {
654
655 /* If miss other argument than the first one, we return an error. */
656 if (idx > 0)
657 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
658
659 /* If first argument have a certain type, some default values
660 * may be used. See the function smp_resolve_args().
661 */
662 switch (mask & ARGT_MASK) {
663
664 case ARGT_FE:
665 if (!(p->cap & PR_CAP_FE))
666 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
667 argp[idx].data.prx = p;
668 argp[idx].type = ARGT_FE;
669 argp[idx+1].type = ARGT_STOP;
670 break;
671
672 case ARGT_BE:
673 if (!(p->cap & PR_CAP_BE))
674 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
675 argp[idx].data.prx = p;
676 argp[idx].type = ARGT_BE;
677 argp[idx+1].type = ARGT_STOP;
678 break;
679
680 case ARGT_TAB:
681 argp[idx].data.prx = p;
682 argp[idx].type = ARGT_TAB;
683 argp[idx+1].type = ARGT_STOP;
684 break;
685
686 default:
687 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
688 break;
689 }
690 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100691 return 0;
692 }
693
694 /* Check for exceed the number of requiered argument. */
695 if ((mask & ARGT_MASK) == ARGT_STOP &&
696 argp[idx].type != ARGT_STOP) {
697 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
698 }
699
700 if ((mask & ARGT_MASK) == ARGT_STOP &&
701 argp[idx].type == ARGT_STOP) {
702 return 0;
703 }
704
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100705 /* Convert some argument types. */
706 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100707 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100708 if (argp[idx].type != ARGT_SINT)
709 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
710 argp[idx].type = ARGT_SINT;
711 break;
712
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100713 case ARGT_TIME:
714 if (argp[idx].type != ARGT_SINT)
715 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200716 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100717 break;
718
719 case ARGT_SIZE:
720 if (argp[idx].type != ARGT_SINT)
721 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200722 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100723 break;
724
725 case ARGT_FE:
726 if (argp[idx].type != ARGT_STR)
727 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
728 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
729 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200730 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100731 if (!argp[idx].data.prx)
732 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
733 argp[idx].type = ARGT_FE;
734 break;
735
736 case ARGT_BE:
737 if (argp[idx].type != ARGT_STR)
738 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
739 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
740 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200741 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100742 if (!argp[idx].data.prx)
743 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
744 argp[idx].type = ARGT_BE;
745 break;
746
747 case ARGT_TAB:
748 if (argp[idx].type != ARGT_STR)
749 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
750 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
751 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200752 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100753 if (!argp[idx].data.prx)
754 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
755 argp[idx].type = ARGT_TAB;
756 break;
757
758 case ARGT_SRV:
759 if (argp[idx].type != ARGT_STR)
760 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
761 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
762 trash.str[argp[idx].data.str.len] = 0;
763 sname = strrchr(trash.str, '/');
764 if (sname) {
765 *sname++ = '\0';
766 pname = trash.str;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200767 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100768 if (!px)
769 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
770 }
771 else {
772 sname = trash.str;
773 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100774 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100775 argp[idx].data.srv = findserver(px, sname);
776 if (!argp[idx].data.srv)
777 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
778 argp[idx].type = ARGT_SRV;
779 break;
780
781 case ARGT_IPV4:
782 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
783 trash.str[argp[idx].data.str.len] = 0;
784 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
785 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
786 argp[idx].type = ARGT_IPV4;
787 break;
788
789 case ARGT_MSK4:
790 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
791 trash.str[argp[idx].data.str.len] = 0;
792 if (!str2mask(trash.str, &argp[idx].data.ipv4))
793 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
794 argp[idx].type = ARGT_MSK4;
795 break;
796
797 case ARGT_IPV6:
798 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
799 trash.str[argp[idx].data.str.len] = 0;
800 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
801 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
802 argp[idx].type = ARGT_IPV6;
803 break;
804
805 case ARGT_MSK6:
806 case ARGT_MAP:
807 case ARGT_REG:
808 case ARGT_USR:
809 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100810 break;
811 }
812
813 /* Check for type of argument. */
814 if ((mask & ARGT_MASK) != argp[idx].type) {
815 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
816 arg_type_names[(mask & ARGT_MASK)],
817 arg_type_names[argp[idx].type & ARGT_MASK]);
818 WILL_LJMP(luaL_argerror(L, first + idx, msg));
819 }
820
821 /* Next argument. */
822 mask >>= ARGT_BITS;
823 idx++;
824 }
825}
826
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100827/*
828 * The following functions are used to make correspondance between the the
829 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100830 *
831 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100832 * - hlua_sethlua : create the association between hlua context and lua_state.
833 */
834static inline struct hlua *hlua_gethlua(lua_State *L)
835{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100836 struct hlua **hlua = lua_getextraspace(L);
837 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100838}
839static inline void hlua_sethlua(struct hlua *hlua)
840{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100841 struct hlua **hlua_store = lua_getextraspace(hlua->T);
842 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100843}
844
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100845/* This function is used to send logs. It try to send on screen (stderr)
846 * and on the default syslog server.
847 */
848static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
849{
850 struct tm tm;
851 char *p;
852
853 /* Cleanup the log message. */
854 p = trash.str;
855 for (; *msg != '\0'; msg++, p++) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200856 if (p >= trash.str + trash.size - 1) {
857 /* Break the message if exceed the buffer size. */
858 *(p-4) = ' ';
859 *(p-3) = '.';
860 *(p-2) = '.';
861 *(p-1) = '.';
862 break;
863 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100864 if (isprint(*msg))
865 *p = *msg;
866 else
867 *p = '.';
868 }
869 *p = '\0';
870
Thierry FOURNIER5554e292015-09-09 11:21:37 +0200871 send_log(px, level, "%s\n", trash.str);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100872 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200873 get_localtime(date.tv_sec, &tm);
874 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100875 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
876 (int)getpid(), trash.str);
877 fflush(stderr);
878 }
879}
880
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100881/* This function just ensure that the yield will be always
882 * returned with a timeout and permit to set some flags
883 */
884__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100885 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100886{
887 struct hlua *hlua = hlua_gethlua(L);
888
889 /* Set the wake timeout. If timeout is required, we set
890 * the expiration time.
891 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200892 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100893
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100894 hlua->flags |= flags;
895
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100896 /* Process the yield. */
897 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
898}
899
Willy Tarreau87b09662015-04-03 00:22:06 +0200900/* This function initialises the Lua environment stored in the stream.
901 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100902 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200903 *
904 * This function is particular. it initialises a new Lua thread. If the
905 * initialisation fails (example: out of memory error), the lua function
906 * throws an error (longjmp).
907 *
908 * This function manipulates two Lua stack: the main and the thread. Only
909 * the main stack can fail. The thread is not manipulated. This function
910 * MUST NOT manipulate the created thread stack state, because is not
911 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100912 */
913int hlua_ctx_init(struct hlua *lua, struct task *task)
914{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200915 if (!SET_SAFE_LJMP(gL.T)) {
916 lua->Tref = LUA_REFNIL;
917 return 0;
918 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100919 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100920 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100921 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100922 lua->T = lua_newthread(gL.T);
923 if (!lua->T) {
924 lua->Tref = LUA_REFNIL;
925 return 0;
926 }
927 hlua_sethlua(lua);
928 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
929 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200930 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100931 return 1;
932}
933
Willy Tarreau87b09662015-04-03 00:22:06 +0200934/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100935 * is destroyed. The destroy also the memory context. The struct "lua"
936 * is not freed.
937 */
938void hlua_ctx_destroy(struct hlua *lua)
939{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100940 if (!lua->T)
941 return;
942
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100943 /* Purge all the pending signals. */
944 hlua_com_purge(lua);
945
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100946 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
947 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200948
949 /* Forces a garbage collecting process. If the Lua program is finished
950 * without error, we run the GC on the thread pointer. Its freed all
951 * the unused memory.
952 * If the thread is finnish with an error or is currently yielded,
953 * it seems that the GC applied on the thread doesn't clean anything,
954 * so e run the GC on the main thread.
955 * NOTE: maybe this action locks all the Lua threads untiml the en of
956 * the garbage collection.
957 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200958 if (lua->flags & HLUA_MUST_GC) {
959 lua_gc(lua->T, LUA_GCCOLLECT, 0);
960 if (lua_status(lua->T) != LUA_OK)
961 lua_gc(gL.T, LUA_GCCOLLECT, 0);
962 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200963
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200964 lua->T = NULL;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100965}
966
967/* This function is used to restore the Lua context when a coroutine
968 * fails. This function copy the common memory between old coroutine
969 * and the new coroutine. The old coroutine is destroyed, and its
970 * replaced by the new coroutine.
971 * If the flag "keep_msg" is set, the last entry of the old is assumed
972 * as string error message and it is copied in the new stack.
973 */
974static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
975{
976 lua_State *T;
977 int new_ref;
978
979 /* Renew the main LUA stack doesn't have sense. */
980 if (lua == &gL)
981 return 0;
982
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100983 /* New Lua coroutine. */
984 T = lua_newthread(gL.T);
985 if (!T)
986 return 0;
987
988 /* Copy last error message. */
989 if (keep_msg)
990 lua_xmove(lua->T, T, 1);
991
992 /* Copy data between the coroutines. */
993 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
994 lua_xmove(lua->T, T, 1);
995 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
996
997 /* Destroy old data. */
998 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
999
1000 /* The thread is garbage collected by Lua. */
1001 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
1002
1003 /* Fill the struct with the new coroutine values. */
1004 lua->Mref = new_ref;
1005 lua->T = T;
1006 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
1007
1008 /* Set context. */
1009 hlua_sethlua(lua);
1010
1011 return 1;
1012}
1013
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001014void hlua_hook(lua_State *L, lua_Debug *ar)
1015{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001016 struct hlua *hlua = hlua_gethlua(L);
1017
1018 /* Lua cannot yield when its returning from a function,
1019 * so, we can fix the interrupt hook to 1 instruction,
1020 * expecting that the function is finnished.
1021 */
1022 if (lua_gethookmask(L) & LUA_MASKRET) {
1023 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1024 return;
1025 }
1026
1027 /* restore the interrupt condition. */
1028 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1029
1030 /* If we interrupt the Lua processing in yieldable state, we yield.
1031 * If the state is not yieldable, trying yield causes an error.
1032 */
1033 if (lua_isyieldable(L))
1034 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
1035
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001036 /* If we cannot yield, update the clock and check the timeout. */
1037 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001038 hlua->run_time += now_ms - hlua->start_time;
1039 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001040 lua_pushfstring(L, "execution timeout");
1041 WILL_LJMP(lua_error(L));
1042 }
1043
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001044 /* Update the start time. */
1045 hlua->start_time = now_ms;
1046
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001047 /* Try to interrupt the process at the end of the current
1048 * unyieldable function.
1049 */
1050 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001051}
1052
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001053/* This function start or resumes the Lua stack execution. If the flag
1054 * "yield_allowed" if no set and the LUA stack execution returns a yield
1055 * The function return an error.
1056 *
1057 * The function can returns 4 values:
1058 * - HLUA_E_OK : The execution is terminated without any errors.
1059 * - HLUA_E_AGAIN : The execution must continue at the next associated
1060 * task wakeup.
1061 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
1062 * the top of the stack.
1063 * - HLUA_E_ERR : An error has occured without error message.
1064 *
1065 * If an error occured, the stack is renewed and it is ready to run new
1066 * LUA code.
1067 */
1068static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1069{
1070 int ret;
1071 const char *msg;
1072
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001073 /* Initialise run time counter. */
1074 if (!HLUA_IS_RUNNING(lua))
1075 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001076
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001077resume_execution:
1078
1079 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1080 * instructions. it is used for preventing infinite loops.
1081 */
1082 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1083
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001084 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001085 HLUA_SET_RUN(lua);
1086 HLUA_CLR_CTRLYIELD(lua);
1087 HLUA_CLR_WAKERESWR(lua);
1088 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001089
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001090 /* Update the start time. */
1091 lua->start_time = now_ms;
1092
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001093 /* Call the function. */
1094 ret = lua_resume(lua->T, gL.T, lua->nargs);
1095 switch (ret) {
1096
1097 case LUA_OK:
1098 ret = HLUA_E_OK;
1099 break;
1100
1101 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001102 /* Check if the execution timeout is expired. It it is the case, we
1103 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001104 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001105 tv_update_date(0, 1);
1106 lua->run_time += now_ms - lua->start_time;
1107 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001108 lua_settop(lua->T, 0); /* Empty the stack. */
1109 if (!lua_checkstack(lua->T, 1)) {
1110 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001111 break;
1112 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001113 lua_pushfstring(lua->T, "execution timeout");
1114 ret = HLUA_E_ERRMSG;
1115 break;
1116 }
1117 /* Process the forced yield. if the general yield is not allowed or
1118 * if no task were associated this the current Lua execution
1119 * coroutine, we resume the execution. Else we want to return in the
1120 * scheduler and we want to be waked up again, to continue the
1121 * current Lua execution. So we schedule our own task.
1122 */
1123 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001124 if (!yield_allowed || !lua->task)
1125 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001126 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001127 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001128 if (!yield_allowed) {
1129 lua_settop(lua->T, 0); /* Empty the stack. */
1130 if (!lua_checkstack(lua->T, 1)) {
1131 ret = HLUA_E_ERR;
1132 break;
1133 }
1134 lua_pushfstring(lua->T, "yield not allowed");
1135 ret = HLUA_E_ERRMSG;
1136 break;
1137 }
1138 ret = HLUA_E_AGAIN;
1139 break;
1140
1141 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001142
1143 /* Special exit case. The traditionnal exit is returned as an error
1144 * because the errors ares the only one mean to return immediately
1145 * from and lua execution.
1146 */
1147 if (lua->flags & HLUA_EXIT) {
1148 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001149 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001150 break;
1151 }
1152
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001153 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001154 if (!lua_checkstack(lua->T, 1)) {
1155 ret = HLUA_E_ERR;
1156 break;
1157 }
1158 msg = lua_tostring(lua->T, -1);
1159 lua_settop(lua->T, 0); /* Empty the stack. */
1160 lua_pop(lua->T, 1);
1161 if (msg)
1162 lua_pushfstring(lua->T, "runtime error: %s", msg);
1163 else
1164 lua_pushfstring(lua->T, "unknown runtime error");
1165 ret = HLUA_E_ERRMSG;
1166 break;
1167
1168 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001169 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001170 lua_settop(lua->T, 0); /* Empty the stack. */
1171 if (!lua_checkstack(lua->T, 1)) {
1172 ret = HLUA_E_ERR;
1173 break;
1174 }
1175 lua_pushfstring(lua->T, "out of memory error");
1176 ret = HLUA_E_ERRMSG;
1177 break;
1178
1179 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001180 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001181 if (!lua_checkstack(lua->T, 1)) {
1182 ret = HLUA_E_ERR;
1183 break;
1184 }
1185 msg = lua_tostring(lua->T, -1);
1186 lua_settop(lua->T, 0); /* Empty the stack. */
1187 lua_pop(lua->T, 1);
1188 if (msg)
1189 lua_pushfstring(lua->T, "message handler error: %s", msg);
1190 else
1191 lua_pushfstring(lua->T, "message handler error");
1192 ret = HLUA_E_ERRMSG;
1193 break;
1194
1195 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001196 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001197 lua_settop(lua->T, 0); /* Empty the stack. */
1198 if (!lua_checkstack(lua->T, 1)) {
1199 ret = HLUA_E_ERR;
1200 break;
1201 }
1202 lua_pushfstring(lua->T, "unknonwn error");
1203 ret = HLUA_E_ERRMSG;
1204 break;
1205 }
1206
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001207 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001208 if (lua->flags & HLUA_MUST_GC &&
1209 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001210 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1211
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001212 switch (ret) {
1213 case HLUA_E_AGAIN:
1214 break;
1215
1216 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001217 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001218 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001219 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001220 break;
1221
1222 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001223 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001224 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001225 hlua_ctx_renew(lua, 0);
1226 break;
1227
1228 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001229 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001230 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001231 break;
1232 }
1233
1234 return ret;
1235}
1236
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001237/* This function exit the current code. */
1238__LJMP static int hlua_done(lua_State *L)
1239{
1240 struct hlua *hlua = hlua_gethlua(L);
1241
1242 hlua->flags |= HLUA_EXIT;
1243 WILL_LJMP(lua_error(L));
1244
1245 return 0;
1246}
1247
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001248/* This function is an LUA binding. It provides a function
1249 * for deleting ACL from a referenced ACL file.
1250 */
1251__LJMP static int hlua_del_acl(lua_State *L)
1252{
1253 const char *name;
1254 const char *key;
1255 struct pat_ref *ref;
1256
1257 MAY_LJMP(check_args(L, 2, "del_acl"));
1258
1259 name = MAY_LJMP(luaL_checkstring(L, 1));
1260 key = MAY_LJMP(luaL_checkstring(L, 2));
1261
1262 ref = pat_ref_lookup(name);
1263 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001264 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001265
1266 pat_ref_delete(ref, key);
1267 return 0;
1268}
1269
1270/* This function is an LUA binding. It provides a function
1271 * for deleting map entry from a referenced map file.
1272 */
1273static int hlua_del_map(lua_State *L)
1274{
1275 const char *name;
1276 const char *key;
1277 struct pat_ref *ref;
1278
1279 MAY_LJMP(check_args(L, 2, "del_map"));
1280
1281 name = MAY_LJMP(luaL_checkstring(L, 1));
1282 key = MAY_LJMP(luaL_checkstring(L, 2));
1283
1284 ref = pat_ref_lookup(name);
1285 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001286 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001287
1288 pat_ref_delete(ref, key);
1289 return 0;
1290}
1291
1292/* This function is an LUA binding. It provides a function
1293 * for adding ACL pattern from a referenced ACL file.
1294 */
1295static int hlua_add_acl(lua_State *L)
1296{
1297 const char *name;
1298 const char *key;
1299 struct pat_ref *ref;
1300
1301 MAY_LJMP(check_args(L, 2, "add_acl"));
1302
1303 name = MAY_LJMP(luaL_checkstring(L, 1));
1304 key = MAY_LJMP(luaL_checkstring(L, 2));
1305
1306 ref = pat_ref_lookup(name);
1307 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001308 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001309
1310 if (pat_ref_find_elt(ref, key) == NULL)
1311 pat_ref_add(ref, key, NULL, NULL);
1312 return 0;
1313}
1314
1315/* This function is an LUA binding. It provides a function
1316 * for setting map pattern and sample from a referenced map
1317 * file.
1318 */
1319static int hlua_set_map(lua_State *L)
1320{
1321 const char *name;
1322 const char *key;
1323 const char *value;
1324 struct pat_ref *ref;
1325
1326 MAY_LJMP(check_args(L, 3, "set_map"));
1327
1328 name = MAY_LJMP(luaL_checkstring(L, 1));
1329 key = MAY_LJMP(luaL_checkstring(L, 2));
1330 value = MAY_LJMP(luaL_checkstring(L, 3));
1331
1332 ref = pat_ref_lookup(name);
1333 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001334 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001335
1336 if (pat_ref_find_elt(ref, key) != NULL)
1337 pat_ref_set(ref, key, value, NULL);
1338 else
1339 pat_ref_add(ref, key, value, NULL);
1340 return 0;
1341}
1342
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001343/* A class is a lot of memory that contain data. This data can be a table,
1344 * an integer or user data. This data is associated with a metatable. This
1345 * metatable have an original version registred in the global context with
1346 * the name of the object (_G[<name>] = <metable> ).
1347 *
1348 * A metable is a table that modify the standard behavior of a standard
1349 * access to the associated data. The entries of this new metatable are
1350 * defined as is:
1351 *
1352 * http://lua-users.org/wiki/MetatableEvents
1353 *
1354 * __index
1355 *
1356 * we access an absent field in a table, the result is nil. This is
1357 * true, but it is not the whole truth. Actually, such access triggers
1358 * the interpreter to look for an __index metamethod: If there is no
1359 * such method, as usually happens, then the access results in nil;
1360 * otherwise, the metamethod will provide the result.
1361 *
1362 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1363 * the key does not appear in the table, but the metatable has an __index
1364 * property:
1365 *
1366 * - if the value is a function, the function is called, passing in the
1367 * table and the key; the return value of that function is returned as
1368 * the result.
1369 *
1370 * - if the value is another table, the value of the key in that table is
1371 * asked for and returned (and if it doesn't exist in that table, but that
1372 * table's metatable has an __index property, then it continues on up)
1373 *
1374 * - Use "rawget(myTable,key)" to skip this metamethod.
1375 *
1376 * http://www.lua.org/pil/13.4.1.html
1377 *
1378 * __newindex
1379 *
1380 * Like __index, but control property assignment.
1381 *
1382 * __mode - Control weak references. A string value with one or both
1383 * of the characters 'k' and 'v' which specifies that the the
1384 * keys and/or values in the table are weak references.
1385 *
1386 * __call - Treat a table like a function. When a table is followed by
1387 * parenthesis such as "myTable( 'foo' )" and the metatable has
1388 * a __call key pointing to a function, that function is invoked
1389 * (passing any specified arguments) and the return value is
1390 * returned.
1391 *
1392 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1393 * called, if the metatable for myTable has a __metatable
1394 * key, the value of that key is returned instead of the
1395 * actual metatable.
1396 *
1397 * __tostring - Control string representation. When the builtin
1398 * "tostring( myTable )" function is called, if the metatable
1399 * for myTable has a __tostring property set to a function,
1400 * that function is invoked (passing myTable to it) and the
1401 * return value is used as the string representation.
1402 *
1403 * __len - Control table length. When the table length is requested using
1404 * the length operator ( '#' ), if the metatable for myTable has
1405 * a __len key pointing to a function, that function is invoked
1406 * (passing myTable to it) and the return value used as the value
1407 * of "#myTable".
1408 *
1409 * __gc - Userdata finalizer code. When userdata is set to be garbage
1410 * collected, if the metatable has a __gc field pointing to a
1411 * function, that function is first invoked, passing the userdata
1412 * to it. The __gc metamethod is not called for tables.
1413 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1414 *
1415 * Special metamethods for redefining standard operators:
1416 * http://www.lua.org/pil/13.1.html
1417 *
1418 * __add "+"
1419 * __sub "-"
1420 * __mul "*"
1421 * __div "/"
1422 * __unm "!"
1423 * __pow "^"
1424 * __concat ".."
1425 *
1426 * Special methods for redfining standar relations
1427 * http://www.lua.org/pil/13.2.html
1428 *
1429 * __eq "=="
1430 * __lt "<"
1431 * __le "<="
1432 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001433
1434/*
1435 *
1436 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001437 * Class Map
1438 *
1439 *
1440 */
1441
1442/* Returns a struct hlua_map if the stack entry "ud" is
1443 * a class session, otherwise it throws an error.
1444 */
1445__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1446{
1447 return (struct map_descriptor *)MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
1448}
1449
1450/* This function is the map constructor. It don't need
1451 * the class Map object. It creates and return a new Map
1452 * object. It must be called only during "body" or "init"
1453 * context because it process some filesystem accesses.
1454 */
1455__LJMP static int hlua_map_new(struct lua_State *L)
1456{
1457 const char *fn;
1458 int match = PAT_MATCH_STR;
1459 struct sample_conv conv;
1460 const char *file = "";
1461 int line = 0;
1462 lua_Debug ar;
1463 char *err = NULL;
1464 struct arg args[2];
1465
1466 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1467 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1468
1469 fn = MAY_LJMP(luaL_checkstring(L, 1));
1470
1471 if (lua_gettop(L) >= 2) {
1472 match = MAY_LJMP(luaL_checkinteger(L, 2));
1473 if (match < 0 || match >= PAT_MATCH_NUM)
1474 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1475 }
1476
1477 /* Get Lua filename and line number. */
1478 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1479 lua_getinfo(L, "Sl", &ar); /* get info about it */
1480 if (ar.currentline > 0) { /* is there info? */
1481 file = ar.short_src;
1482 line = ar.currentline;
1483 }
1484 }
1485
1486 /* fill fake sample_conv struct. */
1487 conv.kw = ""; /* unused. */
1488 conv.process = NULL; /* unused. */
1489 conv.arg_mask = 0; /* unused. */
1490 conv.val_args = NULL; /* unused. */
1491 conv.out_type = SMP_T_STR;
1492 conv.private = (void *)(long)match;
1493 switch (match) {
1494 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1495 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1496 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1497 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1498 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1499 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1500 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001501 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001502 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1503 default:
1504 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1505 }
1506
1507 /* fill fake args. */
1508 args[0].type = ARGT_STR;
1509 args[0].data.str.str = (char *)fn;
1510 args[1].type = ARGT_STOP;
1511
1512 /* load the map. */
1513 if (!sample_load_map(args, &conv, file, line, &err)) {
1514 /* error case: we cant use luaL_error because we must
1515 * free the err variable.
1516 */
1517 luaL_where(L, 1);
1518 lua_pushfstring(L, "'new': %s.", err);
1519 lua_concat(L, 2);
1520 free(err);
1521 WILL_LJMP(lua_error(L));
1522 }
1523
1524 /* create the lua object. */
1525 lua_newtable(L);
1526 lua_pushlightuserdata(L, args[0].data.map);
1527 lua_rawseti(L, -2, 0);
1528
1529 /* Pop a class Map metatable and affect it to the userdata. */
1530 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1531 lua_setmetatable(L, -2);
1532
1533
1534 return 1;
1535}
1536
1537__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1538{
1539 struct map_descriptor *desc;
1540 struct pattern *pat;
1541 struct sample smp;
1542
1543 MAY_LJMP(check_args(L, 2, "lookup"));
1544 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001545 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001546 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001547 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001548 }
1549 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001550 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001551 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001552 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 +02001553 }
1554
1555 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001556 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001557 if (str)
1558 lua_pushstring(L, "");
1559 else
1560 lua_pushnil(L);
1561 return 1;
1562 }
1563
1564 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001565 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001566 return 1;
1567}
1568
1569__LJMP static int hlua_map_lookup(struct lua_State *L)
1570{
1571 return _hlua_map_lookup(L, 0);
1572}
1573
1574__LJMP static int hlua_map_slookup(struct lua_State *L)
1575{
1576 return _hlua_map_lookup(L, 1);
1577}
1578
1579/*
1580 *
1581 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001582 * Class Socket
1583 *
1584 *
1585 */
1586
1587__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1588{
1589 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1590}
1591
1592/* This function is the handler called for each I/O on the established
1593 * connection. It is used for notify space avalaible to send or data
1594 * received.
1595 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001596static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001597{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001598 struct stream_interface *si = appctx->owner;
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001599 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001600
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001601 /* If the connection object is not avalaible, close all the
1602 * streams and wakeup everithing waiting for.
1603 */
1604 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001605 si_shutw(si);
1606 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001607 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001608 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1609 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001610 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001611 }
1612
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001613 /* If we cant write, wakeup the pending write signals. */
1614 if (channel_output_closed(si_ic(si)))
1615 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1616
1617 /* If we cant read, wakeup the pending read signals. */
1618 if (channel_input_closed(si_oc(si)))
1619 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1620
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001621 /* if the connection is not estabkished, inform the stream that we want
1622 * to be notified whenever the connection completes.
1623 */
1624 if (!(c->flags & CO_FL_CONNECTED)) {
1625 si_applet_cant_get(si);
1626 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001627 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001628 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001629
1630 /* This function is called after the connect. */
1631 appctx->ctx.hlua.connected = 1;
1632
1633 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001634 if (channel_may_recv(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001635 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1636
1637 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001638 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001639 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1640}
1641
Willy Tarreau87b09662015-04-03 00:22:06 +02001642/* This function is called when the "struct stream" is destroyed.
1643 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001644 * Wake all the pending signals.
1645 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001646static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001647{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001648 /* Remove my link in the original object. */
1649 if (appctx->ctx.hlua.socket)
1650 appctx->ctx.hlua.socket->s = NULL;
1651
1652 /* Wake all the task waiting for me. */
1653 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1654 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1655}
1656
1657/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001658 * uses this object. If the stream does not exists, just quit.
1659 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001660 * pending signal can rest in the read and write lists. destroy
1661 * it.
1662 */
1663__LJMP static int hlua_socket_gc(lua_State *L)
1664{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001665 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001666 struct appctx *appctx;
1667
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001668 MAY_LJMP(check_args(L, 1, "__gc"));
1669
1670 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001671 if (!socket->s)
1672 return 0;
1673
Willy Tarreau87b09662015-04-03 00:22:06 +02001674 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001675 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaue7dff022015-04-03 01:14:29 +02001676 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001677 socket->s = NULL;
1678 appctx->ctx.hlua.socket = NULL;
1679
1680 return 0;
1681}
1682
1683/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001684 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001685 */
1686__LJMP static int hlua_socket_close(lua_State *L)
1687{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001688 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001689 struct appctx *appctx;
1690
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001691 MAY_LJMP(check_args(L, 1, "close"));
1692
1693 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001694 if (!socket->s)
1695 return 0;
1696
Willy Tarreau87b09662015-04-03 00:22:06 +02001697 /* Close the stream and remove the associated stop task. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02001698 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001699 appctx = objt_appctx(socket->s->si[0].end);
1700 appctx->ctx.hlua.socket = NULL;
1701 socket->s = NULL;
1702
1703 return 0;
1704}
1705
1706/* This Lua function assumes that the stack contain three parameters.
1707 * 1 - USERDATA containing a struct socket
1708 * 2 - INTEGER with values of the macro defined below
1709 * If the integer is -1, we must read at most one line.
1710 * If the integer is -2, we ust read all the data until the
1711 * end of the stream.
1712 * If the integer is positive value, we must read a number of
1713 * bytes corresponding to this value.
1714 */
1715#define HLSR_READ_LINE (-1)
1716#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001717__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001718{
1719 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1720 int wanted = lua_tointeger(L, 2);
1721 struct hlua *hlua = hlua_gethlua(L);
1722 struct appctx *appctx;
1723 int len;
1724 int nblk;
1725 char *blk1;
1726 int len1;
1727 char *blk2;
1728 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001729 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001730 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001731
1732 /* Check if this lua stack is schedulable. */
1733 if (!hlua || !hlua->task)
1734 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1735 "'frontend', 'backend' or 'task'"));
1736
1737 /* check for connection closed. If some data where read, return it. */
1738 if (!socket->s)
1739 goto connection_closed;
1740
Willy Tarreau94aa6172015-03-13 14:19:06 +01001741 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001742 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001743 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001744 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001745 if (nblk < 0) /* Connection close. */
1746 goto connection_closed;
1747 if (nblk == 0) /* No data avalaible. */
1748 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001749
1750 /* remove final \r\n. */
1751 if (nblk == 1) {
1752 if (blk1[len1-1] == '\n') {
1753 len1--;
1754 skip_at_end++;
1755 if (blk1[len1-1] == '\r') {
1756 len1--;
1757 skip_at_end++;
1758 }
1759 }
1760 }
1761 else {
1762 if (blk2[len2-1] == '\n') {
1763 len2--;
1764 skip_at_end++;
1765 if (blk2[len2-1] == '\r') {
1766 len2--;
1767 skip_at_end++;
1768 }
1769 }
1770 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001771 }
1772
1773 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001774 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001775 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001776 if (nblk < 0) /* Connection close. */
1777 goto connection_closed;
1778 if (nblk == 0) /* No data avalaible. */
1779 goto connection_empty;
1780 }
1781
1782 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001783 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001784 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001785 if (nblk < 0) /* Connection close. */
1786 goto connection_closed;
1787 if (nblk == 0) /* No data avalaible. */
1788 goto connection_empty;
1789
1790 if (len1 > wanted) {
1791 nblk = 1;
1792 len1 = wanted;
1793 } if (nblk == 2 && len1 + len2 > wanted)
1794 len2 = wanted - len1;
1795 }
1796
1797 len = len1;
1798
1799 luaL_addlstring(&socket->b, blk1, len1);
1800 if (nblk == 2) {
1801 len += len2;
1802 luaL_addlstring(&socket->b, blk2, len2);
1803 }
1804
1805 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001806 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001807
1808 /* Don't wait anything. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001809 stream_int_notify(&socket->s->si[0]);
1810 stream_int_update_applet(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001811
1812 /* If the pattern reclaim to read all the data
1813 * in the connection, got out.
1814 */
1815 if (wanted == HLSR_READ_ALL)
1816 goto connection_empty;
1817 else if (wanted >= 0 && len < wanted)
1818 goto connection_empty;
1819
1820 /* Return result. */
1821 luaL_pushresult(&socket->b);
1822 return 1;
1823
1824connection_closed:
1825
1826 /* If the buffer containds data. */
1827 if (socket->b.n > 0) {
1828 luaL_pushresult(&socket->b);
1829 return 1;
1830 }
1831 lua_pushnil(L);
1832 lua_pushstring(L, "connection closed.");
1833 return 2;
1834
1835connection_empty:
1836
1837 appctx = objt_appctx(socket->s->si[0].end);
1838 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1839 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001840 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001841 return 0;
1842}
1843
1844/* This Lus function gets two parameters. The first one can be string
1845 * or a number. If the string is "*l", the user require one line. If
1846 * the string is "*a", the user require all the content of the stream.
1847 * If the value is a number, the user require a number of bytes equal
1848 * to the value. The default value is "*l" (a line).
1849 *
1850 * This paraeter with a variable type is converted in integer. This
1851 * integer takes this values:
1852 * -1 : read a line
1853 * -2 : read all the stream
1854 * >0 : amount if bytes.
1855 *
1856 * The second parameter is optinal. It contains a string that must be
1857 * concatenated with the read data.
1858 */
1859__LJMP static int hlua_socket_receive(struct lua_State *L)
1860{
1861 int wanted = HLSR_READ_LINE;
1862 const char *pattern;
1863 int type;
1864 char *error;
1865 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001866 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001867
1868 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1869 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1870
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001871 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001872
1873 /* check for pattern. */
1874 if (lua_gettop(L) >= 2) {
1875 type = lua_type(L, 2);
1876 if (type == LUA_TSTRING) {
1877 pattern = lua_tostring(L, 2);
1878 if (strcmp(pattern, "*a") == 0)
1879 wanted = HLSR_READ_ALL;
1880 else if (strcmp(pattern, "*l") == 0)
1881 wanted = HLSR_READ_LINE;
1882 else {
1883 wanted = strtoll(pattern, &error, 10);
1884 if (*error != '\0')
1885 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1886 }
1887 }
1888 else if (type == LUA_TNUMBER) {
1889 wanted = lua_tointeger(L, 2);
1890 if (wanted < 0)
1891 WILL_LJMP(luaL_error(L, "Unsupported size."));
1892 }
1893 }
1894
1895 /* Set pattern. */
1896 lua_pushinteger(L, wanted);
1897 lua_replace(L, 2);
1898
1899 /* init bufffer, and fiil it wih prefix. */
1900 luaL_buffinit(L, &socket->b);
1901
1902 /* Check prefix. */
1903 if (lua_gettop(L) >= 3) {
1904 if (lua_type(L, 3) != LUA_TSTRING)
1905 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1906 pattern = lua_tolstring(L, 3, &len);
1907 luaL_addlstring(&socket->b, pattern, len);
1908 }
1909
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001910 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001911}
1912
1913/* Write the Lua input string in the output buffer.
1914 * This fucntion returns a yield if no space are available.
1915 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001916static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001917{
1918 struct hlua_socket *socket;
1919 struct hlua *hlua = hlua_gethlua(L);
1920 struct appctx *appctx;
1921 size_t buf_len;
1922 const char *buf;
1923 int len;
1924 int send_len;
1925 int sent;
1926
1927 /* Check if this lua stack is schedulable. */
1928 if (!hlua || !hlua->task)
1929 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1930 "'frontend', 'backend' or 'task'"));
1931
1932 /* Get object */
1933 socket = MAY_LJMP(hlua_checksocket(L, 1));
1934 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001935 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001936
1937 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001938 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001939 lua_pushinteger(L, -1);
1940 return 1;
1941 }
1942
1943 /* Update the input buffer data. */
1944 buf += sent;
1945 send_len = buf_len - sent;
1946
1947 /* All the data are sent. */
1948 if (sent >= buf_len)
1949 return 1; /* Implicitly return the length sent. */
1950
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001951 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1952 * the request buffer if its not required.
1953 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001954 if (socket->s->req.buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02001955 if (!stream_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001956 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001957 goto hlua_socket_write_yield_return;
1958 }
1959 }
1960
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001961 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001962 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001963 if (len <= 0)
1964 goto hlua_socket_write_yield_return;
1965
1966 /* send data */
1967 if (len < send_len)
1968 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001969 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001970
1971 /* "Not enough space" (-1), "Buffer too little to contain
1972 * the data" (-2) are not expected because the available length
1973 * is tested.
1974 * Other unknown error are also not expected.
1975 */
1976 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001977 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001978 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001979
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001980 MAY_LJMP(hlua_socket_close(L));
1981 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001982 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001983 return 1;
1984 }
1985
1986 /* update buffers. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001987 stream_int_notify(&socket->s->si[0]);
1988 stream_int_update_applet(&socket->s->si[0]);
1989
Willy Tarreau94aa6172015-03-13 14:19:06 +01001990 socket->s->req.rex = TICK_ETERNITY;
1991 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001992
1993 /* Update length sent. */
1994 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001995 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001996
1997 /* All the data buffer is sent ? */
1998 if (sent + len >= buf_len)
1999 return 1;
2000
2001hlua_socket_write_yield_return:
2002 appctx = objt_appctx(socket->s->si[0].end);
2003 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2004 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002005 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002006 return 0;
2007}
2008
2009/* This function initiate the send of data. It just check the input
2010 * parameters and push an integer in the Lua stack that contain the
2011 * amount of data writed in the buffer. This is used by the function
2012 * "hlua_socket_write_yield" that can yield.
2013 *
2014 * The Lua function gets between 3 and 4 parameters. The first one is
2015 * the associated object. The second is a string buffer. The third is
2016 * a facultative integer that represents where is the buffer position
2017 * of the start of the data that can send. The first byte is the
2018 * position "1". The default value is "1". The fourth argument is a
2019 * facultative integer that represents where is the buffer position
2020 * of the end of the data that can send. The default is the last byte.
2021 */
2022static int hlua_socket_send(struct lua_State *L)
2023{
2024 int i;
2025 int j;
2026 const char *buf;
2027 size_t buf_len;
2028
2029 /* Check number of arguments. */
2030 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2031 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2032
2033 /* Get the string. */
2034 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2035
2036 /* Get and check j. */
2037 if (lua_gettop(L) == 4) {
2038 j = MAY_LJMP(luaL_checkinteger(L, 4));
2039 if (j < 0)
2040 j = buf_len + j + 1;
2041 if (j > buf_len)
2042 j = buf_len + 1;
2043 lua_pop(L, 1);
2044 }
2045 else
2046 j = buf_len;
2047
2048 /* Get and check i. */
2049 if (lua_gettop(L) == 3) {
2050 i = MAY_LJMP(luaL_checkinteger(L, 3));
2051 if (i < 0)
2052 i = buf_len + i + 1;
2053 if (i > buf_len)
2054 i = buf_len + 1;
2055 lua_pop(L, 1);
2056 } else
2057 i = 1;
2058
2059 /* Check bth i and j. */
2060 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002061 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002062 return 1;
2063 }
2064 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002065 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002066 return 1;
2067 }
2068 if (i == 0)
2069 i = 1;
2070 if (j == 0)
2071 j = 1;
2072
2073 /* Pop the string. */
2074 lua_pop(L, 1);
2075
2076 /* Update the buffer length. */
2077 buf += i - 1;
2078 buf_len = j - i + 1;
2079 lua_pushlstring(L, buf, buf_len);
2080
2081 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002082 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002083
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002084 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002085}
2086
Willy Tarreau22b0a682015-06-17 19:43:49 +02002087#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002088__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2089{
2090 static char buffer[SOCKET_INFO_MAX_LEN];
2091 int ret;
2092 int len;
2093 char *p;
2094
2095 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2096 if (ret <= 0) {
2097 lua_pushnil(L);
2098 return 1;
2099 }
2100
2101 if (ret == AF_UNIX) {
2102 lua_pushstring(L, buffer+1);
2103 return 1;
2104 }
2105 else if (ret == AF_INET6) {
2106 buffer[0] = '[';
2107 len = strlen(buffer);
2108 buffer[len] = ']';
2109 len++;
2110 buffer[len] = ':';
2111 len++;
2112 p = buffer;
2113 }
2114 else if (ret == AF_INET) {
2115 p = buffer + 1;
2116 len = strlen(p);
2117 p[len] = ':';
2118 len++;
2119 }
2120 else {
2121 lua_pushnil(L);
2122 return 1;
2123 }
2124
2125 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2126 lua_pushnil(L);
2127 return 1;
2128 }
2129
2130 lua_pushstring(L, p);
2131 return 1;
2132}
2133
2134/* Returns information about the peer of the connection. */
2135__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2136{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002137 struct hlua_socket *socket;
2138 struct connection *conn;
2139
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002140 MAY_LJMP(check_args(L, 1, "getpeername"));
2141
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002142 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002143
2144 /* Check if the tcp object is avalaible. */
2145 if (!socket->s) {
2146 lua_pushnil(L);
2147 return 1;
2148 }
2149
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002150 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002151 if (!conn) {
2152 lua_pushnil(L);
2153 return 1;
2154 }
2155
2156 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
2157 unsigned int salen = sizeof(conn->addr.to);
2158 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
2159 lua_pushnil(L);
2160 return 1;
2161 }
2162 conn->flags |= CO_FL_ADDR_TO_SET;
2163 }
2164
2165 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2166}
2167
2168/* Returns information about my connection side. */
2169static int hlua_socket_getsockname(struct lua_State *L)
2170{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002171 struct hlua_socket *socket;
2172 struct connection *conn;
2173
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002174 MAY_LJMP(check_args(L, 1, "getsockname"));
2175
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002176 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002177
2178 /* Check if the tcp object is avalaible. */
2179 if (!socket->s) {
2180 lua_pushnil(L);
2181 return 1;
2182 }
2183
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002184 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002185 if (!conn) {
2186 lua_pushnil(L);
2187 return 1;
2188 }
2189
2190 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
2191 unsigned int salen = sizeof(conn->addr.from);
2192 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
2193 lua_pushnil(L);
2194 return 1;
2195 }
2196 conn->flags |= CO_FL_ADDR_FROM_SET;
2197 }
2198
2199 return hlua_socket_info(L, &conn->addr.from);
2200}
2201
2202/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002203static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002204 .obj_type = OBJ_TYPE_APPLET,
2205 .name = "<LUA_TCP>",
2206 .fct = hlua_socket_handler,
2207 .release = hlua_socket_release,
2208};
2209
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002210__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002211{
2212 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2213 struct hlua *hlua = hlua_gethlua(L);
2214 struct appctx *appctx;
2215
2216 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002217 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002218 lua_pushnil(L);
2219 lua_pushstring(L, "Can't connect");
2220 return 2;
2221 }
2222
2223 appctx = objt_appctx(socket->s->si[0].end);
2224
2225 /* Check for connection established. */
2226 if (appctx->ctx.hlua.connected) {
2227 lua_pushinteger(L, 1);
2228 return 1;
2229 }
2230
2231 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2232 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002233 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002234 return 0;
2235}
2236
2237/* This function fail or initite the connection. */
2238__LJMP static int hlua_socket_connect(struct lua_State *L)
2239{
2240 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002241 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002242 const char *ip;
2243 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002244 struct hlua *hlua;
2245 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002246 int low, high;
2247 struct sockaddr_storage *addr;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002248
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002249 if (lua_gettop(L) < 2)
2250 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002251
2252 /* Get args. */
2253 socket = MAY_LJMP(hlua_checksocket(L, 1));
2254 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002255 if (lua_gettop(L) >= 3)
2256 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002257
Willy Tarreau973a5422015-08-05 21:47:23 +02002258 conn = si_alloc_conn(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002259 if (!conn)
2260 WILL_LJMP(luaL_error(L, "connect: internal error"));
2261
Willy Tarreau3adac082015-09-26 17:51:09 +02002262 /* needed for the connection not to be closed */
2263 conn->target = socket->s->target;
2264
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002265 /* Parse ip address. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002266 addr = str2sa_range(ip, &low, &high, NULL, NULL, NULL, 0);
2267 if (!addr)
2268 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
2269 if (low != high)
2270 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
2271 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002272
2273 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002274 if (low == 0) {
2275 if (conn->addr.to.ss_family == AF_INET) {
2276 if (port == -1)
2277 WILL_LJMP(luaL_error(L, "connect: port missing"));
2278 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2279 } else if (conn->addr.to.ss_family == AF_INET6) {
2280 if (port == -1)
2281 WILL_LJMP(luaL_error(L, "connect: port missing"));
2282 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2283 }
2284 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002285
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002286 hlua = hlua_gethlua(L);
2287 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002288
2289 /* inform the stream that we want to be notified whenever the
2290 * connection completes.
2291 */
2292 si_applet_cant_get(&socket->s->si[0]);
2293 si_applet_cant_put(&socket->s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002294 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002295
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002296 hlua->flags |= HLUA_MUST_GC;
2297
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002298 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2299 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002300 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002301
2302 return 0;
2303}
2304
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002305#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002306__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2307{
2308 struct hlua_socket *socket;
2309
2310 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2311 socket = MAY_LJMP(hlua_checksocket(L, 1));
2312 socket->s->target = &socket_ssl.obj_type;
2313 return MAY_LJMP(hlua_socket_connect(L));
2314}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002315#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002316
2317__LJMP static int hlua_socket_setoption(struct lua_State *L)
2318{
2319 return 0;
2320}
2321
2322__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2323{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002324 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002325 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002326
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002327 MAY_LJMP(check_args(L, 2, "settimeout"));
2328
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002329 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002330 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002331
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002332 socket->s->req.rto = tmout;
2333 socket->s->req.wto = tmout;
2334 socket->s->res.rto = tmout;
2335 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002336
2337 return 0;
2338}
2339
2340__LJMP static int hlua_socket_new(lua_State *L)
2341{
2342 struct hlua_socket *socket;
2343 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002344 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002345 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002346 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002347
2348 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002349 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002350 hlua_pusherror(L, "socket: full stack");
2351 goto out_fail_conf;
2352 }
2353
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002354 /* Create the object: obj[0] = userdata. */
2355 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002356 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002357 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002358 memset(socket, 0, sizeof(*socket));
2359
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002360 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002361 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002362 hlua_pusherror(L, "socket: uninitialized pools.");
2363 goto out_fail_conf;
2364 }
2365
Willy Tarreau87b09662015-04-03 00:22:06 +02002366 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002367 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2368 lua_setmetatable(L, -2);
2369
Willy Tarreaud420a972015-04-06 00:39:18 +02002370 /* Create the applet context */
2371 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002372 if (!appctx) {
2373 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002374 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002375 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002376
Willy Tarreaud420a972015-04-06 00:39:18 +02002377 appctx->ctx.hlua.socket = socket;
2378 appctx->ctx.hlua.connected = 0;
2379 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2380 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002381
Willy Tarreaud420a972015-04-06 00:39:18 +02002382 /* Now create a session, task and stream for this applet */
2383 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2384 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002385 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002386 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002387 }
2388
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002389 task = task_new();
2390 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002391 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002392 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002393 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002394 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002395
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002396 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002397 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002398 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002399 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002400 }
2401
Willy Tarreaud420a972015-04-06 00:39:18 +02002402 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002403 socket->s = strm;
2404 strm->hlua.T = NULL;
2405 strm->hlua.Tref = LUA_REFNIL;
2406 strm->hlua.Mref = LUA_REFNIL;
2407 strm->hlua.nargs = 0;
2408 strm->hlua.flags = 0;
2409 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002410
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002411 /* Configure "right" stream interface. this "si" is used to connect
2412 * and retrieve data from the server. The connection is initialized
2413 * with the "struct server".
2414 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002415 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002416
2417 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002418 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2419 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002420
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002421 /* Update statistics counters. */
2422 socket_proxy.feconn++; /* beconn will be increased later */
2423 jobs++;
2424 totalconn++;
2425
2426 /* Return yield waiting for connection. */
2427 return 1;
2428
Willy Tarreaud420a972015-04-06 00:39:18 +02002429 out_fail_stream:
2430 task_free(task);
2431 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002432 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002433 out_fail_sess:
2434 appctx_free(appctx);
2435 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002436 WILL_LJMP(lua_error(L));
2437 return 0;
2438}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002439
2440/*
2441 *
2442 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002443 * Class Channel
2444 *
2445 *
2446 */
2447
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002448/* The state between the channel data and the HTTP parser state can be
2449 * unconsistent, so reset the parser and call it again. Warning, this
2450 * action not revalidate the request and not send a 400 if the modified
2451 * resuest is not valid.
2452 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002453 * This function never fails. The direction is set using dir, which equals
2454 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002455 */
2456static void hlua_resynchonize_proto(struct stream *stream, int dir)
2457{
2458 /* Protocol HTTP. */
2459 if (stream->be->mode == PR_MODE_HTTP) {
2460
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002461 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002462 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002463 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002464 http_txn_reset_res(stream->txn);
2465
2466 if (stream->txn->hdr_idx.v)
2467 hdr_idx_init(&stream->txn->hdr_idx);
2468
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002469 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002470 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002471 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002472 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2473 }
2474}
2475
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002476/* Check the protocole integrity after the Lua manipulations. Close the stream
2477 * and returns 0 if fails, otherwise returns 1. The direction is set using dir,
2478 * which equals either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002479 */
2480static int hlua_check_proto(struct stream *stream, int dir)
2481{
2482 const struct chunk msg = { .len = 0 };
2483
Willy Tarreau9af89f72015-09-26 11:50:08 +02002484 /* Protocol HTTP. The message parsing state must match the request or
2485 * response state. The problem that may happen is that Lua modifies
2486 * the request or response message *after* it was parsed, and corrupted
2487 * it so that it could not be processed anymore. We just need to verify
2488 * if the parser is still expected to run or not.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002489 */
2490 if (stream->be->mode == PR_MODE_HTTP) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002491 if (dir == SMP_OPT_DIR_REQ &&
Willy Tarreau9af89f72015-09-26 11:50:08 +02002492 !(stream->req.analysers & AN_REQ_WAIT_HTTP) &&
2493 stream->txn->req.msg_state < HTTP_MSG_BODY) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002494 stream_int_retnclose(&stream->si[0], &msg);
2495 return 0;
2496 }
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002497 else if (dir == SMP_OPT_DIR_RES &&
Willy Tarreau9af89f72015-09-26 11:50:08 +02002498 !(stream->res.analysers & AN_RES_WAIT_HTTP) &&
2499 stream->txn->rsp.msg_state < HTTP_MSG_BODY) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002500 stream_int_retnclose(&stream->si[0], &msg);
2501 return 0;
2502 }
2503 }
2504 return 1;
2505}
2506
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002507/* Returns the struct hlua_channel join to the class channel in the
2508 * stack entry "ud" or throws an argument error.
2509 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002510__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002511{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002512 return (struct channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002513}
2514
Willy Tarreau47860ed2015-03-10 14:07:50 +01002515/* Pushes the channel onto the top of the stack. If the stask does not have a
2516 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002517 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002518static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002519{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002520 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002521 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002522 return 0;
2523
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002524 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002525 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002526 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002527
2528 /* Pop a class sesison metatable and affect it to the userdata. */
2529 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2530 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002531 return 1;
2532}
2533
2534/* Duplicate all the data present in the input channel and put it
2535 * in a string LUA variables. Returns -1 and push a nil value in
2536 * the stack if the channel is closed and all the data are consumed,
2537 * returns 0 if no data are available, otherwise it returns the length
2538 * of the builded string.
2539 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002540static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002541{
2542 char *blk1;
2543 char *blk2;
2544 int len1;
2545 int len2;
2546 int ret;
2547 luaL_Buffer b;
2548
Willy Tarreau47860ed2015-03-10 14:07:50 +01002549 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002550 if (unlikely(ret == 0))
2551 return 0;
2552
2553 if (unlikely(ret < 0)) {
2554 lua_pushnil(L);
2555 return -1;
2556 }
2557
2558 luaL_buffinit(L, &b);
2559 luaL_addlstring(&b, blk1, len1);
2560 if (unlikely(ret == 2))
2561 luaL_addlstring(&b, blk2, len2);
2562 luaL_pushresult(&b);
2563
2564 if (unlikely(ret == 2))
2565 return len1 + len2;
2566 return len1;
2567}
2568
2569/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2570 * a yield. This function keep the data in the buffer.
2571 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002572__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002573{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002574 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002575
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002576 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2577
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002578 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002579 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002580 return 1;
2581}
2582
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002583/* Check arguments for the function "hlua_channel_dup_yield". */
2584__LJMP static int hlua_channel_dup(lua_State *L)
2585{
2586 MAY_LJMP(check_args(L, 1, "dup"));
2587 MAY_LJMP(hlua_checkchannel(L, 1));
2588 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2589}
2590
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002591/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2592 * a yield. This function consumes the data in the buffer. It returns
2593 * a string containing the data or a nil pointer if no data are available
2594 * and the channel is closed.
2595 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002596__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002597{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002598 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002599 int ret;
2600
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002601 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002602
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002603 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002604 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002605 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002606
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002607 if (unlikely(ret == -1))
2608 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002609
Willy Tarreau47860ed2015-03-10 14:07:50 +01002610 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002611 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002612 return 1;
2613}
2614
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002615/* Check arguments for the fucntion "hlua_channel_get_yield". */
2616__LJMP static int hlua_channel_get(lua_State *L)
2617{
2618 MAY_LJMP(check_args(L, 1, "get"));
2619 MAY_LJMP(hlua_checkchannel(L, 1));
2620 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2621}
2622
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002623/* This functions consumes and returns one line. If the channel is closed,
2624 * and the last data does not contains a final '\n', the data are returned
2625 * without the final '\n'. When no more data are avalaible, it returns nil
2626 * value.
2627 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002628__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002629{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002630 char *blk1;
2631 char *blk2;
2632 int len1;
2633 int len2;
2634 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002635 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002636 int ret;
2637 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002638
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002639 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2640
Willy Tarreau47860ed2015-03-10 14:07:50 +01002641 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002642 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002643 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002644
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002645 if (ret == -1) {
2646 lua_pushnil(L);
2647 return 1;
2648 }
2649
2650 luaL_buffinit(L, &b);
2651 luaL_addlstring(&b, blk1, len1);
2652 len = len1;
2653 if (unlikely(ret == 2)) {
2654 luaL_addlstring(&b, blk2, len2);
2655 len += len2;
2656 }
2657 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002658 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002659 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002660 return 1;
2661}
2662
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002663/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2664__LJMP static int hlua_channel_getline(lua_State *L)
2665{
2666 MAY_LJMP(check_args(L, 1, "getline"));
2667 MAY_LJMP(hlua_checkchannel(L, 1));
2668 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2669}
2670
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002671/* This function takes a string as input, and append it at the
2672 * input side of channel. If the data is too big, but a space
2673 * is probably available after sending some data, the function
2674 * yield. If the data is bigger than the buffer, or if the
2675 * channel is closed, it returns -1. otherwise, it returns the
2676 * amount of data writed.
2677 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002678__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002679{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002680 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002681 size_t len;
2682 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2683 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2684 int ret;
2685 int max;
2686
Willy Tarreau47860ed2015-03-10 14:07:50 +01002687 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002688 if (max > len - l)
2689 max = len - l;
2690
Willy Tarreau47860ed2015-03-10 14:07:50 +01002691 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002692 if (ret == -2 || ret == -3) {
2693 lua_pushinteger(L, -1);
2694 return 1;
2695 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002696 if (ret == -1) {
2697 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002698 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002699 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002700 l += ret;
2701 lua_pop(L, 1);
2702 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002703 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002704
Willy Tarreau47860ed2015-03-10 14:07:50 +01002705 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2706 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002707 /* There are no space avalaible, and the output buffer is empty.
2708 * in this case, we cannot add more data, so we cannot yield,
2709 * we return the amount of copyied data.
2710 */
2711 return 1;
2712 }
2713 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002714 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002715 return 1;
2716}
2717
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002718/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002719 * of the writed string, or -1 if the channel is closed or if the
2720 * buffer size is too little for the data.
2721 */
2722__LJMP static int hlua_channel_append(lua_State *L)
2723{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002724 size_t len;
2725
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002726 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002727 MAY_LJMP(hlua_checkchannel(L, 1));
2728 MAY_LJMP(luaL_checklstring(L, 2, &len));
2729 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002730 lua_pushinteger(L, 0);
2731
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002732 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002733}
2734
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002735/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002736 * his process by cleaning the buffer. The result is a replacement
2737 * of the current data. It returns the length of the writed string,
2738 * or -1 if the channel is closed or if the buffer size is too
2739 * little for the data.
2740 */
2741__LJMP static int hlua_channel_set(lua_State *L)
2742{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002743 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002744
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002745 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002746 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002747 lua_pushinteger(L, 0);
2748
Willy Tarreau47860ed2015-03-10 14:07:50 +01002749 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002750
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002751 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002752}
2753
2754/* Append data in the output side of the buffer. This data is immediatly
2755 * sent. The fcuntion returns the ammount of data writed. If the buffer
2756 * cannot contains the data, the function yield. The function returns -1
2757 * if the channel is closed.
2758 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002759__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002760{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002761 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002762 size_t len;
2763 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2764 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2765 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002766 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002767
Willy Tarreau47860ed2015-03-10 14:07:50 +01002768 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002769 lua_pushinteger(L, -1);
2770 return 1;
2771 }
2772
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002773 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2774 * the request buffer if its not required.
2775 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002776 if (chn->buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02002777 if (!stream_alloc_recv_buffer(chn)) {
Willy Tarreau47860ed2015-03-10 14:07:50 +01002778 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002779 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002780 }
2781 }
2782
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002783 /* the writed data will be immediatly sent, so we can check
2784 * the avalaible space without taking in account the reserve.
2785 * The reserve is guaranted for the processing of incoming
2786 * data, because the buffer will be flushed.
2787 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002788 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002789
2790 /* If there are no space avalaible, and the output buffer is empty.
2791 * in this case, we cannot add more data, so we cannot yield,
2792 * we return the amount of copyied data.
2793 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002794 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002795 return 1;
2796
2797 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002798 if (max > len - l)
2799 max = len - l;
2800
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002801 /* The buffer avalaible size may be not contiguous. This test
2802 * detects a non contiguous buffer and realign it.
2803 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002804 if (bi_space_for_replace(chn->buf) < max)
2805 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002806
2807 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002808 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002809
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002810 /* buffer replace considers that the input part is filled.
2811 * so, I must forward these new data in the output part.
2812 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002813 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002814
2815 l += max;
2816 lua_pop(L, 1);
2817 lua_pushinteger(L, l);
2818
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002819 /* If there are no space avalaible, and the output buffer is empty.
2820 * in this case, we cannot add more data, so we cannot yield,
2821 * we return the amount of copyied data.
2822 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002823 max = chn->buf->size - buffer_len(chn->buf);
2824 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002825 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002826
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002827 if (l < len) {
2828 /* If we are waiting for space in the response buffer, we
2829 * must set the flag WAKERESWR. This flag required the task
2830 * wake up if any activity is detected on the response buffer.
2831 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002832 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002833 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002834 else
2835 HLUA_SET_WAKEREQWR(hlua);
2836 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002837 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002838
2839 return 1;
2840}
2841
2842/* Just a wraper of "_hlua_channel_send". This wrapper permits
2843 * yield the LUA process, and resume it without checking the
2844 * input arguments.
2845 */
2846__LJMP static int hlua_channel_send(lua_State *L)
2847{
2848 MAY_LJMP(check_args(L, 2, "send"));
2849 lua_pushinteger(L, 0);
2850
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002851 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002852}
2853
2854/* This function forward and amount of butes. The data pass from
2855 * the input side of the buffer to the output side, and can be
2856 * forwarded. This function never fails.
2857 *
2858 * The Lua function takes an amount of bytes to be forwarded in
2859 * imput. It returns the number of bytes forwarded.
2860 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002861__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002862{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002863 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002864 int len;
2865 int l;
2866 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002867 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002868
2869 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2870 len = MAY_LJMP(luaL_checkinteger(L, 2));
2871 l = MAY_LJMP(luaL_checkinteger(L, -1));
2872
2873 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002874 if (max > chn->buf->i)
2875 max = chn->buf->i;
2876 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002877 l += max;
2878
2879 lua_pop(L, 1);
2880 lua_pushinteger(L, l);
2881
2882 /* Check if it miss bytes to forward. */
2883 if (l < len) {
2884 /* The the input channel or the output channel are closed, we
2885 * must return the amount of data forwarded.
2886 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002887 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002888 return 1;
2889
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002890 /* If we are waiting for space data in the response buffer, we
2891 * must set the flag WAKERESWR. This flag required the task
2892 * wake up if any activity is detected on the response buffer.
2893 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002894 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002895 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002896 else
2897 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002898
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002899 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002900 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002901 }
2902
2903 return 1;
2904}
2905
2906/* Just check the input and prepare the stack for the previous
2907 * function "hlua_channel_forward_yield"
2908 */
2909__LJMP static int hlua_channel_forward(lua_State *L)
2910{
2911 MAY_LJMP(check_args(L, 2, "forward"));
2912 MAY_LJMP(hlua_checkchannel(L, 1));
2913 MAY_LJMP(luaL_checkinteger(L, 2));
2914
2915 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002916 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002917}
2918
2919/* Just returns the number of bytes available in the input
2920 * side of the buffer. This function never fails.
2921 */
2922__LJMP static int hlua_channel_get_in_len(lua_State *L)
2923{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002924 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002925
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002926 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002927 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002928 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002929 return 1;
2930}
2931
2932/* Just returns the number of bytes available in the output
2933 * side of the buffer. This function never fails.
2934 */
2935__LJMP static int hlua_channel_get_out_len(lua_State *L)
2936{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002937 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002938
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002939 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002940 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002941 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002942 return 1;
2943}
2944
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002945/*
2946 *
2947 *
2948 * Class Fetches
2949 *
2950 *
2951 */
2952
2953/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002954 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002955 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002956__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002957{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002958 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002959}
2960
2961/* This function creates and push in the stack a fetch object according
2962 * with a current TXN.
2963 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002964static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002965{
Willy Tarreau7073c472015-04-06 11:15:40 +02002966 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002967
2968 /* Check stack size. */
2969 if (!lua_checkstack(L, 3))
2970 return 0;
2971
2972 /* Create the object: obj[0] = userdata.
2973 * Note that the base of the Fetches object is the
2974 * transaction object.
2975 */
2976 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002977 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002978 lua_rawseti(L, -2, 0);
2979
Willy Tarreau7073c472015-04-06 11:15:40 +02002980 hsmp->s = txn->s;
2981 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01002982 hsmp->dir = txn->dir;
Willy Tarreau7073c472015-04-06 11:15:40 +02002983 hsmp->stringsafe = stringsafe;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002984
2985 /* Pop a class sesison metatable and affect it to the userdata. */
2986 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2987 lua_setmetatable(L, -2);
2988
2989 return 1;
2990}
2991
2992/* This function is an LUA binding. It is called with each sample-fetch.
2993 * It uses closure argument to store the associated sample-fetch. It
2994 * returns only one argument or throws an error. An error is thrown
2995 * only if an error is encountered during the argument parsing. If
2996 * the "sample-fetch" function fails, nil is returned.
2997 */
2998__LJMP static int hlua_run_sample_fetch(lua_State *L)
2999{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003000 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003001 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003002 struct arg args[ARGM_NBARGS + 1];
3003 int i;
3004 struct sample smp;
3005
3006 /* Get closure arguments. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003007 f = (struct sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003008
3009 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003010 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003011
3012 /* Get extra arguments. */
3013 for (i = 0; i < lua_gettop(L) - 1; i++) {
3014 if (i >= ARGM_NBARGS)
3015 break;
3016 hlua_lua2arg(L, i + 2, &args[i]);
3017 }
3018 args[i].type = ARGT_STOP;
3019
3020 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003021 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003022
3023 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003024 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003025 lua_pushfstring(L, "error in arguments");
3026 WILL_LJMP(lua_error(L));
3027 }
3028
3029 /* Initialise the sample. */
3030 memset(&smp, 0, sizeof(smp));
3031
3032 /* Run the sample fetch process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02003033 smp.px = hsmp->p;
3034 smp.sess = hsmp->s->sess;
3035 smp.strm = hsmp->s;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003036 smp.opt = hsmp->dir & SMP_OPT_DIR;
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003037 if (!f->process(args, &smp, f->kw, f->private)) {
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003038 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003039 lua_pushstring(L, "");
3040 else
3041 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003042 return 1;
3043 }
3044
3045 /* Convert the returned sample in lua value. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003046 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003047 hlua_smp2lua_str(L, &smp);
3048 else
3049 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003050 return 1;
3051}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003052
3053/*
3054 *
3055 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003056 * Class Converters
3057 *
3058 *
3059 */
3060
3061/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003062 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003063 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003064__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003065{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003066 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003067}
3068
3069/* This function creates and push in the stack a Converters object
3070 * according with a current TXN.
3071 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003072static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003073{
Willy Tarreau7073c472015-04-06 11:15:40 +02003074 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003075
3076 /* Check stack size. */
3077 if (!lua_checkstack(L, 3))
3078 return 0;
3079
3080 /* Create the object: obj[0] = userdata.
3081 * Note that the base of the Converters object is the
3082 * same than the TXN object.
3083 */
3084 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003085 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003086 lua_rawseti(L, -2, 0);
3087
Willy Tarreau7073c472015-04-06 11:15:40 +02003088 hsmp->s = txn->s;
3089 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003090 hsmp->dir = txn->dir;
Willy Tarreau7073c472015-04-06 11:15:40 +02003091 hsmp->stringsafe = stringsafe;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003092
Willy Tarreau87b09662015-04-03 00:22:06 +02003093 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003094 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3095 lua_setmetatable(L, -2);
3096
3097 return 1;
3098}
3099
3100/* This function is an LUA binding. It is called with each converter.
3101 * It uses closure argument to store the associated converter. It
3102 * returns only one argument or throws an error. An error is thrown
3103 * only if an error is encountered during the argument parsing. If
3104 * the converter function function fails, nil is returned.
3105 */
3106__LJMP static int hlua_run_sample_conv(lua_State *L)
3107{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003108 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003109 struct sample_conv *conv;
3110 struct arg args[ARGM_NBARGS + 1];
3111 int i;
3112 struct sample smp;
3113
3114 /* Get closure arguments. */
3115 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
3116
3117 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003118 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003119
3120 /* Get extra arguments. */
3121 for (i = 0; i < lua_gettop(L) - 2; i++) {
3122 if (i >= ARGM_NBARGS)
3123 break;
3124 hlua_lua2arg(L, i + 3, &args[i]);
3125 }
3126 args[i].type = ARGT_STOP;
3127
3128 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003129 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003130
3131 /* Run the special args checker. */
3132 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3133 hlua_pusherror(L, "error in arguments");
3134 WILL_LJMP(lua_error(L));
3135 }
3136
3137 /* Initialise the sample. */
3138 if (!hlua_lua2smp(L, 2, &smp)) {
3139 hlua_pusherror(L, "error in the input argument");
3140 WILL_LJMP(lua_error(L));
3141 }
3142
3143 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003144 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003145 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003146 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003147 WILL_LJMP(lua_error(L));
3148 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003149 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3150 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003151 hlua_pusherror(L, "error during the input argument casting");
3152 WILL_LJMP(lua_error(L));
3153 }
3154
3155 /* Run the sample conversion process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02003156 smp.px = hsmp->p;
3157 smp.sess = hsmp->s->sess;
3158 smp.strm = hsmp->s;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003159 smp.opt = hsmp->dir & SMP_OPT_DIR;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003160 if (!conv->process(args, &smp, conv->private)) {
Willy Tarreauda5f1082015-04-06 11:17:13 +02003161 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003162 lua_pushstring(L, "");
3163 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003164 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003165 return 1;
3166 }
3167
3168 /* Convert the returned sample in lua value. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003169 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003170 hlua_smp2lua_str(L, &smp);
3171 else
3172 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003173 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003174}
3175
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003176/*
3177 *
3178 *
3179 * Class AppletTCP
3180 *
3181 *
3182 */
3183
3184/* Returns a struct hlua_txn if the stack entry "ud" is
3185 * a class stream, otherwise it throws an error.
3186 */
3187__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3188{
3189 return (struct hlua_appctx *)MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
3190}
3191
3192/* This function creates and push in the stack an Applet object
3193 * according with a current TXN.
3194 */
3195static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3196{
3197 struct hlua_appctx *appctx;
3198 struct stream_interface *si = ctx->owner;
3199 struct stream *s = si_strm(si);
3200 struct proxy *p = s->be;
3201
3202 /* Check stack size. */
3203 if (!lua_checkstack(L, 3))
3204 return 0;
3205
3206 /* Create the object: obj[0] = userdata.
3207 * Note that the base of the Converters object is the
3208 * same than the TXN object.
3209 */
3210 lua_newtable(L);
3211 appctx = lua_newuserdata(L, sizeof(*appctx));
3212 lua_rawseti(L, -2, 0);
3213 appctx->appctx = ctx;
3214 appctx->htxn.s = s;
3215 appctx->htxn.p = p;
3216
3217 /* Create the "f" field that contains a list of fetches. */
3218 lua_pushstring(L, "f");
3219 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3220 return 0;
3221 lua_settable(L, -3);
3222
3223 /* Create the "sf" field that contains a list of stringsafe fetches. */
3224 lua_pushstring(L, "sf");
3225 if (!hlua_fetches_new(L, &appctx->htxn, 1))
3226 return 0;
3227 lua_settable(L, -3);
3228
3229 /* Create the "c" field that contains a list of converters. */
3230 lua_pushstring(L, "c");
3231 if (!hlua_converters_new(L, &appctx->htxn, 0))
3232 return 0;
3233 lua_settable(L, -3);
3234
3235 /* Create the "sc" field that contains a list of stringsafe converters. */
3236 lua_pushstring(L, "sc");
3237 if (!hlua_converters_new(L, &appctx->htxn, 1))
3238 return 0;
3239 lua_settable(L, -3);
3240
3241 /* Pop a class stream metatable and affect it to the table. */
3242 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3243 lua_setmetatable(L, -2);
3244
3245 return 1;
3246}
3247
3248/* If expected data not yet available, it returns a yield. This function
3249 * consumes the data in the buffer. It returns a string containing the
3250 * data. This string can be empty.
3251 */
3252__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3253{
3254 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3255 struct stream_interface *si = appctx->appctx->owner;
3256 int ret;
3257 char *blk1;
3258 int len1;
3259 char *blk2;
3260 int len2;
3261
3262 /* Read the maximum amount of data avalaible. */
3263 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3264
3265 /* Data not yet avalaible. return yield. */
3266 if (ret == 0) {
3267 si_applet_cant_get(si);
3268 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3269 }
3270
3271 /* End of data: commit the total strings and return. */
3272 if (ret < 0) {
3273 luaL_pushresult(&appctx->b);
3274 return 1;
3275 }
3276
3277 /* Ensure that the block 2 length is usable. */
3278 if (ret == 1)
3279 len2 = 0;
3280
3281 /* dont check the max length read and dont check. */
3282 luaL_addlstring(&appctx->b, blk1, len1);
3283 luaL_addlstring(&appctx->b, blk2, len2);
3284
3285 /* Consume input channel output buffer data. */
3286 bo_skip(si_oc(si), len1 + len2);
3287 luaL_pushresult(&appctx->b);
3288 return 1;
3289}
3290
3291/* Check arguments for the fucntion "hlua_channel_get_yield". */
3292__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3293{
3294 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3295
3296 /* Initialise the string catenation. */
3297 luaL_buffinit(L, &appctx->b);
3298
3299 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3300}
3301
3302/* If expected data not yet available, it returns a yield. This function
3303 * consumes the data in the buffer. It returns a string containing the
3304 * data. This string can be empty.
3305 */
3306__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3307{
3308 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3309 struct stream_interface *si = appctx->appctx->owner;
3310 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3311 int ret;
3312 char *blk1;
3313 int len1;
3314 char *blk2;
3315 int len2;
3316
3317 /* Read the maximum amount of data avalaible. */
3318 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3319
3320 /* Data not yet avalaible. return yield. */
3321 if (ret == 0) {
3322 si_applet_cant_get(si);
3323 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3324 }
3325
3326 /* End of data: commit the total strings and return. */
3327 if (ret < 0) {
3328 luaL_pushresult(&appctx->b);
3329 return 1;
3330 }
3331
3332 /* Ensure that the block 2 length is usable. */
3333 if (ret == 1)
3334 len2 = 0;
3335
3336 if (len == -1) {
3337
3338 /* If len == -1, catenate all the data avalaile and
3339 * yield because we want to get all the data until
3340 * the end of data stream.
3341 */
3342 luaL_addlstring(&appctx->b, blk1, len1);
3343 luaL_addlstring(&appctx->b, blk2, len2);
3344 bo_skip(si_oc(si), len1 + len2);
3345 si_applet_cant_get(si);
3346 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3347
3348 } else {
3349
3350 /* Copy the fisrt block caping to the length required. */
3351 if (len1 > len)
3352 len1 = len;
3353 luaL_addlstring(&appctx->b, blk1, len1);
3354 len -= len1;
3355
3356 /* Copy the second block. */
3357 if (len2 > len)
3358 len2 = len;
3359 luaL_addlstring(&appctx->b, blk2, len2);
3360 len -= len2;
3361
3362 /* Consume input channel output buffer data. */
3363 bo_skip(si_oc(si), len1 + len2);
3364
3365 /* If we are no other data avalaible, yield waiting for new data. */
3366 if (len > 0) {
3367 lua_pushinteger(L, len);
3368 lua_replace(L, 2);
3369 si_applet_cant_get(si);
3370 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3371 }
3372
3373 /* return the result. */
3374 luaL_pushresult(&appctx->b);
3375 return 1;
3376 }
3377
3378 /* we never executes this */
3379 hlua_pusherror(L, "Lua: internal error");
3380 WILL_LJMP(lua_error(L));
3381 return 0;
3382}
3383
3384/* Check arguments for the fucntion "hlua_channel_get_yield". */
3385__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3386{
3387 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3388 int len = -1;
3389
3390 if (lua_gettop(L) > 2)
3391 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3392 if (lua_gettop(L) >= 2) {
3393 len = MAY_LJMP(luaL_checkinteger(L, 2));
3394 lua_pop(L, 1);
3395 }
3396
3397 /* Confirm or set the required length */
3398 lua_pushinteger(L, len);
3399
3400 /* Initialise the string catenation. */
3401 luaL_buffinit(L, &appctx->b);
3402
3403 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3404}
3405
3406/* Append data in the output side of the buffer. This data is immediatly
3407 * sent. The fcuntion returns the ammount of data writed. If the buffer
3408 * cannot contains the data, the function yield. The function returns -1
3409 * if the channel is closed.
3410 */
3411__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3412{
3413 size_t len;
3414 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3415 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3416 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3417 struct stream_interface *si = appctx->appctx->owner;
3418 struct channel *chn = si_ic(si);
3419 int max;
3420
3421 /* Get the max amount of data which can write as input in the channel. */
3422 max = channel_recv_max(chn);
3423 if (max > (len - l))
3424 max = len - l;
3425
3426 /* Copy data. */
3427 bi_putblk(chn, str + l, max);
3428
3429 /* update counters. */
3430 l += max;
3431 lua_pop(L, 1);
3432 lua_pushinteger(L, l);
3433
3434 /* If some data is not send, declares the situation to the
3435 * applet, and returns a yield.
3436 */
3437 if (l < len) {
3438 si_applet_cant_put(si);
3439 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3440 }
3441
3442 return 1;
3443}
3444
3445/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3446 * yield the LUA process, and resume it without checking the
3447 * input arguments.
3448 */
3449__LJMP static int hlua_applet_tcp_send(lua_State *L)
3450{
3451 MAY_LJMP(check_args(L, 2, "send"));
3452 lua_pushinteger(L, 0);
3453
3454 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3455}
3456
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003457/*
3458 *
3459 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003460 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003461 *
3462 *
3463 */
3464
3465/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003466 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003467 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003468__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003469{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003470 return (struct hlua_appctx *)MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003471}
3472
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003473/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003474 * according with a current TXN.
3475 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003476static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003477{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003478 struct hlua_appctx *appctx;
3479 struct stream_interface *si = ctx->owner;
3480 struct stream *s = si_strm(si);
3481 struct proxy *px = s->be;
3482 struct http_txn *txn = s->txn;
3483 const char *path;
3484 const char *end;
3485 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003486
3487 /* Check stack size. */
3488 if (!lua_checkstack(L, 3))
3489 return 0;
3490
3491 /* Create the object: obj[0] = userdata.
3492 * Note that the base of the Converters object is the
3493 * same than the TXN object.
3494 */
3495 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003496 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003497 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003498 appctx->appctx = ctx;
3499 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
3500 appctx->htxn.s = s;
3501 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003502
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003503 /* Create the "f" field that contains a list of fetches. */
3504 lua_pushstring(L, "f");
3505 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3506 return 0;
3507 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003508
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003509 /* Create the "sf" field that contains a list of stringsafe fetches. */
3510 lua_pushstring(L, "sf");
3511 if (!hlua_fetches_new(L, &appctx->htxn, 1))
3512 return 0;
3513 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003514
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003515 /* Create the "c" field that contains a list of converters. */
3516 lua_pushstring(L, "c");
3517 if (!hlua_converters_new(L, &appctx->htxn, 0))
3518 return 0;
3519 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003520
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003521 /* Create the "sc" field that contains a list of stringsafe converters. */
3522 lua_pushstring(L, "sc");
3523 if (!hlua_converters_new(L, &appctx->htxn, 1))
3524 return 0;
3525 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003526
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003527 /* Stores the request method. */
3528 lua_pushstring(L, "method");
3529 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3530 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003531
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003532 /* Stores the http version. */
3533 lua_pushstring(L, "version");
3534 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3535 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003536
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003537 /* Get path and qs */
3538 path = http_get_path(txn);
3539 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3540 p = path;
3541 while (p < end && *p != '?')
3542 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003543
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003544 /* Stores the request path. */
3545 lua_pushstring(L, "path");
3546 lua_pushlstring(L, path, p - path);
3547 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003548
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003549 /* Stores the query string. */
3550 lua_pushstring(L, "qs");
3551 if (*p == '?')
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003552 p++;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003553 lua_pushlstring(L, p, end - p);
3554 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003555
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003556 /* Stores the request path. */
3557 lua_pushstring(L, "length");
3558 lua_pushinteger(L, txn->req.body_len);
3559 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003560
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003561 /* Create an array of HTTP request headers. */
3562 lua_pushstring(L, "headers");
3563 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3564 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003565
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003566 /* Create an empty array of HTTP request headers. */
3567 lua_pushstring(L, "response");
3568 lua_newtable(L);
3569 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003570
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003571 /* Pop a class stream metatable and affect it to the table. */
3572 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3573 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003574
3575 return 1;
3576}
3577
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003578/* If expected data not yet available, it returns a yield. This function
3579 * consumes the data in the buffer. It returns a string containing the
3580 * data. This string can be empty.
3581 */
3582__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003583{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003584 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3585 struct stream_interface *si = appctx->appctx->owner;
3586 struct channel *chn = si_ic(si);
3587 int ret;
3588 char *blk1;
3589 int len1;
3590 char *blk2;
3591 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003592
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003593 /* Maybe we cant send a 100-continue ? */
3594 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3595 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3596 /* if ret == -2 or -3 the channel closed or the message si too
3597 * big for the buffers. We cant send anything. So, we ignoring
3598 * the error, considers that the 100-continue is sent, and try
3599 * to receive.
3600 * If ret is -1, we dont have room in the buffer, so we yield.
3601 */
3602 if (ret == -1) {
3603 si_applet_cant_put(si);
3604 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3605 }
3606 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3607 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003608
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003609 /* Check for the end of the data. */
3610 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
3611 luaL_pushresult(&appctx->b);
3612 return 1;
3613 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003614
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003615 /* Read the maximum amount of data avalaible. */
3616 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003617
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003618 /* Data not yet avalaible. return yield. */
3619 if (ret == 0) {
3620 si_applet_cant_get(si);
3621 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3622 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003623
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003624 /* End of data: commit the total strings and return. */
3625 if (ret < 0) {
3626 luaL_pushresult(&appctx->b);
3627 return 1;
3628 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003629
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003630 /* Ensure that the block 2 length is usable. */
3631 if (ret == 1)
3632 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003633
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003634 /* Copy the fisrt block caping to the length required. */
3635 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3636 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3637 luaL_addlstring(&appctx->b, blk1, len1);
3638 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003639
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003640 /* Copy the second block. */
3641 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3642 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3643 luaL_addlstring(&appctx->b, blk2, len2);
3644 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003645
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003646 /* Consume input channel output buffer data. */
3647 bo_skip(si_oc(si), len1 + len2);
3648 luaL_pushresult(&appctx->b);
3649 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003650}
3651
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003652/* Check arguments for the fucntion "hlua_channel_get_yield". */
3653__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003654{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003655 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003656
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003657 /* Initialise the string catenation. */
3658 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003659
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003660 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003661}
3662
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003663/* If expected data not yet available, it returns a yield. This function
3664 * consumes the data in the buffer. It returns a string containing the
3665 * data. This string can be empty.
3666 */
3667__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003668{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003669 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3670 struct stream_interface *si = appctx->appctx->owner;
3671 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3672 struct channel *chn = si_ic(si);
3673 int ret;
3674 char *blk1;
3675 int len1;
3676 char *blk2;
3677 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003678
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003679 /* Maybe we cant send a 100-continue ? */
3680 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3681 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3682 /* if ret == -2 or -3 the channel closed or the message si too
3683 * big for the buffers. We cant send anything. So, we ignoring
3684 * the error, considers that the 100-continue is sent, and try
3685 * to receive.
3686 * If ret is -1, we dont have room in the buffer, so we yield.
3687 */
3688 if (ret == -1) {
3689 si_applet_cant_put(si);
3690 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3691 }
3692 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3693 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003694
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003695 /* Read the maximum amount of data avalaible. */
3696 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003697
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003698 /* Data not yet avalaible. return yield. */
3699 if (ret == 0) {
3700 si_applet_cant_get(si);
3701 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3702 }
3703
3704 /* End of data: commit the total strings and return. */
3705 if (ret < 0) {
3706 luaL_pushresult(&appctx->b);
3707 return 1;
3708 }
3709
3710 /* Ensure that the block 2 length is usable. */
3711 if (ret == 1)
3712 len2 = 0;
3713
3714 /* Copy the fisrt block caping to the length required. */
3715 if (len1 > len)
3716 len1 = len;
3717 luaL_addlstring(&appctx->b, blk1, len1);
3718 len -= len1;
3719
3720 /* Copy the second block. */
3721 if (len2 > len)
3722 len2 = len;
3723 luaL_addlstring(&appctx->b, blk2, len2);
3724 len -= len2;
3725
3726 /* Consume input channel output buffer data. */
3727 bo_skip(si_oc(si), len1 + len2);
3728 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
3729 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
3730
3731 /* If we are no other data avalaible, yield waiting for new data. */
3732 if (len > 0) {
3733 lua_pushinteger(L, len);
3734 lua_replace(L, 2);
3735 si_applet_cant_get(si);
3736 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3737 }
3738
3739 /* return the result. */
3740 luaL_pushresult(&appctx->b);
3741 return 1;
3742}
3743
3744/* Check arguments for the fucntion "hlua_channel_get_yield". */
3745__LJMP static int hlua_applet_http_recv(lua_State *L)
3746{
3747 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3748 int len = -1;
3749
3750 /* Check arguments. */
3751 if (lua_gettop(L) > 2)
3752 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3753 if (lua_gettop(L) >= 2) {
3754 len = MAY_LJMP(luaL_checkinteger(L, 2));
3755 lua_pop(L, 1);
3756 }
3757
3758 /* Check the required length */
3759 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3760 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3761 lua_pushinteger(L, len);
3762
3763 /* Initialise the string catenation. */
3764 luaL_buffinit(L, &appctx->b);
3765
3766 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
3767}
3768
3769/* Append data in the output side of the buffer. This data is immediatly
3770 * sent. The fcuntion returns the ammount of data writed. If the buffer
3771 * cannot contains the data, the function yield. The function returns -1
3772 * if the channel is closed.
3773 */
3774__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
3775{
3776 size_t len;
3777 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3778 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3779 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3780 struct stream_interface *si = appctx->appctx->owner;
3781 struct channel *chn = si_ic(si);
3782 int max;
3783
3784 /* Get the max amount of data which can write as input in the channel. */
3785 max = channel_recv_max(chn);
3786 if (max > (len - l))
3787 max = len - l;
3788
3789 /* Copy data. */
3790 bi_putblk(chn, str + l, max);
3791
3792 /* update counters. */
3793 l += max;
3794 lua_pop(L, 1);
3795 lua_pushinteger(L, l);
3796
3797 /* If some data is not send, declares the situation to the
3798 * applet, and returns a yield.
3799 */
3800 if (l < len) {
3801 si_applet_cant_put(si);
3802 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
3803 }
3804
3805 return 1;
3806}
3807
3808/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
3809 * yield the LUA process, and resume it without checking the
3810 * input arguments.
3811 */
3812__LJMP static int hlua_applet_http_send(lua_State *L)
3813{
3814 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3815 size_t len;
3816 char hex[10];
3817
3818 MAY_LJMP(luaL_checklstring(L, 2, &len));
3819
3820 /* If transfer encoding chunked is selected, we surround the data
3821 * by chunk data.
3822 */
3823 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
3824 snprintf(hex, 9, "%x", (unsigned int)len);
3825 lua_pushfstring(L, "%s\r\n", hex);
3826 lua_insert(L, 2); /* swap the last 2 entries. */
3827 lua_pushstring(L, "\r\n");
3828 lua_concat(L, 3);
3829 }
3830
3831 /* This interger is used for followinf the amount of data sent. */
3832 lua_pushinteger(L, 0);
3833
3834 /* We want to send some data. Headers must be sent. */
3835 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
3836 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
3837 WILL_LJMP(lua_error(L));
3838 }
3839
3840 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
3841}
3842
3843__LJMP static int hlua_applet_http_addheader(lua_State *L)
3844{
3845 const char *name;
3846 int ret;
3847
3848 MAY_LJMP(hlua_checkapplet_http(L, 1));
3849 name = MAY_LJMP(luaL_checkstring(L, 2));
3850 MAY_LJMP(luaL_checkstring(L, 3));
3851
3852 /* Push in the stack the "response" entry. */
3853 ret = lua_getfield(L, 1, "response");
3854 if (ret != LUA_TTABLE) {
3855 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
3856 "is expected as an array. %s found", lua_typename(L, ret));
3857 WILL_LJMP(lua_error(L));
3858 }
3859
3860 /* check if the header is already registered if it is not
3861 * the case, register it.
3862 */
3863 ret = lua_getfield(L, -1, name);
3864 if (ret == LUA_TNIL) {
3865
3866 /* Entry not found. */
3867 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
3868
3869 /* Insert the new header name in the array in the top of the stack.
3870 * It left the new array in the top of the stack.
3871 */
3872 lua_newtable(L);
3873 lua_pushvalue(L, 2);
3874 lua_pushvalue(L, -2);
3875 lua_settable(L, -4);
3876
3877 } else if (ret != LUA_TTABLE) {
3878
3879 /* corruption error. */
3880 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
3881 "is expected as an array. %s found", name, lua_typename(L, ret));
3882 WILL_LJMP(lua_error(L));
3883 }
3884
3885 /* Now the top od thestack is an array of values. We push
3886 * the header value as new entry.
3887 */
3888 lua_pushvalue(L, 3);
3889 ret = lua_rawlen(L, -2);
3890 lua_rawseti(L, -2, ret + 1);
3891 lua_pushboolean(L, 1);
3892 return 1;
3893}
3894
3895__LJMP static int hlua_applet_http_status(lua_State *L)
3896{
3897 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3898 int status = MAY_LJMP(luaL_checkinteger(L, 2));
3899
3900 if (status < 100 || status > 599) {
3901 lua_pushboolean(L, 0);
3902 return 1;
3903 }
3904
3905 appctx->appctx->ctx.hlua_apphttp.status = status;
3906 lua_pushboolean(L, 1);
3907 return 1;
3908}
3909
3910/* We will build the status line and the headers of the HTTP response.
3911 * We will try send at once if its not possible, we give back the hand
3912 * waiting for more room.
3913 */
3914__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
3915{
3916 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3917 struct stream_interface *si = appctx->appctx->owner;
3918 struct channel *chn = si_ic(si);
3919 int ret;
3920 size_t len;
3921 const char *msg;
3922
3923 /* Get the message as the first argument on the stack. */
3924 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
3925
3926 /* Send the message at once. */
3927 ret = bi_putblk(chn, msg, len);
3928
3929 /* if ret == -2 or -3 the channel closed or the message si too
3930 * big for the buffers.
3931 */
3932 if (ret == -2 || ret == -3) {
3933 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
3934 WILL_LJMP(lua_error(L));
3935 }
3936
3937 /* If ret is -1, we dont have room in the buffer, so we yield. */
3938 if (ret == -1) {
3939 si_applet_cant_put(si);
3940 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
3941 }
3942
3943 /* Headers sent, set the flag. */
3944 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
3945 return 0;
3946}
3947
3948__LJMP static int hlua_applet_http_start_response(lua_State *L)
3949{
3950 struct chunk *tmp = get_trash_chunk();
3951 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3952 struct stream_interface *si = appctx->appctx->owner;
3953 struct stream *s = si_strm(si);
3954 struct http_txn *txn = s->txn;
3955 const char *name;
3956 const char *value;
3957 int id;
3958 int hdr_connection = 0;
3959 int hdr_contentlength = -1;
3960 int hdr_chunked = 0;
3961
3962 /* Use the same http version than the request. */
3963 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
3964 txn->req.flags & HTTP_MSGF_VER_11 ? '1' : '0',
3965 appctx->appctx->ctx.hlua_apphttp.status,
3966 get_reason(appctx->appctx->ctx.hlua_apphttp.status));
3967
3968 /* Get the array associated to the field "response" in the object AppletHTTP. */
3969 lua_pushvalue(L, 0);
3970 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
3971 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
3972 appctx->appctx->rule->arg.hlua_rule->fcn.name);
3973 WILL_LJMP(lua_error(L));
3974 }
3975
3976 /* Browse the list of headers. */
3977 lua_pushnil(L);
3978 while(lua_next(L, -2) != 0) {
3979
3980 /* We expect a string as -2. */
3981 if (lua_type(L, -2) != LUA_TSTRING) {
3982 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
3983 appctx->appctx->rule->arg.hlua_rule->fcn.name,
3984 lua_typename(L, lua_type(L, -2)));
3985 WILL_LJMP(lua_error(L));
3986 }
3987 name = lua_tostring(L, -2);
3988
3989 /* We expect an array as -1. */
3990 if (lua_type(L, -1) != LUA_TTABLE) {
3991 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
3992 appctx->appctx->rule->arg.hlua_rule->fcn.name,
3993 name,
3994 lua_typename(L, lua_type(L, -1)));
3995 WILL_LJMP(lua_error(L));
3996 }
3997
3998 /* Browse the table who is on the top of the stack. */
3999 lua_pushnil(L);
4000 while(lua_next(L, -2) != 0) {
4001
4002 /* We expect a number as -2. */
4003 if (lua_type(L, -2) != LUA_TNUMBER) {
4004 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4005 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4006 name,
4007 lua_typename(L, lua_type(L, -2)));
4008 WILL_LJMP(lua_error(L));
4009 }
4010 id = lua_tointeger(L, -2);
4011
4012 /* We expect a string as -2. */
4013 if (lua_type(L, -1) != LUA_TSTRING) {
4014 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4015 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4016 name, id,
4017 lua_typename(L, lua_type(L, -1)));
4018 WILL_LJMP(lua_error(L));
4019 }
4020 value = lua_tostring(L, -1);
4021
4022 /* Catenate a new header. */
4023 chunk_appendf(tmp, "%s: %s\r\n", name, value);
4024
4025 /* Protocol checks. */
4026
4027 /* Check if the header conneciton is present. */
4028 if (strcasecmp("connection", name) == 0)
4029 hdr_connection = 1;
4030
4031 /* Copy the header content length. The length conversion
4032 * is done without control. If it contains a ad value, this
4033 * is not our problem.
4034 */
4035 if (strcasecmp("content-length", name) == 0)
4036 hdr_contentlength = atoi(value);
4037
4038 /* Check if the client annouces a transfer-encoding chunked it self. */
4039 if (strcasecmp("transfer-encoding", name) == 0 &&
4040 strcasecmp("chunked", value) == 0)
4041 hdr_chunked = 1;
4042
4043 /* Remove the array from the stack, and get next element with a remaining string. */
4044 lua_pop(L, 1);
4045 }
4046
4047 /* Remove the array from the stack, and get next element with a remaining string. */
4048 lua_pop(L, 1);
4049 }
4050
4051 /* If the http protocol version is 1.1, we expect an header "connection" set
4052 * to "close" to be HAProxy/keeplive compliant. Otherwise, we expect nothing.
4053 * If the header conneciton is present, don't change it, if it is not present,
4054 * we must set.
4055 *
4056 * we set a "connection: close" header for ensuring that the keepalive will be
4057 * respected by haproxy. HAProcy considers that the application cloe the connection
4058 * and it keep the connection from the client open.
4059 */
4060 if (txn->req.flags & HTTP_MSGF_VER_11 && !hdr_connection)
4061 chunk_appendf(tmp, "Connection: close\r\n");
4062
4063 /* If we dont have a content-length set, we must announce a transfer enconding
4064 * chunked. This is required by haproxy for the keepalive compliance.
4065 * If the applet annouce a transfer-encoding chunked itslef, don't
4066 * do anything.
4067 */
4068 if (hdr_contentlength == -1 && hdr_chunked == 0) {
4069 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4070 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4071 }
4072
4073 /* Finalize headers. */
4074 chunk_appendf(tmp, "\r\n");
4075
4076 /* Remove the last entry and the array of headers */
4077 lua_pop(L, 2);
4078
4079 /* Push the headers block. */
4080 lua_pushlstring(L, tmp->str, tmp->len);
4081
4082 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4083}
4084
4085/*
4086 *
4087 *
4088 * Class HTTP
4089 *
4090 *
4091 */
4092
4093/* Returns a struct hlua_txn if the stack entry "ud" is
4094 * a class stream, otherwise it throws an error.
4095 */
4096__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4097{
4098 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
4099}
4100
4101/* This function creates and push in the stack a HTTP object
4102 * according with a current TXN.
4103 */
4104static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4105{
4106 struct hlua_txn *htxn;
4107
4108 /* Check stack size. */
4109 if (!lua_checkstack(L, 3))
4110 return 0;
4111
4112 /* Create the object: obj[0] = userdata.
4113 * Note that the base of the Converters object is the
4114 * same than the TXN object.
4115 */
4116 lua_newtable(L);
4117 htxn = lua_newuserdata(L, sizeof(*htxn));
4118 lua_rawseti(L, -2, 0);
4119
4120 htxn->s = txn->s;
4121 htxn->p = txn->p;
4122
4123 /* Pop a class stream metatable and affect it to the table. */
4124 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4125 lua_setmetatable(L, -2);
4126
4127 return 1;
4128}
4129
4130/* This function creates ans returns an array of HTTP headers.
4131 * This function does not fails. It is used as wrapper with the
4132 * 2 following functions.
4133 */
4134__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4135{
4136 const char *cur_ptr, *cur_next, *p;
4137 int old_idx, cur_idx;
4138 struct hdr_idx_elem *cur_hdr;
4139 const char *hn, *hv;
4140 int hnl, hvl;
4141 int type;
4142 const char *in;
4143 char *out;
4144 int len;
4145
4146 /* Create the table. */
4147 lua_newtable(L);
4148
4149 if (!htxn->s->txn)
4150 return 1;
4151
4152 /* Build array of headers. */
4153 old_idx = 0;
4154 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4155
4156 while (1) {
4157 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4158 if (!cur_idx)
4159 break;
4160 old_idx = cur_idx;
4161
4162 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4163 cur_ptr = cur_next;
4164 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4165
4166 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4167 * and the next header starts at cur_next. We'll check
4168 * this header in the list as well as against the default
4169 * rule.
4170 */
4171
4172 /* look for ': *'. */
4173 hn = cur_ptr;
4174 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4175 if (p >= cur_ptr+cur_hdr->len)
4176 continue;
4177 hnl = p - hn;
4178 p++;
4179 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4180 p++;
4181 if (p >= cur_ptr+cur_hdr->len)
4182 continue;
4183 hv = p;
4184 hvl = cur_ptr+cur_hdr->len-p;
4185
4186 /* Lowercase the key. Don't check the size of trash, it have
4187 * the size of one buffer and the input data contains in one
4188 * buffer.
4189 */
4190 out = trash.str;
4191 for (in=hn; in<hn+hnl; in++, out++)
4192 *out = tolower(*in);
4193 *out = '\0';
4194
4195 /* Check for existing entry:
4196 * assume that the table is on the top of the stack, and
4197 * push the key in the stack, the function lua_gettable()
4198 * perform the lookup.
4199 */
4200 lua_pushlstring(L, trash.str, hnl);
4201 lua_gettable(L, -2);
4202 type = lua_type(L, -1);
4203
4204 switch (type) {
4205 case LUA_TNIL:
4206 /* Table not found, create it. */
4207 lua_pop(L, 1); /* remove the nil value. */
4208 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4209 lua_newtable(L); /* create and push empty table. */
4210 lua_pushlstring(L, hv, hvl); /* push header value. */
4211 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4212 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4213 break;
4214
4215 case LUA_TTABLE:
4216 /* Entry found: push the value in the table. */
4217 len = lua_rawlen(L, -1);
4218 lua_pushlstring(L, hv, hvl); /* push header value. */
4219 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4220 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4221 break;
4222
4223 default:
4224 /* Other cases are errors. */
4225 hlua_pusherror(L, "internal error during the parsing of headers.");
4226 WILL_LJMP(lua_error(L));
4227 }
4228 }
4229
4230 return 1;
4231}
4232
4233__LJMP static int hlua_http_req_get_headers(lua_State *L)
4234{
4235 struct hlua_txn *htxn;
4236
4237 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4238 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4239
4240 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4241}
4242
4243__LJMP static int hlua_http_res_get_headers(lua_State *L)
4244{
4245 struct hlua_txn *htxn;
4246
4247 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4248 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4249
4250 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4251}
4252
4253/* This function replace full header, or just a value in
4254 * the request or in the response. It is a wrapper fir the
4255 * 4 following functions.
4256 */
4257__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4258 struct http_msg *msg, int action)
4259{
4260 size_t name_len;
4261 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4262 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4263 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4264 struct my_regex re;
4265
4266 if (!regex_comp(reg, &re, 1, 1, NULL))
4267 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4268
4269 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4270 regex_free(&re);
4271 return 0;
4272}
4273
4274__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4275{
4276 struct hlua_txn *htxn;
4277
4278 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4279 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4280
4281 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4282}
4283
4284__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4285{
4286 struct hlua_txn *htxn;
4287
4288 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4289 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4290
4291 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4292}
4293
4294__LJMP static int hlua_http_req_rep_val(lua_State *L)
4295{
4296 struct hlua_txn *htxn;
4297
4298 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4299 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4300
4301 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4302}
4303
4304__LJMP static int hlua_http_res_rep_val(lua_State *L)
4305{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004306 struct hlua_txn *htxn;
4307
4308 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4309 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4310
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004311 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004312}
4313
4314/* This function deletes all the occurences of an header.
4315 * It is a wrapper for the 2 following functions.
4316 */
4317__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4318{
4319 size_t len;
4320 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4321 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004322 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004323
4324 ctx.idx = 0;
4325 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4326 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4327 return 0;
4328}
4329
4330__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4331{
4332 struct hlua_txn *htxn;
4333
4334 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4335 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4336
Willy Tarreaueee5b512015-04-03 23:46:31 +02004337 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004338}
4339
4340__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4341{
4342 struct hlua_txn *htxn;
4343
4344 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4345 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4346
Willy Tarreaueee5b512015-04-03 23:46:31 +02004347 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004348}
4349
4350/* This function adds an header. It is a wrapper used by
4351 * the 2 following functions.
4352 */
4353__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4354{
4355 size_t name_len;
4356 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4357 size_t value_len;
4358 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4359 char *p;
4360
4361 /* Check length. */
4362 trash.len = value_len + name_len + 2;
4363 if (trash.len > trash.size)
4364 return 0;
4365
4366 /* Creates the header string. */
4367 p = trash.str;
4368 memcpy(p, name, name_len);
4369 p += name_len;
4370 *p = ':';
4371 p++;
4372 *p = ' ';
4373 p++;
4374 memcpy(p, value, value_len);
4375
Willy Tarreaueee5b512015-04-03 23:46:31 +02004376 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004377 trash.str, trash.len) != 0);
4378
4379 return 0;
4380}
4381
4382__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4383{
4384 struct hlua_txn *htxn;
4385
4386 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4387 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4388
Willy Tarreaueee5b512015-04-03 23:46:31 +02004389 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004390}
4391
4392__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4393{
4394 struct hlua_txn *htxn;
4395
4396 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4397 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4398
Willy Tarreaueee5b512015-04-03 23:46:31 +02004399 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004400}
4401
4402static int hlua_http_req_set_hdr(lua_State *L)
4403{
4404 struct hlua_txn *htxn;
4405
4406 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4407 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4408
Willy Tarreaueee5b512015-04-03 23:46:31 +02004409 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4410 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004411}
4412
4413static int hlua_http_res_set_hdr(lua_State *L)
4414{
4415 struct hlua_txn *htxn;
4416
4417 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4418 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4419
Willy Tarreaueee5b512015-04-03 23:46:31 +02004420 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4421 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004422}
4423
4424/* This function set the method. */
4425static int hlua_http_req_set_meth(lua_State *L)
4426{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004427 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004428 size_t name_len;
4429 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004430
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004431 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004432 return 1;
4433}
4434
4435/* This function set the method. */
4436static int hlua_http_req_set_path(lua_State *L)
4437{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004438 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004439 size_t name_len;
4440 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004441 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004442 return 1;
4443}
4444
4445/* This function set the query-string. */
4446static int hlua_http_req_set_query(lua_State *L)
4447{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004448 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004449 size_t name_len;
4450 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004451
4452 /* Check length. */
4453 if (name_len > trash.size - 1) {
4454 lua_pushboolean(L, 0);
4455 return 1;
4456 }
4457
4458 /* Add the mark question as prefix. */
4459 chunk_reset(&trash);
4460 trash.str[trash.len++] = '?';
4461 memcpy(trash.str + trash.len, name, name_len);
4462 trash.len += name_len;
4463
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004464 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004465 return 1;
4466}
4467
4468/* This function set the uri. */
4469static int hlua_http_req_set_uri(lua_State *L)
4470{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004471 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004472 size_t name_len;
4473 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004474
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004475 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004476 return 1;
4477}
4478
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004479/* This function set the response code. */
4480static int hlua_http_res_set_status(lua_State *L)
4481{
4482 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4483 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
4484
4485 http_set_status(code, htxn->s);
4486 return 0;
4487}
4488
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004489/*
4490 *
4491 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004492 * Class TXN
4493 *
4494 *
4495 */
4496
4497/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004498 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004499 */
4500__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
4501{
4502 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
4503}
4504
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004505__LJMP static int hlua_set_var(lua_State *L)
4506{
4507 struct hlua_txn *htxn;
4508 const char *name;
4509 size_t len;
4510 struct sample smp;
4511
4512 MAY_LJMP(check_args(L, 3, "set_var"));
4513
4514 /* It is useles to retrieve the stream, but this function
4515 * runs only in a stream context.
4516 */
4517 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4518 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4519
4520 /* Converts the third argument in a sample. */
4521 hlua_lua2smp(L, 3, &smp);
4522
4523 /* Store the sample in a variable. */
4524 vars_set_by_name(name, len, htxn->s, &smp);
4525 return 0;
4526}
4527
4528__LJMP static int hlua_get_var(lua_State *L)
4529{
4530 struct hlua_txn *htxn;
4531 const char *name;
4532 size_t len;
4533 struct sample smp;
4534
4535 MAY_LJMP(check_args(L, 2, "get_var"));
4536
4537 /* It is useles to retrieve the stream, but this function
4538 * runs only in a stream context.
4539 */
4540 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4541 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4542
4543 if (!vars_get_by_name(name, len, htxn->s, &smp)) {
4544 lua_pushnil(L);
4545 return 1;
4546 }
4547
4548 return hlua_smp2lua(L, &smp);
4549}
4550
Willy Tarreau59551662015-03-10 14:23:13 +01004551__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004552{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004553 struct hlua *hlua;
4554
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004555 MAY_LJMP(check_args(L, 2, "set_priv"));
4556
Willy Tarreau87b09662015-04-03 00:22:06 +02004557 /* It is useles to retrieve the stream, but this function
4558 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004559 */
4560 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004561 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004562
4563 /* Remove previous value. */
4564 if (hlua->Mref != -1)
4565 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
4566
4567 /* Get and store new value. */
4568 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4569 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4570
4571 return 0;
4572}
4573
Willy Tarreau59551662015-03-10 14:23:13 +01004574__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004575{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004576 struct hlua *hlua;
4577
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004578 MAY_LJMP(check_args(L, 1, "get_priv"));
4579
Willy Tarreau87b09662015-04-03 00:22:06 +02004580 /* It is useles to retrieve the stream, but this function
4581 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004582 */
4583 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004584 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004585
4586 /* Push configuration index in the stack. */
4587 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4588
4589 return 1;
4590}
4591
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004592/* Create stack entry containing a class TXN. This function
4593 * return 0 if the stack does not contains free slots,
4594 * otherwise it returns 1.
4595 */
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004596static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004597{
Willy Tarreaude491382015-04-06 11:04:28 +02004598 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004599
4600 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004601 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004602 return 0;
4603
4604 /* NOTE: The allocation never fails. The failure
4605 * throw an error, and the function never returns.
4606 * if the throw is not avalaible, the process is aborted.
4607 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004608 /* Create the object: obj[0] = userdata. */
4609 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02004610 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004611 lua_rawseti(L, -2, 0);
4612
Willy Tarreaude491382015-04-06 11:04:28 +02004613 htxn->s = s;
4614 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004615 htxn->dir = dir;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004616
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004617 /* Create the "f" field that contains a list of fetches. */
4618 lua_pushstring(L, "f");
Willy Tarreaude491382015-04-06 11:04:28 +02004619 if (!hlua_fetches_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004620 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004621 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004622
4623 /* Create the "sf" field that contains a list of stringsafe fetches. */
4624 lua_pushstring(L, "sf");
Willy Tarreaude491382015-04-06 11:04:28 +02004625 if (!hlua_fetches_new(L, htxn, 1))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004626 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004627 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004628
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004629 /* Create the "c" field that contains a list of converters. */
4630 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02004631 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004632 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004633 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004634
4635 /* Create the "sc" field that contains a list of stringsafe converters. */
4636 lua_pushstring(L, "sc");
Willy Tarreaude491382015-04-06 11:04:28 +02004637 if (!hlua_converters_new(L, htxn, 1))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004638 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004639 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004640
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004641 /* Create the "req" field that contains the request channel object. */
4642 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004643 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004644 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004645 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004646
4647 /* Create the "res" field that contains the response channel object. */
4648 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004649 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004650 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004651 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004652
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004653 /* Creates the HTTP object is the current proxy allows http. */
4654 lua_pushstring(L, "http");
4655 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02004656 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004657 return 0;
4658 }
4659 else
4660 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004661 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004662
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004663 /* Pop a class sesison metatable and affect it to the userdata. */
4664 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
4665 lua_setmetatable(L, -2);
4666
4667 return 1;
4668}
4669
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004670__LJMP static int hlua_txn_deflog(lua_State *L)
4671{
4672 const char *msg;
4673 struct hlua_txn *htxn;
4674
4675 MAY_LJMP(check_args(L, 2, "deflog"));
4676 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4677 msg = MAY_LJMP(luaL_checkstring(L, 2));
4678
4679 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
4680 return 0;
4681}
4682
4683__LJMP static int hlua_txn_log(lua_State *L)
4684{
4685 int level;
4686 const char *msg;
4687 struct hlua_txn *htxn;
4688
4689 MAY_LJMP(check_args(L, 3, "log"));
4690 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4691 level = MAY_LJMP(luaL_checkinteger(L, 2));
4692 msg = MAY_LJMP(luaL_checkstring(L, 3));
4693
4694 if (level < 0 || level >= NB_LOG_LEVELS)
4695 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
4696
4697 hlua_sendlog(htxn->s->be, level, msg);
4698 return 0;
4699}
4700
4701__LJMP static int hlua_txn_log_debug(lua_State *L)
4702{
4703 const char *msg;
4704 struct hlua_txn *htxn;
4705
4706 MAY_LJMP(check_args(L, 2, "Debug"));
4707 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4708 msg = MAY_LJMP(luaL_checkstring(L, 2));
4709 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
4710 return 0;
4711}
4712
4713__LJMP static int hlua_txn_log_info(lua_State *L)
4714{
4715 const char *msg;
4716 struct hlua_txn *htxn;
4717
4718 MAY_LJMP(check_args(L, 2, "Info"));
4719 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4720 msg = MAY_LJMP(luaL_checkstring(L, 2));
4721 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
4722 return 0;
4723}
4724
4725__LJMP static int hlua_txn_log_warning(lua_State *L)
4726{
4727 const char *msg;
4728 struct hlua_txn *htxn;
4729
4730 MAY_LJMP(check_args(L, 2, "Warning"));
4731 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4732 msg = MAY_LJMP(luaL_checkstring(L, 2));
4733 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
4734 return 0;
4735}
4736
4737__LJMP static int hlua_txn_log_alert(lua_State *L)
4738{
4739 const char *msg;
4740 struct hlua_txn *htxn;
4741
4742 MAY_LJMP(check_args(L, 2, "Alert"));
4743 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4744 msg = MAY_LJMP(luaL_checkstring(L, 2));
4745 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
4746 return 0;
4747}
4748
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004749__LJMP static int hlua_txn_set_loglevel(lua_State *L)
4750{
4751 struct hlua_txn *htxn;
4752 int ll;
4753
4754 MAY_LJMP(check_args(L, 2, "set_loglevel"));
4755 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4756 ll = MAY_LJMP(luaL_checkinteger(L, 2));
4757
4758 if (ll < 0 || ll > 7)
4759 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
4760
4761 htxn->s->logs.level = ll;
4762 return 0;
4763}
4764
4765__LJMP static int hlua_txn_set_tos(lua_State *L)
4766{
4767 struct hlua_txn *htxn;
4768 struct connection *cli_conn;
4769 int tos;
4770
4771 MAY_LJMP(check_args(L, 2, "set_tos"));
4772 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4773 tos = MAY_LJMP(luaL_checkinteger(L, 2));
4774
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02004775 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004776 inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, tos);
4777
4778 return 0;
4779}
4780
4781__LJMP static int hlua_txn_set_mark(lua_State *L)
4782{
4783#ifdef SO_MARK
4784 struct hlua_txn *htxn;
4785 struct connection *cli_conn;
4786 int mark;
4787
4788 MAY_LJMP(check_args(L, 2, "set_mark"));
4789 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4790 mark = MAY_LJMP(luaL_checkinteger(L, 2));
4791
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02004792 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02004793 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004794#endif
4795 return 0;
4796}
4797
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004798/* This function is an Lua binding that send pending data
4799 * to the client, and close the stream interface.
4800 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004801__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004802{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004803 struct hlua_txn *htxn;
Willy Tarreau81389672015-03-10 12:03:52 +01004804 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004805
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004806 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004807 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004808
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004809 ic = &htxn->s->req;
4810 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01004811
Willy Tarreau630ef452015-08-28 10:06:15 +02004812 if (htxn->s->txn) {
4813 /* HTTP mode, let's stay in sync with the stream */
4814 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
4815 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
4816 htxn->s->txn->req.sov = 0;
4817 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
4818 oc->analysers = AN_RES_HTTP_XFER_BODY;
4819 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
4820 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
4821
Willy Tarreau630ef452015-08-28 10:06:15 +02004822 /* Note that if we want to support keep-alive, we need
4823 * to bypass the close/shutr_now calls below, but that
4824 * may only be done if the HTTP request was already
4825 * processed and the connection header is known (ie
4826 * not during TCP rules).
4827 */
4828 }
4829
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02004830 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01004831 channel_abort(ic);
4832 channel_auto_close(ic);
4833 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02004834
4835 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01004836 channel_auto_read(oc);
4837 channel_auto_close(oc);
4838 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004839
Willy Tarreau0458b082015-08-28 09:40:04 +02004840 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004841
4842 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004843 return 0;
4844}
4845
4846__LJMP static int hlua_log(lua_State *L)
4847{
4848 int level;
4849 const char *msg;
4850
4851 MAY_LJMP(check_args(L, 2, "log"));
4852 level = MAY_LJMP(luaL_checkinteger(L, 1));
4853 msg = MAY_LJMP(luaL_checkstring(L, 2));
4854
4855 if (level < 0 || level >= NB_LOG_LEVELS)
4856 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
4857
4858 hlua_sendlog(NULL, level, msg);
4859 return 0;
4860}
4861
4862__LJMP static int hlua_log_debug(lua_State *L)
4863{
4864 const char *msg;
4865
4866 MAY_LJMP(check_args(L, 1, "debug"));
4867 msg = MAY_LJMP(luaL_checkstring(L, 1));
4868 hlua_sendlog(NULL, LOG_DEBUG, msg);
4869 return 0;
4870}
4871
4872__LJMP static int hlua_log_info(lua_State *L)
4873{
4874 const char *msg;
4875
4876 MAY_LJMP(check_args(L, 1, "info"));
4877 msg = MAY_LJMP(luaL_checkstring(L, 1));
4878 hlua_sendlog(NULL, LOG_INFO, msg);
4879 return 0;
4880}
4881
4882__LJMP static int hlua_log_warning(lua_State *L)
4883{
4884 const char *msg;
4885
4886 MAY_LJMP(check_args(L, 1, "warning"));
4887 msg = MAY_LJMP(luaL_checkstring(L, 1));
4888 hlua_sendlog(NULL, LOG_WARNING, msg);
4889 return 0;
4890}
4891
4892__LJMP static int hlua_log_alert(lua_State *L)
4893{
4894 const char *msg;
4895
4896 MAY_LJMP(check_args(L, 1, "alert"));
4897 msg = MAY_LJMP(luaL_checkstring(L, 1));
4898 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004899 return 0;
4900}
4901
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004902__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004903{
4904 int wakeup_ms = lua_tointeger(L, -1);
4905 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004906 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004907 return 0;
4908}
4909
4910__LJMP static int hlua_sleep(lua_State *L)
4911{
4912 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004913 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004914
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004915 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004916
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004917 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004918 wakeup_ms = tick_add(now_ms, delay);
4919 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004920
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004921 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
4922 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004923}
4924
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004925__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004926{
4927 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004928 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004929
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004930 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004931
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004932 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004933 wakeup_ms = tick_add(now_ms, delay);
4934 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004935
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004936 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
4937 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004938}
4939
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004940/* This functionis an LUA binding. it permits to give back
4941 * the hand at the HAProxy scheduler. It is used when the
4942 * LUA processing consumes a lot of time.
4943 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004944__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004945{
4946 return 0;
4947}
4948
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004949__LJMP static int hlua_yield(lua_State *L)
4950{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004951 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
4952 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004953}
4954
Thierry FOURNIER37196f42015-02-16 19:34:56 +01004955/* This function change the nice of the currently executed
4956 * task. It is used set low or high priority at the current
4957 * task.
4958 */
Willy Tarreau59551662015-03-10 14:23:13 +01004959__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01004960{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004961 struct hlua *hlua;
4962 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01004963
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004964 MAY_LJMP(check_args(L, 1, "set_nice"));
4965 hlua = hlua_gethlua(L);
4966 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01004967
4968 /* If he task is not set, I'm in a start mode. */
4969 if (!hlua || !hlua->task)
4970 return 0;
4971
4972 if (nice < -1024)
4973 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004974 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01004975 nice = 1024;
4976
4977 hlua->task->nice = nice;
4978 return 0;
4979}
4980
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004981/* This function is used as a calback of a task. It is called by the
4982 * HAProxy task subsystem when the task is awaked. The LUA runtime can
4983 * return an E_AGAIN signal, the emmiter of this signal must set a
4984 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004985 *
4986 * Task wrapper are longjmp safe because the only one Lua code
4987 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004988 */
4989static struct task *hlua_process_task(struct task *task)
4990{
4991 struct hlua *hlua = task->context;
4992 enum hlua_exec status;
4993
4994 /* We need to remove the task from the wait queue before executing
4995 * the Lua code because we don't know if it needs to wait for
4996 * another timer or not in the case of E_AGAIN.
4997 */
4998 task_delete(task);
4999
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005000 /* If it is the first call to the task, we must initialize the
5001 * execution timeouts.
5002 */
5003 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005004 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005005
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005006 /* Execute the Lua code. */
5007 status = hlua_ctx_resume(hlua, 1);
5008
5009 switch (status) {
5010 /* finished or yield */
5011 case HLUA_E_OK:
5012 hlua_ctx_destroy(hlua);
5013 task_delete(task);
5014 task_free(task);
5015 break;
5016
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005017 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
5018 if (hlua->wake_time != TICK_ETERNITY)
5019 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005020 break;
5021
5022 /* finished with error. */
5023 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005024 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005025 hlua_ctx_destroy(hlua);
5026 task_delete(task);
5027 task_free(task);
5028 break;
5029
5030 case HLUA_E_ERR:
5031 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005032 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005033 hlua_ctx_destroy(hlua);
5034 task_delete(task);
5035 task_free(task);
5036 break;
5037 }
5038 return NULL;
5039}
5040
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005041/* This function is an LUA binding that register LUA function to be
5042 * executed after the HAProxy configuration parsing and before the
5043 * HAProxy scheduler starts. This function expect only one LUA
5044 * argument that is a function. This function returns nothing, but
5045 * throws if an error is encountered.
5046 */
5047__LJMP static int hlua_register_init(lua_State *L)
5048{
5049 struct hlua_init_function *init;
5050 int ref;
5051
5052 MAY_LJMP(check_args(L, 1, "register_init"));
5053
5054 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5055
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005056 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005057 if (!init)
5058 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5059
5060 init->function_ref = ref;
5061 LIST_ADDQ(&hlua_init_functions, &init->l);
5062 return 0;
5063}
5064
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005065/* This functio is an LUA binding. It permits to register a task
5066 * executed in parallel of the main HAroxy activity. The task is
5067 * created and it is set in the HAProxy scheduler. It can be called
5068 * from the "init" section, "post init" or during the runtime.
5069 *
5070 * Lua prototype:
5071 *
5072 * <none> core.register_task(<function>)
5073 */
5074static int hlua_register_task(lua_State *L)
5075{
5076 struct hlua *hlua;
5077 struct task *task;
5078 int ref;
5079
5080 MAY_LJMP(check_args(L, 1, "register_task"));
5081
5082 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5083
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005084 hlua = calloc(1, sizeof(*hlua));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005085 if (!hlua)
5086 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5087
5088 task = task_new();
5089 task->context = hlua;
5090 task->process = hlua_process_task;
5091
5092 if (!hlua_ctx_init(hlua, task))
5093 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5094
5095 /* Restore the function in the stack. */
5096 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5097 hlua->nargs = 0;
5098
5099 /* Schedule task. */
5100 task_schedule(task, now_ms);
5101
5102 return 0;
5103}
5104
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005105/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5106 * doesn't allow "yield" functions because the HAProxy engine cannot
5107 * resume converters.
5108 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005109static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005110{
5111 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005112 struct stream *stream = smp->strm;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005113
Willy Tarreau87b09662015-04-03 00:22:06 +02005114 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005115 * Lua context can be not initialized. This behavior
5116 * permits to save performances because a systematic
5117 * Lua initialization cause 5% performances loss.
5118 */
Willy Tarreau87b09662015-04-03 00:22:06 +02005119 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005120 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005121 return 0;
5122 }
5123
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005124 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005125 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005126
5127 /* The following Lua calls can fail. */
5128 if (!SET_SAFE_LJMP(stream->hlua.T)) {
5129 SEND_ERR(stream->be, "Lua converter '%s': critical error.\n", fcn->name);
5130 return 0;
5131 }
5132
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005133 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005134 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005135 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005136 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005137 return 0;
5138 }
5139
5140 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005141 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005142
5143 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005144 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005145 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005146 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005147 return 0;
5148 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005149 hlua_smp2lua(stream->hlua.T, smp);
5150 stream->hlua.nargs = 2;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005151
5152 /* push keywords in the stack. */
5153 if (arg_p) {
5154 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02005155 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005156 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005157 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005158 return 0;
5159 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005160 hlua_arg2lua(stream->hlua.T, arg_p);
5161 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005162 }
5163 }
5164
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005165 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005166 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005167
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005168 /* At this point the execution is safe. */
5169 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005170 }
5171
5172 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005173 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005174 /* finished. */
5175 case HLUA_E_OK:
5176 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005177 hlua_lua2smp(stream->hlua.T, -1, smp);
5178 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005179 return 1;
5180
5181 /* yield. */
5182 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005183 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005184 return 0;
5185
5186 /* finished with error. */
5187 case HLUA_E_ERRMSG:
5188 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005189 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
5190 fcn->name, lua_tostring(stream->hlua.T, -1));
Willy Tarreau87b09662015-04-03 00:22:06 +02005191 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005192 return 0;
5193
5194 case HLUA_E_ERR:
5195 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005196 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005197
5198 default:
5199 return 0;
5200 }
5201}
5202
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005203/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5204 * doesn't allow "yield" functions because the HAProxy engine cannot
5205 * resume sample-fetches.
5206 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005207static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5208 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005209{
5210 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005211 struct stream *stream = smp->strm;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005212
Willy Tarreau87b09662015-04-03 00:22:06 +02005213 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005214 * Lua context can be not initialized. This behavior
5215 * permits to save performances because a systematic
5216 * Lua initialization cause 5% performances loss.
5217 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005218 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005219 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005220 return 0;
5221 }
5222
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005223 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005224 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005225
5226 /* The following Lua calls can fail. */
5227 if (!SET_SAFE_LJMP(stream->hlua.T)) {
5228 SEND_ERR(smp->px, "Lua sample-fetch '%s': critical error.\n", fcn->name);
5229 return 0;
5230 }
5231
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005232 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005233 if (!lua_checkstack(stream->hlua.T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005234 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005235 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005236 return 0;
5237 }
5238
5239 /* Restore the function in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005240 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005241
5242 /* push arguments in the stack. */
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005243 if (!hlua_txn_new(stream->hlua.T, stream, smp->px, smp->opt & SMP_OPT_DIR)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005244 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005245 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005246 return 0;
5247 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005248 stream->hlua.nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005249
5250 /* push keywords in the stack. */
5251 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5252 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005253 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005254 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005255 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005256 return 0;
5257 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005258 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005259 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005260 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005261 return 0;
5262 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005263 hlua_arg2lua(stream->hlua.T, arg_p);
5264 stream->hlua.nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005265 }
5266
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005267 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005268 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005269
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005270 /* At this point the execution is safe. */
5271 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005272 }
5273
5274 /* Execute the function. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005275 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005276 /* finished. */
5277 case HLUA_E_OK:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005278 if (!hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005279 return 0;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005280 /* Convert the returned value in sample. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005281 hlua_lua2smp(stream->hlua.T, -1, smp);
5282 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005283
5284 /* Set the end of execution flag. */
5285 smp->flags &= ~SMP_F_MAY_CHANGE;
5286 return 1;
5287
5288 /* yield. */
5289 case HLUA_E_AGAIN:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005290 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005291 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005292 return 0;
5293
5294 /* finished with error. */
5295 case HLUA_E_ERRMSG:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005296 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005297 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005298 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
5299 fcn->name, lua_tostring(stream->hlua.T, -1));
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005300 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005301 return 0;
5302
5303 case HLUA_E_ERR:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005304 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005305 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005306 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005307
5308 default:
5309 return 0;
5310 }
5311}
5312
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005313/* This function is an LUA binding used for registering
5314 * "sample-conv" functions. It expects a converter name used
5315 * in the haproxy configuration file, and an LUA function.
5316 */
5317__LJMP static int hlua_register_converters(lua_State *L)
5318{
5319 struct sample_conv_kw_list *sck;
5320 const char *name;
5321 int ref;
5322 int len;
5323 struct hlua_function *fcn;
5324
5325 MAY_LJMP(check_args(L, 2, "register_converters"));
5326
5327 /* First argument : converter name. */
5328 name = MAY_LJMP(luaL_checkstring(L, 1));
5329
5330 /* Second argument : lua function. */
5331 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5332
5333 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005334 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005335 if (!sck)
5336 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005337 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005338 if (!fcn)
5339 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5340
5341 /* Fill fcn. */
5342 fcn->name = strdup(name);
5343 if (!fcn->name)
5344 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5345 fcn->function_ref = ref;
5346
5347 /* List head */
5348 sck->list.n = sck->list.p = NULL;
5349
5350 /* converter keyword. */
5351 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005352 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005353 if (!sck->kw[0].kw)
5354 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5355
5356 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5357 sck->kw[0].process = hlua_sample_conv_wrapper;
5358 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
5359 sck->kw[0].val_args = NULL;
5360 sck->kw[0].in_type = SMP_T_STR;
5361 sck->kw[0].out_type = SMP_T_STR;
5362 sck->kw[0].private = fcn;
5363
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005364 /* Register this new converter */
5365 sample_register_convs(sck);
5366
5367 return 0;
5368}
5369
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005370/* This fucntion is an LUA binding used for registering
5371 * "sample-fetch" functions. It expects a converter name used
5372 * in the haproxy configuration file, and an LUA function.
5373 */
5374__LJMP static int hlua_register_fetches(lua_State *L)
5375{
5376 const char *name;
5377 int ref;
5378 int len;
5379 struct sample_fetch_kw_list *sfk;
5380 struct hlua_function *fcn;
5381
5382 MAY_LJMP(check_args(L, 2, "register_fetches"));
5383
5384 /* First argument : sample-fetch name. */
5385 name = MAY_LJMP(luaL_checkstring(L, 1));
5386
5387 /* Second argument : lua function. */
5388 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5389
5390 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005391 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005392 if (!sfk)
5393 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005394 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005395 if (!fcn)
5396 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5397
5398 /* Fill fcn. */
5399 fcn->name = strdup(name);
5400 if (!fcn->name)
5401 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5402 fcn->function_ref = ref;
5403
5404 /* List head */
5405 sfk->list.n = sfk->list.p = NULL;
5406
5407 /* sample-fetch keyword. */
5408 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005409 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005410 if (!sfk->kw[0].kw)
5411 return luaL_error(L, "lua out of memory error.");
5412
5413 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
5414 sfk->kw[0].process = hlua_sample_fetch_wrapper;
5415 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
5416 sfk->kw[0].val_args = NULL;
5417 sfk->kw[0].out_type = SMP_T_STR;
5418 sfk->kw[0].use = SMP_USE_HTTP_ANY;
5419 sfk->kw[0].val = 0;
5420 sfk->kw[0].private = fcn;
5421
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005422 /* Register this new fetch. */
5423 sample_register_fetches(sfk);
5424
5425 return 0;
5426}
5427
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005428/* This function is a wrapper to execute each LUA function declared
5429 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005430 * return ACT_RET_CONT if the processing is finished (with or without
5431 * error) and return ACT_RET_YIELD if the function must be called again
5432 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005433 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005434static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02005435 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005436{
5437 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005438 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005439 int dir;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005440
5441 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01005442 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
5443 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
5444 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
5445 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005446 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005447 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005448 return ACT_RET_CONT;
5449 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005450
Willy Tarreau87b09662015-04-03 00:22:06 +02005451 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005452 * Lua context can be not initialized. This behavior
5453 * permits to save performances because a systematic
5454 * Lua initialization cause 5% performances loss.
5455 */
5456 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005457 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005458 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005459 return ACT_RET_CONT;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005460 }
5461
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005462 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01005463 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005464
5465 /* The following Lua calls can fail. */
5466 if (!SET_SAFE_LJMP(s->hlua.T)) {
5467 SEND_ERR(px, "Lua function '%s': critical error.\n",
5468 rule->arg.hlua_rule->fcn.name);
5469 return ACT_RET_CONT;
5470 }
5471
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005472 /* Check stack available size. */
5473 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005474 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005475 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005476 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005477 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005478 }
5479
5480 /* Restore the function in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005481 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005482
Willy Tarreau87b09662015-04-03 00:22:06 +02005483 /* Create and and push object stream in the stack. */
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005484 if (!hlua_txn_new(s->hlua.T, s, px, dir)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005485 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005486 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005487 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005488 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005489 }
5490 s->hlua.nargs = 1;
5491
5492 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005493 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005494 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005495 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005496 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005497 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005498 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005499 }
5500 lua_pushstring(s->hlua.T, *arg);
5501 s->hlua.nargs++;
5502 }
5503
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005504 /* Now the execution is safe. */
5505 RESET_SAFE_LJMP(s->hlua.T);
5506
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005507 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005508 s->hlua.max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005509 }
5510
5511 /* Execute the function. */
Willy Tarreau528192d2015-09-27 10:48:01 +02005512 switch (hlua_ctx_resume(&s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005513 /* finished. */
5514 case HLUA_E_OK:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005515 if (!hlua_check_proto(s, dir))
5516 return ACT_RET_ERR;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005517 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005518
5519 /* yield. */
5520 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005521 /* Set timeout in the required channel. */
5522 if (s->hlua.wake_time != TICK_ETERNITY) {
5523 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005524 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005525 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005526 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005527 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005528 /* Some actions can be wake up when a "write" event
5529 * is detected on a response channel. This is useful
5530 * only for actions targetted on the requests.
5531 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01005532 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005533 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01005534 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005535 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005536 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01005537 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005538 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005539 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005540
5541 /* finished with error. */
5542 case HLUA_E_ERRMSG:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005543 if (!hlua_check_proto(s, dir))
5544 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005545 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005546 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005547 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005548 lua_pop(s->hlua.T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005549 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005550
5551 case HLUA_E_ERR:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005552 if (!hlua_check_proto(s, dir))
5553 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005554 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005555 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005556 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005557
5558 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005559 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005560 }
5561}
5562
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005563struct task *hlua_applet_wakeup(struct task *t)
5564{
5565 struct appctx *ctx = t->context;
5566 struct stream_interface *si = ctx->owner;
5567
5568 /* If the applet is wake up without any expected work, the sheduler
5569 * remove it from the run queue. This flag indicate that the applet
5570 * is waiting for write. If the buffer is full, the main processing
5571 * will send some data and after call the applet, otherwise it call
5572 * the applet ASAP.
5573 */
5574 si_applet_cant_put(si);
5575 appctx_wakeup(ctx);
5576 return NULL;
5577}
5578
5579static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5580{
5581 struct stream_interface *si = ctx->owner;
5582 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5583 struct task *task;
5584 char **arg;
5585
5586 HLUA_INIT(hlua);
5587 ctx->ctx.hlua_apptcp.flags = 0;
5588
5589 /* Create task used by signal to wakeup applets. */
5590 task = task_new();
5591 if (!task) {
5592 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
5593 ctx->rule->arg.hlua_rule->fcn.name);
5594 return 0;
5595 }
5596 task->nice = 0;
5597 task->context = ctx;
5598 task->process = hlua_applet_wakeup;
5599 ctx->ctx.hlua_apptcp.task = task;
5600
5601 /* In the execution wrappers linked with a stream, the
5602 * Lua context can be not initialized. This behavior
5603 * permits to save performances because a systematic
5604 * Lua initialization cause 5% performances loss.
5605 */
5606 if (!hlua_ctx_init(hlua, task)) {
5607 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
5608 ctx->rule->arg.hlua_rule->fcn.name);
5609 return 0;
5610 }
5611
5612 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005613 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005614
5615 /* The following Lua calls can fail. */
5616 if (!SET_SAFE_LJMP(hlua->T)) {
5617 SEND_ERR(px, "Lua applet tcp '%s': critical error.\n",
5618 ctx->rule->arg.hlua_rule->fcn.name);
5619 RESET_SAFE_LJMP(hlua->T);
5620 return 0;
5621 }
5622
5623 /* Check stack available size. */
5624 if (!lua_checkstack(hlua->T, 1)) {
5625 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5626 ctx->rule->arg.hlua_rule->fcn.name);
5627 RESET_SAFE_LJMP(hlua->T);
5628 return 0;
5629 }
5630
5631 /* Restore the function in the stack. */
5632 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
5633
5634 /* Create and and push object stream in the stack. */
5635 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
5636 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5637 ctx->rule->arg.hlua_rule->fcn.name);
5638 RESET_SAFE_LJMP(hlua->T);
5639 return 0;
5640 }
5641 hlua->nargs = 1;
5642
5643 /* push keywords in the stack. */
5644 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
5645 if (!lua_checkstack(hlua->T, 1)) {
5646 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5647 ctx->rule->arg.hlua_rule->fcn.name);
5648 RESET_SAFE_LJMP(hlua->T);
5649 return 0;
5650 }
5651 lua_pushstring(hlua->T, *arg);
5652 hlua->nargs++;
5653 }
5654
5655 RESET_SAFE_LJMP(hlua->T);
5656
5657 /* Wakeup the applet ASAP. */
5658 si_applet_cant_get(si);
5659 si_applet_cant_put(si);
5660
5661 return 1;
5662}
5663
5664static void hlua_applet_tcp_fct(struct appctx *ctx)
5665{
5666 struct stream_interface *si = ctx->owner;
5667 struct stream *strm = si_strm(si);
5668 struct channel *res = si_ic(si);
5669 struct act_rule *rule = ctx->rule;
5670 struct proxy *px = strm->be;
5671 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5672
5673 /* The applet execution is already done. */
5674 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
5675 return;
5676
5677 /* If the stream is disconnect or closed, ldo nothing. */
5678 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
5679 return;
5680
5681 /* Execute the function. */
5682 switch (hlua_ctx_resume(hlua, 1)) {
5683 /* finished. */
5684 case HLUA_E_OK:
5685 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
5686
5687 /* log time */
5688 strm->logs.tv_request = now;
5689
5690 /* eat the whole request */
5691 bo_skip(si_oc(si), si_ob(si)->o);
5692 res->flags |= CF_READ_NULL;
5693 si_shutr(si);
5694 return;
5695
5696 /* yield. */
5697 case HLUA_E_AGAIN:
5698 return;
5699
5700 /* finished with error. */
5701 case HLUA_E_ERRMSG:
5702 /* Display log. */
5703 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
5704 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
5705 lua_pop(hlua->T, 1);
5706 goto error;
5707
5708 case HLUA_E_ERR:
5709 /* Display log. */
5710 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
5711 rule->arg.hlua_rule->fcn.name);
5712 goto error;
5713
5714 default:
5715 goto error;
5716 }
5717
5718error:
5719
5720 /* For all other cases, just close the stream. */
5721 si_shutw(si);
5722 si_shutr(si);
5723 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
5724}
5725
5726static void hlua_applet_tcp_release(struct appctx *ctx)
5727{
5728 task_free(ctx->ctx.hlua_apptcp.task);
5729 ctx->ctx.hlua_apptcp.task = NULL;
5730 hlua_ctx_destroy(&ctx->ctx.hlua_apptcp.hlua);
5731}
5732
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005733/* The function returns 1 if the initialisation is complete, 0 if
5734 * an errors occurs and -1 if more data are required for initializing
5735 * the applet.
5736 */
5737static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5738{
5739 struct stream_interface *si = ctx->owner;
5740 struct channel *req = si_oc(si);
5741 struct http_msg *msg;
5742 struct http_txn *txn;
5743 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
5744 char **arg;
5745 struct hdr_ctx hdr;
5746 struct task *task;
5747 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
5748
5749 /* Wait for a full HTTP request. */
5750 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
5751 if (smp.flags & SMP_F_MAY_CHANGE)
5752 return -1;
5753 return 0;
5754 }
5755 txn = strm->txn;
5756 msg = &txn->req;
5757
Willy Tarreau0078bfc2015-10-07 20:20:28 +02005758 /* We want two things in HTTP mode :
5759 * - enforce server-close mode if we were in keep-alive, so that the
5760 * applet is released after each response ;
5761 * - enable request body transfer to the applet in order to resync
5762 * with the response body.
5763 */
5764 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
5765 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
5766 req->analysers |= AN_REQ_HTTP_XFER_BODY;
5767
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005768 HLUA_INIT(hlua);
5769 ctx->ctx.hlua_apphttp.left_bytes = -1;
5770 ctx->ctx.hlua_apphttp.flags = 0;
5771
5772 /* Create task used by signal to wakeup applets. */
5773 task = task_new();
5774 if (!task) {
5775 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
5776 ctx->rule->arg.hlua_rule->fcn.name);
5777 return 0;
5778 }
5779 task->nice = 0;
5780 task->context = ctx;
5781 task->process = hlua_applet_wakeup;
5782 ctx->ctx.hlua_apphttp.task = task;
5783
5784 /* In the execution wrappers linked with a stream, the
5785 * Lua context can be not initialized. This behavior
5786 * permits to save performances because a systematic
5787 * Lua initialization cause 5% performances loss.
5788 */
5789 if (!hlua_ctx_init(hlua, task)) {
5790 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
5791 ctx->rule->arg.hlua_rule->fcn.name);
5792 return 0;
5793 }
5794
5795 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005796 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005797
5798 /* The following Lua calls can fail. */
5799 if (!SET_SAFE_LJMP(hlua->T)) {
5800 SEND_ERR(px, "Lua applet http '%s': critical error.\n",
5801 ctx->rule->arg.hlua_rule->fcn.name);
5802 return 0;
5803 }
5804
5805 /* Check stack available size. */
5806 if (!lua_checkstack(hlua->T, 1)) {
5807 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5808 ctx->rule->arg.hlua_rule->fcn.name);
5809 RESET_SAFE_LJMP(hlua->T);
5810 return 0;
5811 }
5812
5813 /* Restore the function in the stack. */
5814 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
5815
5816 /* Create and and push object stream in the stack. */
5817 if (!hlua_applet_http_new(hlua->T, ctx)) {
5818 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5819 ctx->rule->arg.hlua_rule->fcn.name);
5820 RESET_SAFE_LJMP(hlua->T);
5821 return 0;
5822 }
5823 hlua->nargs = 1;
5824
5825 /* Look for a 100-continue expected. */
5826 if (msg->flags & HTTP_MSGF_VER_11) {
5827 hdr.idx = 0;
5828 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
5829 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
5830 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
5831 }
5832
5833 /* push keywords in the stack. */
5834 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
5835 if (!lua_checkstack(hlua->T, 1)) {
5836 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5837 ctx->rule->arg.hlua_rule->fcn.name);
5838 RESET_SAFE_LJMP(hlua->T);
5839 return 0;
5840 }
5841 lua_pushstring(hlua->T, *arg);
5842 hlua->nargs++;
5843 }
5844
5845 RESET_SAFE_LJMP(hlua->T);
5846
5847 /* Wakeup the applet when data is ready for read. */
5848 si_applet_cant_get(si);
5849
5850 return 1;
5851}
5852
5853static void hlua_applet_http_fct(struct appctx *ctx)
5854{
5855 struct stream_interface *si = ctx->owner;
5856 struct stream *strm = si_strm(si);
5857 struct channel *res = si_ic(si);
5858 struct channel *req = si_oc(si);
5859 struct act_rule *rule = ctx->rule;
5860 struct proxy *px = strm->be;
5861 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
5862 char *blk1;
5863 int len1;
5864 char *blk2;
5865 int len2;
5866 int ret;
5867
5868 /* If the stream is disconnect or closed, ldo nothing. */
5869 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
5870 return;
5871
5872 /* Set the currently running flag. */
5873 if (!HLUA_IS_RUNNING(hlua) &&
5874 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
5875
5876 /* enable the minimally required analyzers to handle keep-alive
5877 * and compression on the HTTP response
5878 */
5879 req->analysers = (req->analysers & AN_REQ_HTTP_BODY) |
5880 AN_REQ_HTTP_XFER_BODY | AN_REQ_HTTP_INNER;
5881
5882 /* Wait for full HTTP analysys. */
5883 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
5884 si_applet_cant_get(si);
5885 return;
5886 }
5887
5888 /* Store the max amount of bytes that we can read. */
5889 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
5890
5891 /* We need to flush the request header. This left the body
5892 * for the Lua.
5893 */
5894
5895 /* Read the maximum amount of data avalaible. */
5896 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
5897 if (ret == -1)
5898 return;
5899
5900 /* No data available, ask for more data. */
5901 if (ret == 1)
5902 len2 = 0;
5903 if (ret == 0)
5904 len1 = 0;
5905 if (len1 + len2 < strm->txn->req.eoh + 2) {
5906 si_applet_cant_get(si);
5907 return;
5908 }
5909
5910 /* skip the requests bytes. */
5911 bo_skip(si_oc(si), strm->txn->req.eoh + 2);
5912 }
5913
5914 /* Executes The applet if it is not done. */
5915 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
5916
5917 /* Execute the function. */
5918 switch (hlua_ctx_resume(hlua, 1)) {
5919 /* finished. */
5920 case HLUA_E_OK:
5921 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
5922 break;
5923
5924 /* yield. */
5925 case HLUA_E_AGAIN:
5926 return;
5927
5928 /* finished with error. */
5929 case HLUA_E_ERRMSG:
5930 /* Display log. */
5931 SEND_ERR(px, "Lua applet http '%s': %s.\n",
5932 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
5933 lua_pop(hlua->T, 1);
5934 goto error;
5935
5936 case HLUA_E_ERR:
5937 /* Display log. */
5938 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
5939 rule->arg.hlua_rule->fcn.name);
5940 goto error;
5941
5942 default:
5943 goto error;
5944 }
5945 }
5946
5947 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
5948
5949 /* We must send the final chunk. */
5950 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
5951 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
5952
5953 /* sent last chunk at once. */
5954 ret = bi_putblk(res, "0\r\n\r\n", 5);
5955
5956 /* critical error. */
5957 if (ret == -2 || ret == -3) {
5958 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
5959 rule->arg.hlua_rule->fcn.name);
5960 goto error;
5961 }
5962
5963 /* no enough space error. */
5964 if (ret == -1) {
5965 si_applet_cant_put(si);
5966 return;
5967 }
5968
5969 /* set the last chunk sent. */
5970 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
5971 }
5972
5973 /* close the connection. */
5974
5975 /* status / log */
5976 strm->txn->status = ctx->ctx.hlua_apphttp.status;
5977 strm->logs.tv_request = now;
5978
5979 /* eat the whole request */
5980 bo_skip(si_oc(si), si_ob(si)->o);
5981 res->flags |= CF_READ_NULL;
5982 si_shutr(si);
5983
5984 return;
5985 }
5986
5987error:
5988
5989 /* If we are in HTTP mode, and we are not send any
5990 * data, return a 500 server error in best effort:
5991 * if there are no room avalaible in the buffer,
5992 * just close the connection.
5993 */
5994 bi_putblk(res, error_500, strlen(error_500));
5995 if (!(strm->flags & SF_ERR_MASK))
5996 strm->flags |= SF_ERR_RESOURCE;
5997 si_shutw(si);
5998 si_shutr(si);
5999 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6000}
6001
6002static void hlua_applet_http_release(struct appctx *ctx)
6003{
6004 task_free(ctx->ctx.hlua_apphttp.task);
6005 ctx->ctx.hlua_apphttp.task = NULL;
6006 hlua_ctx_destroy(&ctx->ctx.hlua_apphttp.hlua);
6007}
6008
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006009/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6010 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006011 *
6012 * This function can fail with an abort() due to an Lua critical error.
6013 * We are in the configuration parsing process of HAProxy, this abort() is
6014 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006015 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006016static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6017 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006018{
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006019 struct hlua_function *fcn = (struct hlua_function *)rule->kw->private;
6020
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006021 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006022 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006023 if (!rule->arg.hlua_rule) {
6024 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006025 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006026 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006027
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006028 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006029 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006030
6031 /* TODO: later accept arguments. */
6032 rule->arg.hlua_rule->args = NULL;
6033
Thierry FOURNIER42148732015-09-02 17:17:33 +02006034 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006035 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006036 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006037}
6038
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006039static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6040 struct act_rule *rule, char **err)
6041{
6042 struct hlua_function *fcn = (struct hlua_function *)rule->kw->private;
6043
6044 /* Memory for the rule. */
6045 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6046 if (!rule->arg.hlua_rule) {
6047 memprintf(err, "out of memory error");
6048 return ACT_RET_PRS_ERR;
6049 }
6050
6051 /* Reference the Lua function and store the reference. */
6052 rule->arg.hlua_rule->fcn = *fcn;
6053
6054 /* TODO: later accept arguments. */
6055 rule->arg.hlua_rule->args = NULL;
6056
6057 /* Add applet pointer in the rule. */
6058 rule->applet.obj_type = OBJ_TYPE_APPLET;
6059 rule->applet.name = fcn->name;
6060 rule->applet.init = hlua_applet_http_init;
6061 rule->applet.fct = hlua_applet_http_fct;
6062 rule->applet.release = hlua_applet_http_release;
6063 rule->applet.timeout = hlua_timeout_applet;
6064
6065 return ACT_RET_PRS_OK;
6066}
6067
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006068/* This function is an LUA binding used for registering
6069 * "sample-conv" functions. It expects a converter name used
6070 * in the haproxy configuration file, and an LUA function.
6071 */
6072__LJMP static int hlua_register_action(lua_State *L)
6073{
6074 struct action_kw_list *akl;
6075 const char *name;
6076 int ref;
6077 int len;
6078 struct hlua_function *fcn;
6079
6080 MAY_LJMP(check_args(L, 3, "register_service"));
6081
6082 /* First argument : converter name. */
6083 name = MAY_LJMP(luaL_checkstring(L, 1));
6084
6085 /* Second argument : environment. */
6086 if (lua_type(L, 2) != LUA_TTABLE)
6087 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6088
6089 /* Third argument : lua function. */
6090 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6091
6092 /* browse the second argulent as an array. */
6093 lua_pushnil(L);
6094 while (lua_next(L, 2) != 0) {
6095 if (lua_type(L, -1) != LUA_TSTRING)
6096 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6097
6098 /* Check required environment. Only accepted "http" or "tcp". */
6099 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006100 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006101 if (!akl)
6102 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006103 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006104 if (!fcn)
6105 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6106
6107 /* Fill fcn. */
6108 fcn->name = strdup(name);
6109 if (!fcn->name)
6110 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6111 fcn->function_ref = ref;
6112
6113 /* List head */
6114 akl->list.n = akl->list.p = NULL;
6115
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006116 /* action keyword. */
6117 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006118 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006119 if (!akl->kw[0].kw)
6120 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6121
6122 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6123
6124 akl->kw[0].match_pfx = 0;
6125 akl->kw[0].private = fcn;
6126 akl->kw[0].parse = action_register_lua;
6127
6128 /* select the action registering point. */
6129 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6130 tcp_req_cont_keywords_register(akl);
6131 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6132 tcp_res_cont_keywords_register(akl);
6133 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6134 http_req_keywords_register(akl);
6135 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6136 http_res_keywords_register(akl);
6137 else
6138 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
6139 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6140 "are expected.", lua_tostring(L, -1)));
6141
6142 /* pop the environment string. */
6143 lua_pop(L, 1);
6144 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006145 return ACT_RET_PRS_OK;
6146}
6147
6148static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6149 struct act_rule *rule, char **err)
6150{
6151 struct hlua_function *fcn = (struct hlua_function *)rule->kw->private;
6152
6153 /* Memory for the rule. */
6154 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6155 if (!rule->arg.hlua_rule) {
6156 memprintf(err, "out of memory error");
6157 return ACT_RET_PRS_ERR;
6158 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006159
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006160 /* Reference the Lua function and store the reference. */
6161 rule->arg.hlua_rule->fcn = *fcn;
6162
6163 /* TODO: later accept arguments. */
6164 rule->arg.hlua_rule->args = NULL;
6165
6166 /* Add applet pointer in the rule. */
6167 rule->applet.obj_type = OBJ_TYPE_APPLET;
6168 rule->applet.name = fcn->name;
6169 rule->applet.init = hlua_applet_tcp_init;
6170 rule->applet.fct = hlua_applet_tcp_fct;
6171 rule->applet.release = hlua_applet_tcp_release;
6172 rule->applet.timeout = hlua_timeout_applet;
6173
6174 return 0;
6175}
6176
6177/* This function is an LUA binding used for registering
6178 * "sample-conv" functions. It expects a converter name used
6179 * in the haproxy configuration file, and an LUA function.
6180 */
6181__LJMP static int hlua_register_service(lua_State *L)
6182{
6183 struct action_kw_list *akl;
6184 const char *name;
6185 const char *env;
6186 int ref;
6187 int len;
6188 struct hlua_function *fcn;
6189
6190 MAY_LJMP(check_args(L, 3, "register_service"));
6191
6192 /* First argument : converter name. */
6193 name = MAY_LJMP(luaL_checkstring(L, 1));
6194
6195 /* Second argument : environment. */
6196 env = MAY_LJMP(luaL_checkstring(L, 2));
6197
6198 /* Third argument : lua function. */
6199 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6200
6201 /* Check required environment. Only accepted "http" or "tcp". */
6202 /* Allocate and fill the sample fetch keyword struct. */
6203 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6204 if (!akl)
6205 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6206 fcn = calloc(1, sizeof(*fcn));
6207 if (!fcn)
6208 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6209
6210 /* Fill fcn. */
6211 len = strlen("<lua.>") + strlen(name) + 1;
6212 fcn->name = calloc(1, len);
6213 if (!fcn->name)
6214 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6215 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6216 fcn->function_ref = ref;
6217
6218 /* List head */
6219 akl->list.n = akl->list.p = NULL;
6220
6221 /* converter keyword. */
6222 len = strlen("lua.") + strlen(name) + 1;
6223 akl->kw[0].kw = calloc(1, len);
6224 if (!akl->kw[0].kw)
6225 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6226
6227 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6228
6229 if (strcmp(env, "tcp") == 0)
6230 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006231 else if (strcmp(env, "http") == 0)
6232 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006233 else
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006234 WILL_LJMP(luaL_error(L, "lua service environment '%s' is unknown. "
6235 "'tcp' or 'http' are expected."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006236
6237 akl->kw[0].match_pfx = 0;
6238 akl->kw[0].private = fcn;
6239
6240 /* End of array. */
6241 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6242
6243 /* Register this new converter */
6244 service_keywords_register(akl);
6245
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006246 return 0;
6247}
6248
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006249static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
6250 struct proxy *defpx, const char *file, int line,
6251 char **err, unsigned int *timeout)
6252{
6253 const char *error;
6254
6255 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
6256 if (error && *error != '\0') {
6257 memprintf(err, "%s: invalid timeout", args[0]);
6258 return -1;
6259 }
6260 return 0;
6261}
6262
6263static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
6264 struct proxy *defpx, const char *file, int line,
6265 char **err)
6266{
6267 return hlua_read_timeout(args, section_type, curpx, defpx,
6268 file, line, err, &hlua_timeout_session);
6269}
6270
6271static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
6272 struct proxy *defpx, const char *file, int line,
6273 char **err)
6274{
6275 return hlua_read_timeout(args, section_type, curpx, defpx,
6276 file, line, err, &hlua_timeout_task);
6277}
6278
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006279static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
6280 struct proxy *defpx, const char *file, int line,
6281 char **err)
6282{
6283 return hlua_read_timeout(args, section_type, curpx, defpx,
6284 file, line, err, &hlua_timeout_applet);
6285}
6286
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006287static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
6288 struct proxy *defpx, const char *file, int line,
6289 char **err)
6290{
6291 char *error;
6292
6293 hlua_nb_instruction = strtoll(args[1], &error, 10);
6294 if (*error != '\0') {
6295 memprintf(err, "%s: invalid number", args[0]);
6296 return -1;
6297 }
6298 return 0;
6299}
6300
Willy Tarreau32f61e22015-03-18 17:54:59 +01006301static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
6302 struct proxy *defpx, const char *file, int line,
6303 char **err)
6304{
6305 char *error;
6306
6307 if (*(args[1]) == 0) {
6308 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
6309 return -1;
6310 }
6311 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
6312 if (*error != '\0') {
6313 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
6314 return -1;
6315 }
6316 return 0;
6317}
6318
6319
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006320/* This function is called by the main configuration key "lua-load". It loads and
6321 * execute an lua file during the parsing of the HAProxy configuration file. It is
6322 * the main lua entry point.
6323 *
6324 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
6325 * occured, otherwise it returns 0.
6326 *
6327 * In some error case, LUA set an error message in top of the stack. This function
6328 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006329 *
6330 * This function can fail with an abort() due to an Lua critical error.
6331 * We are in the configuration parsing process of HAProxy, this abort() is
6332 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006333 */
6334static int hlua_load(char **args, int section_type, struct proxy *curpx,
6335 struct proxy *defpx, const char *file, int line,
6336 char **err)
6337{
6338 int error;
6339
6340 /* Just load and compile the file. */
6341 error = luaL_loadfile(gL.T, args[1]);
6342 if (error) {
6343 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
6344 lua_pop(gL.T, 1);
6345 return -1;
6346 }
6347
6348 /* If no syntax error where detected, execute the code. */
6349 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
6350 switch (error) {
6351 case LUA_OK:
6352 break;
6353 case LUA_ERRRUN:
6354 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
6355 lua_pop(gL.T, 1);
6356 return -1;
6357 case LUA_ERRMEM:
6358 memprintf(err, "lua out of memory error\n");
6359 return -1;
6360 case LUA_ERRERR:
6361 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
6362 lua_pop(gL.T, 1);
6363 return -1;
6364 case LUA_ERRGCMM:
6365 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
6366 lua_pop(gL.T, 1);
6367 return -1;
6368 default:
6369 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
6370 lua_pop(gL.T, 1);
6371 return -1;
6372 }
6373
6374 return 0;
6375}
6376
6377/* configuration keywords declaration */
6378static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006379 { CFG_GLOBAL, "lua-load", hlua_load },
6380 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
6381 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02006382 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006383 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01006384 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006385 { 0, NULL, NULL },
6386}};
6387
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006388/* This function can fail with an abort() due to an Lua critical error.
6389 * We are in the initialisation process of HAProxy, this abort() is
6390 * tolerated.
6391 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006392int hlua_post_init()
6393{
6394 struct hlua_init_function *init;
6395 const char *msg;
6396 enum hlua_exec ret;
6397
6398 list_for_each_entry(init, &hlua_init_functions, l) {
6399 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
6400 ret = hlua_ctx_resume(&gL, 0);
6401 switch (ret) {
6402 case HLUA_E_OK:
6403 lua_pop(gL.T, -1);
6404 return 1;
6405 case HLUA_E_AGAIN:
6406 Alert("lua init: yield not allowed.\n");
6407 return 0;
6408 case HLUA_E_ERRMSG:
6409 msg = lua_tostring(gL.T, -1);
6410 Alert("lua init: %s.\n", msg);
6411 return 0;
6412 case HLUA_E_ERR:
6413 default:
6414 Alert("lua init: unknown runtime error.\n");
6415 return 0;
6416 }
6417 }
6418 return 1;
6419}
6420
Willy Tarreau32f61e22015-03-18 17:54:59 +01006421/* The memory allocator used by the Lua stack. <ud> is a pointer to the
6422 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
6423 * is the previously allocated size or the kind of object in case of a new
6424 * allocation. <nsize> is the requested new size.
6425 */
6426static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
6427{
6428 struct hlua_mem_allocator *zone = ud;
6429
6430 if (nsize == 0) {
6431 /* it's a free */
6432 if (ptr)
6433 zone->allocated -= osize;
6434 free(ptr);
6435 return NULL;
6436 }
6437
6438 if (!ptr) {
6439 /* it's a new allocation */
6440 if (zone->limit && zone->allocated + nsize > zone->limit)
6441 return NULL;
6442
6443 ptr = malloc(nsize);
6444 if (ptr)
6445 zone->allocated += nsize;
6446 return ptr;
6447 }
6448
6449 /* it's a realloc */
6450 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
6451 return NULL;
6452
6453 ptr = realloc(ptr, nsize);
6454 if (ptr)
6455 zone->allocated += nsize - osize;
6456 return ptr;
6457}
6458
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006459/* Ithis function can fail with an abort() due to an Lua critical error.
6460 * We are in the initialisation process of HAProxy, this abort() is
6461 * tolerated.
6462 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01006463void hlua_init(void)
6464{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006465 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006466 int idx;
6467 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006468 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006469 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006470#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006471 struct srv_kw *kw;
6472 int tmp_error;
6473 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01006474 char *args[] = { /* SSL client configuration. */
6475 "ssl",
6476 "verify",
6477 "none",
6478 "force-sslv3",
6479 NULL
6480 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006481#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006482
Willy Tarreau87b09662015-04-03 00:22:06 +02006483 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01006484 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
6485
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006486 /* Register configuration keywords. */
6487 cfg_register_keywords(&cfg_kws);
6488
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006489 /* Init main lua stack. */
6490 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01006491 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01006492 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006493 gL.T = luaL_newstate();
6494 hlua_sethlua(&gL);
6495 gL.Tref = LUA_REFNIL;
6496 gL.task = NULL;
6497
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006498 /* From this point, until the end of the initialisation fucntion,
6499 * the Lua function can fail with an abort. We are in the initialisation
6500 * process of HAProxy, this abort() is tolerated.
6501 */
6502
Willy Tarreau32f61e22015-03-18 17:54:59 +01006503 /* change the memory allocators to track memory usage */
6504 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
6505
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006506 /* Initialise lua. */
6507 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006508
6509 /*
6510 *
6511 * Create "core" object.
6512 *
6513 */
6514
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01006515 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006516 lua_newtable(gL.T);
6517
6518 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006519 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006520 hlua_class_const_int(gL.T, log_levels[i], i);
6521
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006522 /* Register special functions. */
6523 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006524 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006525 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006526 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006527 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006528 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006529 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01006530 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006531 hlua_class_function(gL.T, "sleep", hlua_sleep);
6532 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01006533 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
6534 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
6535 hlua_class_function(gL.T, "set_map", hlua_set_map);
6536 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006537 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006538 hlua_class_function(gL.T, "log", hlua_log);
6539 hlua_class_function(gL.T, "Debug", hlua_log_debug);
6540 hlua_class_function(gL.T, "Info", hlua_log_info);
6541 hlua_class_function(gL.T, "Warning", hlua_log_warning);
6542 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02006543 hlua_class_function(gL.T, "done", hlua_done);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006544
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006545 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006546
6547 /*
6548 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006549 * Register class Map
6550 *
6551 */
6552
6553 /* This table entry is the object "Map" base. */
6554 lua_newtable(gL.T);
6555
6556 /* register pattern types. */
6557 for (i=0; i<PAT_MATCH_NUM; i++)
6558 hlua_class_const_int(gL.T, pat_match_names[i], i);
6559
6560 /* register constructor. */
6561 hlua_class_function(gL.T, "new", hlua_map_new);
6562
6563 /* Create and fill the metatable. */
6564 lua_newtable(gL.T);
6565
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006566 /* Create the __tostring identifier */
6567 lua_pushstring(gL.T, "__tostring");
6568 lua_pushstring(gL.T, CLASS_MAP);
6569 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6570 lua_rawset(gL.T, -3);
6571
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006572 /* Create and fille the __index entry. */
6573 lua_pushstring(gL.T, "__index");
6574 lua_newtable(gL.T);
6575
6576 /* Register . */
6577 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
6578 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
6579
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006580 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006581
6582 /* Register previous table in the registry with reference and named entry. */
6583 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6584 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6585 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_MAP); /* register class session. */
6586 class_map_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6587
6588 /* Assign the metatable to the mai Map object. */
6589 lua_setmetatable(gL.T, -2);
6590
6591 /* Set a name to the table. */
6592 lua_setglobal(gL.T, "Map");
6593
6594 /*
6595 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006596 * Register class Channel
6597 *
6598 */
6599
6600 /* Create and fill the metatable. */
6601 lua_newtable(gL.T);
6602
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006603 /* Create the __tostring identifier */
6604 lua_pushstring(gL.T, "__tostring");
6605 lua_pushstring(gL.T, CLASS_CHANNEL);
6606 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6607 lua_rawset(gL.T, -3);
6608
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006609 /* Create and fille the __index entry. */
6610 lua_pushstring(gL.T, "__index");
6611 lua_newtable(gL.T);
6612
6613 /* Register . */
6614 hlua_class_function(gL.T, "get", hlua_channel_get);
6615 hlua_class_function(gL.T, "dup", hlua_channel_dup);
6616 hlua_class_function(gL.T, "getline", hlua_channel_getline);
6617 hlua_class_function(gL.T, "set", hlua_channel_set);
6618 hlua_class_function(gL.T, "append", hlua_channel_append);
6619 hlua_class_function(gL.T, "send", hlua_channel_send);
6620 hlua_class_function(gL.T, "forward", hlua_channel_forward);
6621 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
6622 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
6623
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006624 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006625
6626 /* Register previous table in the registry with reference and named entry. */
6627 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6628 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
6629 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6630
6631 /*
6632 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006633 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006634 *
6635 */
6636
6637 /* Create and fill the metatable. */
6638 lua_newtable(gL.T);
6639
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006640 /* Create the __tostring identifier */
6641 lua_pushstring(gL.T, "__tostring");
6642 lua_pushstring(gL.T, CLASS_FETCHES);
6643 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6644 lua_rawset(gL.T, -3);
6645
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006646 /* Create and fille the __index entry. */
6647 lua_pushstring(gL.T, "__index");
6648 lua_newtable(gL.T);
6649
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006650 /* Browse existing fetches and create the associated
6651 * object method.
6652 */
6653 sf = NULL;
6654 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
6655
6656 /* Dont register the keywork if the arguments check function are
6657 * not safe during the runtime.
6658 */
6659 if ((sf->val_args != NULL) &&
6660 (sf->val_args != val_payload_lv) &&
6661 (sf->val_args != val_hdr))
6662 continue;
6663
6664 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
6665 * by an underscore.
6666 */
6667 strncpy(trash.str, sf->kw, trash.size);
6668 trash.str[trash.size - 1] = '\0';
6669 for (p = trash.str; *p; p++)
6670 if (*p == '.' || *p == '-' || *p == '+')
6671 *p = '_';
6672
6673 /* Register the function. */
6674 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01006675 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006676 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006677 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006678 }
6679
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006680 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006681
6682 /* Register previous table in the registry with reference and named entry. */
6683 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6684 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
6685 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6686
6687 /*
6688 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006689 * Register class Converters
6690 *
6691 */
6692
6693 /* Create and fill the metatable. */
6694 lua_newtable(gL.T);
6695
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006696 /* Create the __tostring identifier */
6697 lua_pushstring(gL.T, "__tostring");
6698 lua_pushstring(gL.T, CLASS_CONVERTERS);
6699 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6700 lua_rawset(gL.T, -3);
6701
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006702 /* Create and fill the __index entry. */
6703 lua_pushstring(gL.T, "__index");
6704 lua_newtable(gL.T);
6705
6706 /* Browse existing converters and create the associated
6707 * object method.
6708 */
6709 sc = NULL;
6710 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
6711 /* Dont register the keywork if the arguments check function are
6712 * not safe during the runtime.
6713 */
6714 if (sc->val_args != NULL)
6715 continue;
6716
6717 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
6718 * by an underscore.
6719 */
6720 strncpy(trash.str, sc->kw, trash.size);
6721 trash.str[trash.size - 1] = '\0';
6722 for (p = trash.str; *p; p++)
6723 if (*p == '.' || *p == '-' || *p == '+')
6724 *p = '_';
6725
6726 /* Register the function. */
6727 lua_pushstring(gL.T, trash.str);
6728 lua_pushlightuserdata(gL.T, sc);
6729 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006730 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006731 }
6732
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006733 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006734
6735 /* Register previous table in the registry with reference and named entry. */
6736 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6737 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
6738 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6739
6740 /*
6741 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006742 * Register class HTTP
6743 *
6744 */
6745
6746 /* Create and fill the metatable. */
6747 lua_newtable(gL.T);
6748
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006749 /* Create the __tostring identifier */
6750 lua_pushstring(gL.T, "__tostring");
6751 lua_pushstring(gL.T, CLASS_HTTP);
6752 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6753 lua_rawset(gL.T, -3);
6754
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006755 /* Create and fille the __index entry. */
6756 lua_pushstring(gL.T, "__index");
6757 lua_newtable(gL.T);
6758
6759 /* Register Lua functions. */
6760 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
6761 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
6762 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
6763 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
6764 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
6765 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
6766 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
6767 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
6768 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
6769 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
6770
6771 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
6772 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
6773 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
6774 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
6775 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
6776 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006777 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006778
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006779 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006780
6781 /* Register previous table in the registry with reference and named entry. */
6782 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6783 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_HTTP); /* register class session. */
6784 class_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6785
6786 /*
6787 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006788 * Register class AppletTCP
6789 *
6790 */
6791
6792 /* Create and fill the metatable. */
6793 lua_newtable(gL.T);
6794
6795 /* Create the __tostring identifier */
6796 lua_pushstring(gL.T, "__tostring");
6797 lua_pushstring(gL.T, CLASS_APPLET_TCP);
6798 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6799 lua_rawset(gL.T, -3);
6800
6801 /* Create and fille the __index entry. */
6802 lua_pushstring(gL.T, "__index");
6803 lua_newtable(gL.T);
6804
6805 /* Register Lua functions. */
6806 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
6807 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
6808 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
6809
6810 lua_settable(gL.T, -3);
6811
6812 /* Register previous table in the registry with reference and named entry. */
6813 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6814 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_APPLET_TCP); /* register class session. */
6815 class_applet_tcp_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6816
6817 /*
6818 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006819 * Register class AppletHTTP
6820 *
6821 */
6822
6823 /* Create and fill the metatable. */
6824 lua_newtable(gL.T);
6825
6826 /* Create the __tostring identifier */
6827 lua_pushstring(gL.T, "__tostring");
6828 lua_pushstring(gL.T, CLASS_APPLET_HTTP);
6829 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6830 lua_rawset(gL.T, -3);
6831
6832 /* Create and fille the __index entry. */
6833 lua_pushstring(gL.T, "__index");
6834 lua_newtable(gL.T);
6835
6836 /* Register Lua functions. */
6837 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
6838 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
6839 hlua_class_function(gL.T, "send", hlua_applet_http_send);
6840 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
6841 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
6842 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
6843
6844 lua_settable(gL.T, -3);
6845
6846 /* Register previous table in the registry with reference and named entry. */
6847 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6848 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_APPLET_HTTP); /* register class session. */
6849 class_applet_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6850
6851 /*
6852 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006853 * Register class TXN
6854 *
6855 */
6856
6857 /* Create and fill the metatable. */
6858 lua_newtable(gL.T);
6859
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006860 /* Create the __tostring identifier */
6861 lua_pushstring(gL.T, "__tostring");
6862 lua_pushstring(gL.T, CLASS_TXN);
6863 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6864 lua_rawset(gL.T, -3);
6865
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006866 /* Create and fille the __index entry. */
6867 lua_pushstring(gL.T, "__index");
6868 lua_newtable(gL.T);
6869
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006870 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01006871 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
6872 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006873 hlua_class_function(gL.T, "set_var", hlua_set_var);
6874 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006875 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006876 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
6877 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
6878 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006879 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
6880 hlua_class_function(gL.T, "log", hlua_txn_log);
6881 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
6882 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
6883 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
6884 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006885
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006886 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006887
6888 /* Register previous table in the registry with reference and named entry. */
6889 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6890 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
6891 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006892
6893 /*
6894 *
6895 * Register class Socket
6896 *
6897 */
6898
6899 /* Create and fill the metatable. */
6900 lua_newtable(gL.T);
6901
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006902 /* Create the __tostring identifier */
6903 lua_pushstring(gL.T, "__tostring");
6904 lua_pushstring(gL.T, CLASS_SOCKET);
6905 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6906 lua_rawset(gL.T, -3);
6907
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006908 /* Create and fille the __index entry. */
6909 lua_pushstring(gL.T, "__index");
6910 lua_newtable(gL.T);
6911
Baptiste Assmann84bb4932015-03-02 21:40:06 +01006912#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006913 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01006914#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006915 hlua_class_function(gL.T, "connect", hlua_socket_connect);
6916 hlua_class_function(gL.T, "send", hlua_socket_send);
6917 hlua_class_function(gL.T, "receive", hlua_socket_receive);
6918 hlua_class_function(gL.T, "close", hlua_socket_close);
6919 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
6920 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
6921 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
6922 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
6923
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006924 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006925
6926 /* Register the garbage collector entry. */
6927 lua_pushstring(gL.T, "__gc");
6928 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006929 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006930
6931 /* Register previous table in the registry with reference and named entry. */
6932 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6933 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6934 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
6935 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
6936
6937 /* Proxy and server configuration initialisation. */
6938 memset(&socket_proxy, 0, sizeof(socket_proxy));
6939 init_new_proxy(&socket_proxy);
6940 socket_proxy.parent = NULL;
6941 socket_proxy.last_change = now.tv_sec;
6942 socket_proxy.id = "LUA-SOCKET";
6943 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
6944 socket_proxy.maxconn = 0;
6945 socket_proxy.accept = NULL;
6946 socket_proxy.options2 |= PR_O2_INDEPSTR;
6947 socket_proxy.srv = NULL;
6948 socket_proxy.conn_retries = 0;
6949 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
6950
6951 /* Init TCP server: unchanged parameters */
6952 memset(&socket_tcp, 0, sizeof(socket_tcp));
6953 socket_tcp.next = NULL;
6954 socket_tcp.proxy = &socket_proxy;
6955 socket_tcp.obj_type = OBJ_TYPE_SERVER;
6956 LIST_INIT(&socket_tcp.actconns);
6957 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02006958 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02006959 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02006960 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006961 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
6962 socket_tcp.last_change = 0;
6963 socket_tcp.id = "LUA-TCP-CONN";
6964 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
6965 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
6966 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
6967
6968 /* XXX: Copy default parameter from default server,
6969 * but the default server is not initialized.
6970 */
6971 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
6972 socket_tcp.minconn = socket_proxy.defsrv.minconn;
6973 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
6974 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
6975 socket_tcp.onerror = socket_proxy.defsrv.onerror;
6976 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
6977 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
6978 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
6979 socket_tcp.uweight = socket_proxy.defsrv.iweight;
6980 socket_tcp.iweight = socket_proxy.defsrv.iweight;
6981
6982 socket_tcp.check.status = HCHK_STATUS_INI;
6983 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
6984 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
6985 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
6986 socket_tcp.check.server = &socket_tcp;
6987
6988 socket_tcp.agent.status = HCHK_STATUS_INI;
6989 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
6990 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
6991 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
6992 socket_tcp.agent.server = &socket_tcp;
6993
6994 socket_tcp.xprt = &raw_sock;
6995
6996#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006997 /* Init TCP server: unchanged parameters */
6998 memset(&socket_ssl, 0, sizeof(socket_ssl));
6999 socket_ssl.next = NULL;
7000 socket_ssl.proxy = &socket_proxy;
7001 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7002 LIST_INIT(&socket_ssl.actconns);
7003 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007004 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007005 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007006 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007007 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
7008 socket_ssl.last_change = 0;
7009 socket_ssl.id = "LUA-SSL-CONN";
7010 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7011 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7012 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7013
7014 /* XXX: Copy default parameter from default server,
7015 * but the default server is not initialized.
7016 */
7017 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7018 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7019 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7020 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7021 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7022 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7023 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7024 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7025 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7026 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7027
7028 socket_ssl.check.status = HCHK_STATUS_INI;
7029 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7030 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7031 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7032 socket_ssl.check.server = &socket_ssl;
7033
7034 socket_ssl.agent.status = HCHK_STATUS_INI;
7035 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7036 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7037 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7038 socket_ssl.agent.server = &socket_ssl;
7039
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007040 socket_ssl.use_ssl = 1;
7041 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007042
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007043 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007044 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7045 /*
7046 *
7047 * If the keyword is not known, we can search in the registered
7048 * server keywords. This is usefull to configure special SSL
7049 * features like client certificates and ssl_verify.
7050 *
7051 */
7052 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7053 if (tmp_error != 0) {
7054 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7055 abort(); /* This must be never arrives because the command line
7056 not editable by the user. */
7057 }
7058 idx += kw->skip;
7059 }
7060 }
7061
7062 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007063 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007064#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007065}