blob: 11117205d86591216c11c2d1765351dbb52b3078 [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 Fournierfb0b5462016-01-21 09:28:58 +010027#include <proto/hlua_fcn.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020028#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010029#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010030#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010031#include <proto/payload.h>
32#include <proto/proto_http.h>
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010033#include <proto/proto_tcp.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010034#include <proto/raw_sock.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010035#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010036#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020037#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020038#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010039#include <proto/ssl_sock.h>
40#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010041#include <proto/task.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020042#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010043
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010044/* Lua uses longjmp to perform yield or throwing errors. This
45 * macro is used only for identifying the function that can
46 * not return because a longjmp is executed.
47 * __LJMP marks a prototype of hlua file that can use longjmp.
48 * WILL_LJMP() marks an lua function that will use longjmp.
49 * MAY_LJMP() marks an lua function that may use longjmp.
50 */
51#define __LJMP
52#define WILL_LJMP(func) func
53#define MAY_LJMP(func) func
54
Thierry FOURNIERbabae282015-09-17 11:36:37 +020055/* This couple of function executes securely some Lua calls outside of
56 * the lua runtime environment. Each Lua call can return a longjmp
57 * if it encounter a memory error.
58 *
59 * Lua documentation extract:
60 *
61 * If an error happens outside any protected environment, Lua calls
62 * a panic function (see lua_atpanic) and then calls abort, thus
63 * exiting the host application. Your panic function can avoid this
64 * exit by never returning (e.g., doing a long jump to your own
65 * recovery point outside Lua).
66 *
67 * The panic function runs as if it were a message handler (see
68 * §2.3); in particular, the error message is at the top of the
69 * stack. However, there is no guarantee about stack space. To push
70 * anything on the stack, the panic function must first check the
71 * available space (see §4.2).
72 *
73 * We must check all the Lua entry point. This includes:
74 * - The include/proto/hlua.h exported functions
75 * - the task wrapper function
76 * - The action wrapper function
77 * - The converters wrapper function
78 * - The sample-fetch wrapper functions
79 *
80 * It is tolerated that the initilisation function returns an abort.
81 * Before each Lua abort, an error message is writed on stderr.
82 *
83 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
84 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
85 * because they must be exists in the program stack when the longjmp
86 * is called.
87 */
88jmp_buf safe_ljmp_env;
89static int hlua_panic_safe(lua_State *L) { return 0; }
90static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
91
92#define SET_SAFE_LJMP(__L) \
93 ({ \
94 int ret; \
95 if (setjmp(safe_ljmp_env) != 0) { \
96 lua_atpanic(__L, hlua_panic_safe); \
97 ret = 0; \
98 } else { \
99 lua_atpanic(__L, hlua_panic_ljmp); \
100 ret = 1; \
101 } \
102 ret; \
103 })
104
105/* If we are the last function catching Lua errors, we
106 * must reset the panic function.
107 */
108#define RESET_SAFE_LJMP(__L) \
109 do { \
110 lua_atpanic(__L, hlua_panic_safe); \
111 } while(0)
112
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200113/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200114#define APPLET_DONE 0x01 /* applet processing is done. */
115#define APPLET_100C 0x02 /* 100 continue expected. */
116#define APPLET_HDR_SENT 0x04 /* Response header sent. */
117#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
118#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100119#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200120
121#define HTTP_100C "HTTP/1.1 100 Continue\r\n\r\n"
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200122
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100123/* The main Lua execution context. */
124struct hlua gL;
125
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100126/* This is the memory pool containing all the signal structs. These
127 * struct are used to store each requiered signal between two tasks.
128 */
129struct pool_head *pool2_hlua_com;
130
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100131/* Used for Socket connection. */
132static struct proxy socket_proxy;
133static struct server socket_tcp;
134#ifdef USE_OPENSSL
135static struct server socket_ssl;
136#endif
137
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100138/* List head of the function called at the initialisation time. */
139struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
140
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100141/* The following variables contains the reference of the different
142 * Lua classes. These references are useful for identify metadata
143 * associated with an object.
144 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100145static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100146static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100147static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100148static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100149static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100150static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200151static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200152static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200153static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100154
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100155/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200156 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100157 * short timeout. Lua linked with tasks doesn't have a timeout
158 * because a task may remain alive during all the haproxy execution.
159 */
160static unsigned int hlua_timeout_session = 4000; /* session timeout. */
161static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200162static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100163
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100164/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
165 * it is used for preventing infinite loops.
166 *
167 * I test the scheer with an infinite loop containing one incrementation
168 * and one test. I run this loop between 10 seconds, I raise a ceil of
169 * 710M loops from one interrupt each 9000 instructions, so I fix the value
170 * to one interrupt each 10 000 instructions.
171 *
172 * configured | Number of
173 * instructions | loops executed
174 * between two | in milions
175 * forced yields |
176 * ---------------+---------------
177 * 10 | 160
178 * 500 | 670
179 * 1000 | 680
180 * 5000 | 700
181 * 7000 | 700
182 * 8000 | 700
183 * 9000 | 710 <- ceil
184 * 10000 | 710
185 * 100000 | 710
186 * 1000000 | 710
187 *
188 */
189static unsigned int hlua_nb_instruction = 10000;
190
Willy Tarreau32f61e22015-03-18 17:54:59 +0100191/* Descriptor for the memory allocation state. If limit is not null, it will
192 * be enforced on any memory allocation.
193 */
194struct hlua_mem_allocator {
195 size_t allocated;
196 size_t limit;
197};
198
199static struct hlua_mem_allocator hlua_global_allocator;
200
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200201static const char error_500[] =
202 "HTTP/1.0 500 Server Error\r\n"
203 "Cache-Control: no-cache\r\n"
204 "Connection: close\r\n"
205 "Content-Type: text/html\r\n"
206 "\r\n"
207 "<html><body><h1>500 Server Error</h1>\nAn internal server error occured.\n</body></html>\n";
208
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100209/* These functions converts types between HAProxy internal args or
210 * sample and LUA types. Another function permits to check if the
211 * LUA stack contains arguments according with an required ARG_T
212 * format.
213 */
214static int hlua_arg2lua(lua_State *L, const struct arg *arg);
215static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100216__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
217 unsigned int mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100218static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100219static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100220static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
221
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200222__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
223
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200224#define SEND_ERR(__be, __fmt, __args...) \
225 do { \
226 send_log(__be, LOG_ERR, __fmt, ## __args); \
227 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
228 Alert(__fmt, ## __args); \
229 } while (0)
230
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100231/* Used to check an Lua function type in the stack. It creates and
232 * returns a reference of the function. This function throws an
233 * error if the rgument is not a "function".
234 */
235__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
236{
237 if (!lua_isfunction(L, argno)) {
238 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
239 WILL_LJMP(luaL_argerror(L, argno, msg));
240 }
241 lua_pushvalue(L, argno);
242 return luaL_ref(L, LUA_REGISTRYINDEX);
243}
244
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200245/* Return the string that is of the top of the stack. */
246const char *hlua_get_top_error_string(lua_State *L)
247{
248 if (lua_gettop(L) < 1)
249 return "unknown error";
250 if (lua_type(L, -1) != LUA_TSTRING)
251 return "unknown error";
252 return lua_tostring(L, -1);
253}
254
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100255/* The three following functions are useful for adding entries
256 * in a table. These functions takes a string and respectively an
257 * integer, a string or a function and add it to the table in the
258 * top of the stack.
259 *
260 * These functions throws an error if no more stack size is
261 * available.
262 */
263__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100264 int value)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100265{
266 if (!lua_checkstack(L, 2))
267 WILL_LJMP(luaL_error(L, "full stack"));
268 lua_pushstring(L, name);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100269 lua_pushinteger(L, value);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +0200270 lua_rawset(L, -3);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100271}
272__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
273 const char *value)
274{
275 if (!lua_checkstack(L, 2))
276 WILL_LJMP(luaL_error(L, "full stack"));
277 lua_pushstring(L, name);
278 lua_pushstring(L, value);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +0200279 lua_rawset(L, -3);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100280}
281__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
282 int (*function)(lua_State *L))
283{
284 if (!lua_checkstack(L, 2))
285 WILL_LJMP(luaL_error(L, "full stack"));
286 lua_pushstring(L, name);
287 lua_pushcclosure(L, function, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +0200288 lua_rawset(L, -3);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100289}
290
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +0200291__LJMP static int hlua_dump_object(struct lua_State *L)
292{
293 const char *name = (const char *)lua_tostring(L, lua_upvalueindex(1));
294 lua_pushfstring(L, "HAProxy class %s", name);
295 return 1;
296}
297
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100298/* This function check the number of arguments available in the
299 * stack. If the number of arguments available is not the same
300 * then <nb> an error is throwed.
301 */
302__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
303{
304 if (lua_gettop(L) == nb)
305 return;
306 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
307}
308
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100309/* This fucntion push an error string prefixed by the file name
310 * and the line number where the error is encountered.
311 */
312static int hlua_pusherror(lua_State *L, const char *fmt, ...)
313{
314 va_list argp;
315 va_start(argp, fmt);
316 luaL_where(L, 1);
317 lua_pushvfstring(L, fmt, argp);
318 va_end(argp);
319 lua_concat(L, 2);
320 return 1;
321}
322
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100323/* This function register a new signal. "lua" is the current lua
324 * execution context. It contains a pointer to the associated task.
325 * "link" is a list head attached to an other task that must be wake
326 * the lua task if an event occurs. This is useful with external
327 * events like TCP I/O or sleep functions. This funcion allocate
328 * memory for the signal.
329 */
330static int hlua_com_new(struct hlua *lua, struct list *link)
331{
332 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
333 if (!com)
334 return 0;
335 LIST_ADDQ(&lua->com, &com->purge_me);
336 LIST_ADDQ(link, &com->wake_me);
337 com->task = lua->task;
338 return 1;
339}
340
341/* This function purge all the pending signals when the LUA execution
342 * is finished. This prevent than a coprocess try to wake a deleted
343 * task. This function remove the memory associated to the signal.
344 */
345static void hlua_com_purge(struct hlua *lua)
346{
347 struct hlua_com *com, *back;
348
349 /* Delete all pending communication signals. */
350 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
351 LIST_DEL(&com->purge_me);
352 LIST_DEL(&com->wake_me);
353 pool_free2(pool2_hlua_com, com);
354 }
355}
356
357/* This function sends signals. It wakes all the tasks attached
358 * to a list head, and remove the signal, and free the used
359 * memory.
360 */
361static void hlua_com_wake(struct list *wake)
362{
363 struct hlua_com *com, *back;
364
365 /* Wake task and delete all pending communication signals. */
366 list_for_each_entry_safe(com, back, wake, wake_me) {
367 LIST_DEL(&com->purge_me);
368 LIST_DEL(&com->wake_me);
369 task_wakeup(com->task, TASK_WOKEN_MSG);
370 pool_free2(pool2_hlua_com, com);
371 }
372}
373
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100374/* This functions is used with sample fetch and converters. It
375 * converts the HAProxy configuration argument in a lua stack
376 * values.
377 *
378 * It takes an array of "arg", and each entry of the array is
379 * converted and pushed in the LUA stack.
380 */
381static int hlua_arg2lua(lua_State *L, const struct arg *arg)
382{
383 switch (arg->type) {
384 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100385 case ARGT_TIME:
386 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100387 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100388 break;
389
390 case ARGT_STR:
391 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
392 break;
393
394 case ARGT_IPV4:
395 case ARGT_IPV6:
396 case ARGT_MSK4:
397 case ARGT_MSK6:
398 case ARGT_FE:
399 case ARGT_BE:
400 case ARGT_TAB:
401 case ARGT_SRV:
402 case ARGT_USR:
403 case ARGT_MAP:
404 default:
405 lua_pushnil(L);
406 break;
407 }
408 return 1;
409}
410
411/* This function take one entrie in an LUA stack at the index "ud",
412 * and try to convert it in an HAProxy argument entry. This is useful
413 * with sample fetch wrappers. The input arguments are gived to the
414 * lua wrapper and converted as arg list by thi function.
415 */
416static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
417{
418 switch (lua_type(L, ud)) {
419
420 case LUA_TNUMBER:
421 case LUA_TBOOLEAN:
422 arg->type = ARGT_SINT;
423 arg->data.sint = lua_tointeger(L, ud);
424 break;
425
426 case LUA_TSTRING:
427 arg->type = ARGT_STR;
428 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
429 break;
430
431 case LUA_TUSERDATA:
432 case LUA_TNIL:
433 case LUA_TTABLE:
434 case LUA_TFUNCTION:
435 case LUA_TTHREAD:
436 case LUA_TLIGHTUSERDATA:
437 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200438 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100439 break;
440 }
441 return 1;
442}
443
444/* the following functions are used to convert a struct sample
445 * in Lua type. This useful to convert the return of the
446 * fetchs or converters.
447 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100448static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100449{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200450 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100451 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100452 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200453 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100454 break;
455
456 case SMP_T_BIN:
457 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200458 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100459 break;
460
461 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200462 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100463 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
464 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
465 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
466 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
467 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
468 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
469 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
470 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
471 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200472 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100473 break;
474 default:
475 lua_pushnil(L);
476 break;
477 }
478 break;
479
480 case SMP_T_IPV4:
481 case SMP_T_IPV6:
482 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200483 if (sample_casts[smp->data.type][SMP_T_STR] &&
484 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200485 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100486 else
487 lua_pushnil(L);
488 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100489 default:
490 lua_pushnil(L);
491 break;
492 }
493 return 1;
494}
495
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100496/* the following functions are used to convert a struct sample
497 * in Lua strings. This is useful to convert the return of the
498 * fetchs or converters.
499 */
500static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
501{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200502 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100503
504 case SMP_T_BIN:
505 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200506 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100507 break;
508
509 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200510 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100511 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
512 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
513 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
514 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
515 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
516 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
517 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
518 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
519 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200520 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100521 break;
522 default:
523 lua_pushstring(L, "");
524 break;
525 }
526 break;
527
528 case SMP_T_SINT:
529 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100530 case SMP_T_IPV4:
531 case SMP_T_IPV6:
532 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200533 if (sample_casts[smp->data.type][SMP_T_STR] &&
534 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200535 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100536 else
537 lua_pushstring(L, "");
538 break;
539 default:
540 lua_pushstring(L, "");
541 break;
542 }
543 return 1;
544}
545
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100546/* the following functions are used to convert an Lua type in a
547 * struct sample. This is useful to provide data from a converter
548 * to the LUA code.
549 */
550static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
551{
552 switch (lua_type(L, ud)) {
553
554 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200555 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200556 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100557 break;
558
559
560 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200561 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200562 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100563 break;
564
565 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200566 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100567 smp->flags |= SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200568 smp->data.u.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100569 break;
570
571 case LUA_TUSERDATA:
572 case LUA_TNIL:
573 case LUA_TTABLE:
574 case LUA_TFUNCTION:
575 case LUA_TTHREAD:
576 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200577 case LUA_TNONE:
578 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200579 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200580 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100581 break;
582 }
583 return 1;
584}
585
586/* This function check the "argp" builded by another conversion function
587 * is in accord with the expected argp defined by the "mask". The fucntion
588 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100589 *
590 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
591 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100592 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100593__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
594 unsigned int mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100595{
596 int min_arg;
597 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100598 struct proxy *px;
599 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100600
601 idx = 0;
602 min_arg = ARGM(mask);
603 mask >>= ARGM_BITS;
604
605 while (1) {
606
607 /* Check oversize. */
608 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100609 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100610 }
611
612 /* Check for mandatory arguments. */
613 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100614 if (idx < min_arg) {
615
616 /* If miss other argument than the first one, we return an error. */
617 if (idx > 0)
618 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
619
620 /* If first argument have a certain type, some default values
621 * may be used. See the function smp_resolve_args().
622 */
623 switch (mask & ARGT_MASK) {
624
625 case ARGT_FE:
626 if (!(p->cap & PR_CAP_FE))
627 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
628 argp[idx].data.prx = p;
629 argp[idx].type = ARGT_FE;
630 argp[idx+1].type = ARGT_STOP;
631 break;
632
633 case ARGT_BE:
634 if (!(p->cap & PR_CAP_BE))
635 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
636 argp[idx].data.prx = p;
637 argp[idx].type = ARGT_BE;
638 argp[idx+1].type = ARGT_STOP;
639 break;
640
641 case ARGT_TAB:
642 argp[idx].data.prx = p;
643 argp[idx].type = ARGT_TAB;
644 argp[idx+1].type = ARGT_STOP;
645 break;
646
647 default:
648 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
649 break;
650 }
651 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100652 return 0;
653 }
654
655 /* Check for exceed the number of requiered argument. */
656 if ((mask & ARGT_MASK) == ARGT_STOP &&
657 argp[idx].type != ARGT_STOP) {
658 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
659 }
660
661 if ((mask & ARGT_MASK) == ARGT_STOP &&
662 argp[idx].type == ARGT_STOP) {
663 return 0;
664 }
665
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100666 /* Convert some argument types. */
667 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100668 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100669 if (argp[idx].type != ARGT_SINT)
670 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
671 argp[idx].type = ARGT_SINT;
672 break;
673
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100674 case ARGT_TIME:
675 if (argp[idx].type != ARGT_SINT)
676 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200677 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100678 break;
679
680 case ARGT_SIZE:
681 if (argp[idx].type != ARGT_SINT)
682 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200683 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100684 break;
685
686 case ARGT_FE:
687 if (argp[idx].type != ARGT_STR)
688 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
689 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
690 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200691 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100692 if (!argp[idx].data.prx)
693 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
694 argp[idx].type = ARGT_FE;
695 break;
696
697 case ARGT_BE:
698 if (argp[idx].type != ARGT_STR)
699 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
700 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
701 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200702 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100703 if (!argp[idx].data.prx)
704 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
705 argp[idx].type = ARGT_BE;
706 break;
707
708 case ARGT_TAB:
709 if (argp[idx].type != ARGT_STR)
710 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
711 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
712 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200713 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100714 if (!argp[idx].data.prx)
715 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
716 argp[idx].type = ARGT_TAB;
717 break;
718
719 case ARGT_SRV:
720 if (argp[idx].type != ARGT_STR)
721 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
722 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
723 trash.str[argp[idx].data.str.len] = 0;
724 sname = strrchr(trash.str, '/');
725 if (sname) {
726 *sname++ = '\0';
727 pname = trash.str;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200728 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100729 if (!px)
730 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
731 }
732 else {
733 sname = trash.str;
734 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100735 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100736 argp[idx].data.srv = findserver(px, sname);
737 if (!argp[idx].data.srv)
738 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
739 argp[idx].type = ARGT_SRV;
740 break;
741
742 case ARGT_IPV4:
743 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
744 trash.str[argp[idx].data.str.len] = 0;
745 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
746 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
747 argp[idx].type = ARGT_IPV4;
748 break;
749
750 case ARGT_MSK4:
751 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
752 trash.str[argp[idx].data.str.len] = 0;
753 if (!str2mask(trash.str, &argp[idx].data.ipv4))
754 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
755 argp[idx].type = ARGT_MSK4;
756 break;
757
758 case ARGT_IPV6:
759 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
760 trash.str[argp[idx].data.str.len] = 0;
761 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
762 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
763 argp[idx].type = ARGT_IPV6;
764 break;
765
766 case ARGT_MSK6:
767 case ARGT_MAP:
768 case ARGT_REG:
769 case ARGT_USR:
770 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100771 break;
772 }
773
774 /* Check for type of argument. */
775 if ((mask & ARGT_MASK) != argp[idx].type) {
776 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
777 arg_type_names[(mask & ARGT_MASK)],
778 arg_type_names[argp[idx].type & ARGT_MASK]);
779 WILL_LJMP(luaL_argerror(L, first + idx, msg));
780 }
781
782 /* Next argument. */
783 mask >>= ARGT_BITS;
784 idx++;
785 }
786}
787
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100788/*
789 * The following functions are used to make correspondance between the the
790 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100791 *
792 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100793 * - hlua_sethlua : create the association between hlua context and lua_state.
794 */
795static inline struct hlua *hlua_gethlua(lua_State *L)
796{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100797 struct hlua **hlua = lua_getextraspace(L);
798 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100799}
800static inline void hlua_sethlua(struct hlua *hlua)
801{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100802 struct hlua **hlua_store = lua_getextraspace(hlua->T);
803 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100804}
805
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100806/* This function is used to send logs. It try to send on screen (stderr)
807 * and on the default syslog server.
808 */
809static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
810{
811 struct tm tm;
812 char *p;
813
814 /* Cleanup the log message. */
815 p = trash.str;
816 for (; *msg != '\0'; msg++, p++) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200817 if (p >= trash.str + trash.size - 1) {
818 /* Break the message if exceed the buffer size. */
819 *(p-4) = ' ';
820 *(p-3) = '.';
821 *(p-2) = '.';
822 *(p-1) = '.';
823 break;
824 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100825 if (isprint(*msg))
826 *p = *msg;
827 else
828 *p = '.';
829 }
830 *p = '\0';
831
Thierry FOURNIER5554e292015-09-09 11:21:37 +0200832 send_log(px, level, "%s\n", trash.str);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100833 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200834 get_localtime(date.tv_sec, &tm);
835 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100836 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
837 (int)getpid(), trash.str);
838 fflush(stderr);
839 }
840}
841
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100842/* This function just ensure that the yield will be always
843 * returned with a timeout and permit to set some flags
844 */
845__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100846 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100847{
848 struct hlua *hlua = hlua_gethlua(L);
849
850 /* Set the wake timeout. If timeout is required, we set
851 * the expiration time.
852 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200853 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100854
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100855 hlua->flags |= flags;
856
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100857 /* Process the yield. */
858 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
859}
860
Willy Tarreau87b09662015-04-03 00:22:06 +0200861/* This function initialises the Lua environment stored in the stream.
862 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100863 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200864 *
865 * This function is particular. it initialises a new Lua thread. If the
866 * initialisation fails (example: out of memory error), the lua function
867 * throws an error (longjmp).
868 *
869 * This function manipulates two Lua stack: the main and the thread. Only
870 * the main stack can fail. The thread is not manipulated. This function
871 * MUST NOT manipulate the created thread stack state, because is not
872 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100873 */
874int hlua_ctx_init(struct hlua *lua, struct task *task)
875{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200876 if (!SET_SAFE_LJMP(gL.T)) {
877 lua->Tref = LUA_REFNIL;
878 return 0;
879 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100880 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100881 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100882 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100883 lua->T = lua_newthread(gL.T);
884 if (!lua->T) {
885 lua->Tref = LUA_REFNIL;
886 return 0;
887 }
888 hlua_sethlua(lua);
889 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
890 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200891 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100892 return 1;
893}
894
Willy Tarreau87b09662015-04-03 00:22:06 +0200895/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100896 * is destroyed. The destroy also the memory context. The struct "lua"
897 * is not freed.
898 */
899void hlua_ctx_destroy(struct hlua *lua)
900{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100901 if (!lua->T)
902 return;
903
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100904 /* Purge all the pending signals. */
905 hlua_com_purge(lua);
906
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100907 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
908 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200909
910 /* Forces a garbage collecting process. If the Lua program is finished
911 * without error, we run the GC on the thread pointer. Its freed all
912 * the unused memory.
913 * If the thread is finnish with an error or is currently yielded,
914 * it seems that the GC applied on the thread doesn't clean anything,
915 * so e run the GC on the main thread.
916 * NOTE: maybe this action locks all the Lua threads untiml the en of
917 * the garbage collection.
918 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200919 if (lua->flags & HLUA_MUST_GC) {
920 lua_gc(lua->T, LUA_GCCOLLECT, 0);
921 if (lua_status(lua->T) != LUA_OK)
922 lua_gc(gL.T, LUA_GCCOLLECT, 0);
923 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200924
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200925 lua->T = NULL;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100926}
927
928/* This function is used to restore the Lua context when a coroutine
929 * fails. This function copy the common memory between old coroutine
930 * and the new coroutine. The old coroutine is destroyed, and its
931 * replaced by the new coroutine.
932 * If the flag "keep_msg" is set, the last entry of the old is assumed
933 * as string error message and it is copied in the new stack.
934 */
935static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
936{
937 lua_State *T;
938 int new_ref;
939
940 /* Renew the main LUA stack doesn't have sense. */
941 if (lua == &gL)
942 return 0;
943
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100944 /* New Lua coroutine. */
945 T = lua_newthread(gL.T);
946 if (!T)
947 return 0;
948
949 /* Copy last error message. */
950 if (keep_msg)
951 lua_xmove(lua->T, T, 1);
952
953 /* Copy data between the coroutines. */
954 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
955 lua_xmove(lua->T, T, 1);
956 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
957
958 /* Destroy old data. */
959 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
960
961 /* The thread is garbage collected by Lua. */
962 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
963
964 /* Fill the struct with the new coroutine values. */
965 lua->Mref = new_ref;
966 lua->T = T;
967 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
968
969 /* Set context. */
970 hlua_sethlua(lua);
971
972 return 1;
973}
974
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100975void hlua_hook(lua_State *L, lua_Debug *ar)
976{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100977 struct hlua *hlua = hlua_gethlua(L);
978
979 /* Lua cannot yield when its returning from a function,
980 * so, we can fix the interrupt hook to 1 instruction,
981 * expecting that the function is finnished.
982 */
983 if (lua_gethookmask(L) & LUA_MASKRET) {
984 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
985 return;
986 }
987
988 /* restore the interrupt condition. */
989 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
990
991 /* If we interrupt the Lua processing in yieldable state, we yield.
992 * If the state is not yieldable, trying yield causes an error.
993 */
994 if (lua_isyieldable(L))
995 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
996
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +0100997 /* If we cannot yield, update the clock and check the timeout. */
998 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200999 hlua->run_time += now_ms - hlua->start_time;
1000 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001001 lua_pushfstring(L, "execution timeout");
1002 WILL_LJMP(lua_error(L));
1003 }
1004
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001005 /* Update the start time. */
1006 hlua->start_time = now_ms;
1007
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001008 /* Try to interrupt the process at the end of the current
1009 * unyieldable function.
1010 */
1011 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001012}
1013
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001014/* This function start or resumes the Lua stack execution. If the flag
1015 * "yield_allowed" if no set and the LUA stack execution returns a yield
1016 * The function return an error.
1017 *
1018 * The function can returns 4 values:
1019 * - HLUA_E_OK : The execution is terminated without any errors.
1020 * - HLUA_E_AGAIN : The execution must continue at the next associated
1021 * task wakeup.
1022 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
1023 * the top of the stack.
1024 * - HLUA_E_ERR : An error has occured without error message.
1025 *
1026 * If an error occured, the stack is renewed and it is ready to run new
1027 * LUA code.
1028 */
1029static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1030{
1031 int ret;
1032 const char *msg;
1033
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001034 /* Initialise run time counter. */
1035 if (!HLUA_IS_RUNNING(lua))
1036 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001037
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001038resume_execution:
1039
1040 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1041 * instructions. it is used for preventing infinite loops.
1042 */
1043 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1044
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001045 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001046 HLUA_SET_RUN(lua);
1047 HLUA_CLR_CTRLYIELD(lua);
1048 HLUA_CLR_WAKERESWR(lua);
1049 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001050
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001051 /* Update the start time. */
1052 lua->start_time = now_ms;
1053
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001054 /* Call the function. */
1055 ret = lua_resume(lua->T, gL.T, lua->nargs);
1056 switch (ret) {
1057
1058 case LUA_OK:
1059 ret = HLUA_E_OK;
1060 break;
1061
1062 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001063 /* Check if the execution timeout is expired. It it is the case, we
1064 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001065 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001066 tv_update_date(0, 1);
1067 lua->run_time += now_ms - lua->start_time;
1068 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001069 lua_settop(lua->T, 0); /* Empty the stack. */
1070 if (!lua_checkstack(lua->T, 1)) {
1071 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001072 break;
1073 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001074 lua_pushfstring(lua->T, "execution timeout");
1075 ret = HLUA_E_ERRMSG;
1076 break;
1077 }
1078 /* Process the forced yield. if the general yield is not allowed or
1079 * if no task were associated this the current Lua execution
1080 * coroutine, we resume the execution. Else we want to return in the
1081 * scheduler and we want to be waked up again, to continue the
1082 * current Lua execution. So we schedule our own task.
1083 */
1084 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001085 if (!yield_allowed || !lua->task)
1086 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001087 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001088 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001089 if (!yield_allowed) {
1090 lua_settop(lua->T, 0); /* Empty the stack. */
1091 if (!lua_checkstack(lua->T, 1)) {
1092 ret = HLUA_E_ERR;
1093 break;
1094 }
1095 lua_pushfstring(lua->T, "yield not allowed");
1096 ret = HLUA_E_ERRMSG;
1097 break;
1098 }
1099 ret = HLUA_E_AGAIN;
1100 break;
1101
1102 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001103
1104 /* Special exit case. The traditionnal exit is returned as an error
1105 * because the errors ares the only one mean to return immediately
1106 * from and lua execution.
1107 */
1108 if (lua->flags & HLUA_EXIT) {
1109 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001110 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001111 break;
1112 }
1113
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001114 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001115 if (!lua_checkstack(lua->T, 1)) {
1116 ret = HLUA_E_ERR;
1117 break;
1118 }
1119 msg = lua_tostring(lua->T, -1);
1120 lua_settop(lua->T, 0); /* Empty the stack. */
1121 lua_pop(lua->T, 1);
1122 if (msg)
1123 lua_pushfstring(lua->T, "runtime error: %s", msg);
1124 else
1125 lua_pushfstring(lua->T, "unknown runtime error");
1126 ret = HLUA_E_ERRMSG;
1127 break;
1128
1129 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001130 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001131 lua_settop(lua->T, 0); /* Empty the stack. */
1132 if (!lua_checkstack(lua->T, 1)) {
1133 ret = HLUA_E_ERR;
1134 break;
1135 }
1136 lua_pushfstring(lua->T, "out of memory error");
1137 ret = HLUA_E_ERRMSG;
1138 break;
1139
1140 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001141 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001142 if (!lua_checkstack(lua->T, 1)) {
1143 ret = HLUA_E_ERR;
1144 break;
1145 }
1146 msg = lua_tostring(lua->T, -1);
1147 lua_settop(lua->T, 0); /* Empty the stack. */
1148 lua_pop(lua->T, 1);
1149 if (msg)
1150 lua_pushfstring(lua->T, "message handler error: %s", msg);
1151 else
1152 lua_pushfstring(lua->T, "message handler error");
1153 ret = HLUA_E_ERRMSG;
1154 break;
1155
1156 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001157 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001158 lua_settop(lua->T, 0); /* Empty the stack. */
1159 if (!lua_checkstack(lua->T, 1)) {
1160 ret = HLUA_E_ERR;
1161 break;
1162 }
1163 lua_pushfstring(lua->T, "unknonwn error");
1164 ret = HLUA_E_ERRMSG;
1165 break;
1166 }
1167
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001168 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001169 if (lua->flags & HLUA_MUST_GC &&
1170 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001171 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1172
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001173 switch (ret) {
1174 case HLUA_E_AGAIN:
1175 break;
1176
1177 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001178 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001179 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001180 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001181 break;
1182
1183 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001184 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001185 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001186 hlua_ctx_renew(lua, 0);
1187 break;
1188
1189 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001190 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001191 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001192 break;
1193 }
1194
1195 return ret;
1196}
1197
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001198/* This function exit the current code. */
1199__LJMP static int hlua_done(lua_State *L)
1200{
1201 struct hlua *hlua = hlua_gethlua(L);
1202
1203 hlua->flags |= HLUA_EXIT;
1204 WILL_LJMP(lua_error(L));
1205
1206 return 0;
1207}
1208
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001209/* This function is an LUA binding. It provides a function
1210 * for deleting ACL from a referenced ACL file.
1211 */
1212__LJMP static int hlua_del_acl(lua_State *L)
1213{
1214 const char *name;
1215 const char *key;
1216 struct pat_ref *ref;
1217
1218 MAY_LJMP(check_args(L, 2, "del_acl"));
1219
1220 name = MAY_LJMP(luaL_checkstring(L, 1));
1221 key = MAY_LJMP(luaL_checkstring(L, 2));
1222
1223 ref = pat_ref_lookup(name);
1224 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001225 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001226
1227 pat_ref_delete(ref, key);
1228 return 0;
1229}
1230
1231/* This function is an LUA binding. It provides a function
1232 * for deleting map entry from a referenced map file.
1233 */
1234static int hlua_del_map(lua_State *L)
1235{
1236 const char *name;
1237 const char *key;
1238 struct pat_ref *ref;
1239
1240 MAY_LJMP(check_args(L, 2, "del_map"));
1241
1242 name = MAY_LJMP(luaL_checkstring(L, 1));
1243 key = MAY_LJMP(luaL_checkstring(L, 2));
1244
1245 ref = pat_ref_lookup(name);
1246 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001247 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001248
1249 pat_ref_delete(ref, key);
1250 return 0;
1251}
1252
1253/* This function is an LUA binding. It provides a function
1254 * for adding ACL pattern from a referenced ACL file.
1255 */
1256static int hlua_add_acl(lua_State *L)
1257{
1258 const char *name;
1259 const char *key;
1260 struct pat_ref *ref;
1261
1262 MAY_LJMP(check_args(L, 2, "add_acl"));
1263
1264 name = MAY_LJMP(luaL_checkstring(L, 1));
1265 key = MAY_LJMP(luaL_checkstring(L, 2));
1266
1267 ref = pat_ref_lookup(name);
1268 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001269 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001270
1271 if (pat_ref_find_elt(ref, key) == NULL)
1272 pat_ref_add(ref, key, NULL, NULL);
1273 return 0;
1274}
1275
1276/* This function is an LUA binding. It provides a function
1277 * for setting map pattern and sample from a referenced map
1278 * file.
1279 */
1280static int hlua_set_map(lua_State *L)
1281{
1282 const char *name;
1283 const char *key;
1284 const char *value;
1285 struct pat_ref *ref;
1286
1287 MAY_LJMP(check_args(L, 3, "set_map"));
1288
1289 name = MAY_LJMP(luaL_checkstring(L, 1));
1290 key = MAY_LJMP(luaL_checkstring(L, 2));
1291 value = MAY_LJMP(luaL_checkstring(L, 3));
1292
1293 ref = pat_ref_lookup(name);
1294 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001295 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001296
1297 if (pat_ref_find_elt(ref, key) != NULL)
1298 pat_ref_set(ref, key, value, NULL);
1299 else
1300 pat_ref_add(ref, key, value, NULL);
1301 return 0;
1302}
1303
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001304/* A class is a lot of memory that contain data. This data can be a table,
1305 * an integer or user data. This data is associated with a metatable. This
1306 * metatable have an original version registred in the global context with
1307 * the name of the object (_G[<name>] = <metable> ).
1308 *
1309 * A metable is a table that modify the standard behavior of a standard
1310 * access to the associated data. The entries of this new metatable are
1311 * defined as is:
1312 *
1313 * http://lua-users.org/wiki/MetatableEvents
1314 *
1315 * __index
1316 *
1317 * we access an absent field in a table, the result is nil. This is
1318 * true, but it is not the whole truth. Actually, such access triggers
1319 * the interpreter to look for an __index metamethod: If there is no
1320 * such method, as usually happens, then the access results in nil;
1321 * otherwise, the metamethod will provide the result.
1322 *
1323 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1324 * the key does not appear in the table, but the metatable has an __index
1325 * property:
1326 *
1327 * - if the value is a function, the function is called, passing in the
1328 * table and the key; the return value of that function is returned as
1329 * the result.
1330 *
1331 * - if the value is another table, the value of the key in that table is
1332 * asked for and returned (and if it doesn't exist in that table, but that
1333 * table's metatable has an __index property, then it continues on up)
1334 *
1335 * - Use "rawget(myTable,key)" to skip this metamethod.
1336 *
1337 * http://www.lua.org/pil/13.4.1.html
1338 *
1339 * __newindex
1340 *
1341 * Like __index, but control property assignment.
1342 *
1343 * __mode - Control weak references. A string value with one or both
1344 * of the characters 'k' and 'v' which specifies that the the
1345 * keys and/or values in the table are weak references.
1346 *
1347 * __call - Treat a table like a function. When a table is followed by
1348 * parenthesis such as "myTable( 'foo' )" and the metatable has
1349 * a __call key pointing to a function, that function is invoked
1350 * (passing any specified arguments) and the return value is
1351 * returned.
1352 *
1353 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1354 * called, if the metatable for myTable has a __metatable
1355 * key, the value of that key is returned instead of the
1356 * actual metatable.
1357 *
1358 * __tostring - Control string representation. When the builtin
1359 * "tostring( myTable )" function is called, if the metatable
1360 * for myTable has a __tostring property set to a function,
1361 * that function is invoked (passing myTable to it) and the
1362 * return value is used as the string representation.
1363 *
1364 * __len - Control table length. When the table length is requested using
1365 * the length operator ( '#' ), if the metatable for myTable has
1366 * a __len key pointing to a function, that function is invoked
1367 * (passing myTable to it) and the return value used as the value
1368 * of "#myTable".
1369 *
1370 * __gc - Userdata finalizer code. When userdata is set to be garbage
1371 * collected, if the metatable has a __gc field pointing to a
1372 * function, that function is first invoked, passing the userdata
1373 * to it. The __gc metamethod is not called for tables.
1374 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1375 *
1376 * Special metamethods for redefining standard operators:
1377 * http://www.lua.org/pil/13.1.html
1378 *
1379 * __add "+"
1380 * __sub "-"
1381 * __mul "*"
1382 * __div "/"
1383 * __unm "!"
1384 * __pow "^"
1385 * __concat ".."
1386 *
1387 * Special methods for redfining standar relations
1388 * http://www.lua.org/pil/13.2.html
1389 *
1390 * __eq "=="
1391 * __lt "<"
1392 * __le "<="
1393 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001394
1395/*
1396 *
1397 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001398 * Class Map
1399 *
1400 *
1401 */
1402
1403/* Returns a struct hlua_map if the stack entry "ud" is
1404 * a class session, otherwise it throws an error.
1405 */
1406__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1407{
1408 return (struct map_descriptor *)MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
1409}
1410
1411/* This function is the map constructor. It don't need
1412 * the class Map object. It creates and return a new Map
1413 * object. It must be called only during "body" or "init"
1414 * context because it process some filesystem accesses.
1415 */
1416__LJMP static int hlua_map_new(struct lua_State *L)
1417{
1418 const char *fn;
1419 int match = PAT_MATCH_STR;
1420 struct sample_conv conv;
1421 const char *file = "";
1422 int line = 0;
1423 lua_Debug ar;
1424 char *err = NULL;
1425 struct arg args[2];
1426
1427 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1428 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1429
1430 fn = MAY_LJMP(luaL_checkstring(L, 1));
1431
1432 if (lua_gettop(L) >= 2) {
1433 match = MAY_LJMP(luaL_checkinteger(L, 2));
1434 if (match < 0 || match >= PAT_MATCH_NUM)
1435 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1436 }
1437
1438 /* Get Lua filename and line number. */
1439 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1440 lua_getinfo(L, "Sl", &ar); /* get info about it */
1441 if (ar.currentline > 0) { /* is there info? */
1442 file = ar.short_src;
1443 line = ar.currentline;
1444 }
1445 }
1446
1447 /* fill fake sample_conv struct. */
1448 conv.kw = ""; /* unused. */
1449 conv.process = NULL; /* unused. */
1450 conv.arg_mask = 0; /* unused. */
1451 conv.val_args = NULL; /* unused. */
1452 conv.out_type = SMP_T_STR;
1453 conv.private = (void *)(long)match;
1454 switch (match) {
1455 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1456 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1457 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1458 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1459 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1460 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1461 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001462 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001463 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1464 default:
1465 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1466 }
1467
1468 /* fill fake args. */
1469 args[0].type = ARGT_STR;
1470 args[0].data.str.str = (char *)fn;
1471 args[1].type = ARGT_STOP;
1472
1473 /* load the map. */
1474 if (!sample_load_map(args, &conv, file, line, &err)) {
1475 /* error case: we cant use luaL_error because we must
1476 * free the err variable.
1477 */
1478 luaL_where(L, 1);
1479 lua_pushfstring(L, "'new': %s.", err);
1480 lua_concat(L, 2);
1481 free(err);
1482 WILL_LJMP(lua_error(L));
1483 }
1484
1485 /* create the lua object. */
1486 lua_newtable(L);
1487 lua_pushlightuserdata(L, args[0].data.map);
1488 lua_rawseti(L, -2, 0);
1489
1490 /* Pop a class Map metatable and affect it to the userdata. */
1491 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1492 lua_setmetatable(L, -2);
1493
1494
1495 return 1;
1496}
1497
1498__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1499{
1500 struct map_descriptor *desc;
1501 struct pattern *pat;
1502 struct sample smp;
1503
1504 MAY_LJMP(check_args(L, 2, "lookup"));
1505 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001506 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001507 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001508 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001509 }
1510 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001511 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001512 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001513 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 +02001514 }
1515
1516 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001517 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001518 if (str)
1519 lua_pushstring(L, "");
1520 else
1521 lua_pushnil(L);
1522 return 1;
1523 }
1524
1525 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001526 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001527 return 1;
1528}
1529
1530__LJMP static int hlua_map_lookup(struct lua_State *L)
1531{
1532 return _hlua_map_lookup(L, 0);
1533}
1534
1535__LJMP static int hlua_map_slookup(struct lua_State *L)
1536{
1537 return _hlua_map_lookup(L, 1);
1538}
1539
1540/*
1541 *
1542 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001543 * Class Socket
1544 *
1545 *
1546 */
1547
1548__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1549{
1550 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1551}
1552
1553/* This function is the handler called for each I/O on the established
1554 * connection. It is used for notify space avalaible to send or data
1555 * received.
1556 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001557static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001558{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001559 struct stream_interface *si = appctx->owner;
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001560 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001561
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001562 /* If the connection object is not avalaible, close all the
1563 * streams and wakeup everithing waiting for.
1564 */
1565 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001566 si_shutw(si);
1567 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001568 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001569 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1570 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001571 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001572 }
1573
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001574 /* If we cant write, wakeup the pending write signals. */
1575 if (channel_output_closed(si_ic(si)))
1576 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1577
1578 /* If we cant read, wakeup the pending read signals. */
1579 if (channel_input_closed(si_oc(si)))
1580 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1581
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001582 /* if the connection is not estabkished, inform the stream that we want
1583 * to be notified whenever the connection completes.
1584 */
1585 if (!(c->flags & CO_FL_CONNECTED)) {
1586 si_applet_cant_get(si);
1587 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001588 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001589 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001590
1591 /* This function is called after the connect. */
1592 appctx->ctx.hlua.connected = 1;
1593
1594 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001595 if (channel_may_recv(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001596 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1597
1598 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001599 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001600 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1601}
1602
Willy Tarreau87b09662015-04-03 00:22:06 +02001603/* This function is called when the "struct stream" is destroyed.
1604 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001605 * Wake all the pending signals.
1606 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001607static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001608{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001609 /* Remove my link in the original object. */
1610 if (appctx->ctx.hlua.socket)
1611 appctx->ctx.hlua.socket->s = NULL;
1612
1613 /* Wake all the task waiting for me. */
1614 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1615 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1616}
1617
1618/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001619 * uses this object. If the stream does not exists, just quit.
1620 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001621 * pending signal can rest in the read and write lists. destroy
1622 * it.
1623 */
1624__LJMP static int hlua_socket_gc(lua_State *L)
1625{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001626 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001627 struct appctx *appctx;
1628
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001629 MAY_LJMP(check_args(L, 1, "__gc"));
1630
1631 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001632 if (!socket->s)
1633 return 0;
1634
Willy Tarreau87b09662015-04-03 00:22:06 +02001635 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001636 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaue7dff022015-04-03 01:14:29 +02001637 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001638 socket->s = NULL;
1639 appctx->ctx.hlua.socket = NULL;
1640
1641 return 0;
1642}
1643
1644/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001645 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001646 */
1647__LJMP static int hlua_socket_close(lua_State *L)
1648{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001649 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001650 struct appctx *appctx;
1651
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001652 MAY_LJMP(check_args(L, 1, "close"));
1653
1654 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001655 if (!socket->s)
1656 return 0;
1657
Willy Tarreau87b09662015-04-03 00:22:06 +02001658 /* Close the stream and remove the associated stop task. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02001659 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001660 appctx = objt_appctx(socket->s->si[0].end);
1661 appctx->ctx.hlua.socket = NULL;
1662 socket->s = NULL;
1663
1664 return 0;
1665}
1666
1667/* This Lua function assumes that the stack contain three parameters.
1668 * 1 - USERDATA containing a struct socket
1669 * 2 - INTEGER with values of the macro defined below
1670 * If the integer is -1, we must read at most one line.
1671 * If the integer is -2, we ust read all the data until the
1672 * end of the stream.
1673 * If the integer is positive value, we must read a number of
1674 * bytes corresponding to this value.
1675 */
1676#define HLSR_READ_LINE (-1)
1677#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001678__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001679{
1680 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1681 int wanted = lua_tointeger(L, 2);
1682 struct hlua *hlua = hlua_gethlua(L);
1683 struct appctx *appctx;
1684 int len;
1685 int nblk;
1686 char *blk1;
1687 int len1;
1688 char *blk2;
1689 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001690 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001691 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001692
1693 /* Check if this lua stack is schedulable. */
1694 if (!hlua || !hlua->task)
1695 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1696 "'frontend', 'backend' or 'task'"));
1697
1698 /* check for connection closed. If some data where read, return it. */
1699 if (!socket->s)
1700 goto connection_closed;
1701
Willy Tarreau94aa6172015-03-13 14:19:06 +01001702 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001703 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001704 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001705 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001706 if (nblk < 0) /* Connection close. */
1707 goto connection_closed;
1708 if (nblk == 0) /* No data avalaible. */
1709 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001710
1711 /* remove final \r\n. */
1712 if (nblk == 1) {
1713 if (blk1[len1-1] == '\n') {
1714 len1--;
1715 skip_at_end++;
1716 if (blk1[len1-1] == '\r') {
1717 len1--;
1718 skip_at_end++;
1719 }
1720 }
1721 }
1722 else {
1723 if (blk2[len2-1] == '\n') {
1724 len2--;
1725 skip_at_end++;
1726 if (blk2[len2-1] == '\r') {
1727 len2--;
1728 skip_at_end++;
1729 }
1730 }
1731 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001732 }
1733
1734 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001735 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001736 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001737 if (nblk < 0) /* Connection close. */
1738 goto connection_closed;
1739 if (nblk == 0) /* No data avalaible. */
1740 goto connection_empty;
1741 }
1742
1743 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001744 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001745 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001746 if (nblk < 0) /* Connection close. */
1747 goto connection_closed;
1748 if (nblk == 0) /* No data avalaible. */
1749 goto connection_empty;
1750
1751 if (len1 > wanted) {
1752 nblk = 1;
1753 len1 = wanted;
1754 } if (nblk == 2 && len1 + len2 > wanted)
1755 len2 = wanted - len1;
1756 }
1757
1758 len = len1;
1759
1760 luaL_addlstring(&socket->b, blk1, len1);
1761 if (nblk == 2) {
1762 len += len2;
1763 luaL_addlstring(&socket->b, blk2, len2);
1764 }
1765
1766 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001767 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001768
1769 /* Don't wait anything. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001770 stream_int_notify(&socket->s->si[0]);
1771 stream_int_update_applet(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001772
1773 /* If the pattern reclaim to read all the data
1774 * in the connection, got out.
1775 */
1776 if (wanted == HLSR_READ_ALL)
1777 goto connection_empty;
1778 else if (wanted >= 0 && len < wanted)
1779 goto connection_empty;
1780
1781 /* Return result. */
1782 luaL_pushresult(&socket->b);
1783 return 1;
1784
1785connection_closed:
1786
1787 /* If the buffer containds data. */
1788 if (socket->b.n > 0) {
1789 luaL_pushresult(&socket->b);
1790 return 1;
1791 }
1792 lua_pushnil(L);
1793 lua_pushstring(L, "connection closed.");
1794 return 2;
1795
1796connection_empty:
1797
1798 appctx = objt_appctx(socket->s->si[0].end);
1799 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1800 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001801 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001802 return 0;
1803}
1804
1805/* This Lus function gets two parameters. The first one can be string
1806 * or a number. If the string is "*l", the user require one line. If
1807 * the string is "*a", the user require all the content of the stream.
1808 * If the value is a number, the user require a number of bytes equal
1809 * to the value. The default value is "*l" (a line).
1810 *
1811 * This paraeter with a variable type is converted in integer. This
1812 * integer takes this values:
1813 * -1 : read a line
1814 * -2 : read all the stream
1815 * >0 : amount if bytes.
1816 *
1817 * The second parameter is optinal. It contains a string that must be
1818 * concatenated with the read data.
1819 */
1820__LJMP static int hlua_socket_receive(struct lua_State *L)
1821{
1822 int wanted = HLSR_READ_LINE;
1823 const char *pattern;
1824 int type;
1825 char *error;
1826 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001827 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001828
1829 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1830 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1831
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001832 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001833
1834 /* check for pattern. */
1835 if (lua_gettop(L) >= 2) {
1836 type = lua_type(L, 2);
1837 if (type == LUA_TSTRING) {
1838 pattern = lua_tostring(L, 2);
1839 if (strcmp(pattern, "*a") == 0)
1840 wanted = HLSR_READ_ALL;
1841 else if (strcmp(pattern, "*l") == 0)
1842 wanted = HLSR_READ_LINE;
1843 else {
1844 wanted = strtoll(pattern, &error, 10);
1845 if (*error != '\0')
1846 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1847 }
1848 }
1849 else if (type == LUA_TNUMBER) {
1850 wanted = lua_tointeger(L, 2);
1851 if (wanted < 0)
1852 WILL_LJMP(luaL_error(L, "Unsupported size."));
1853 }
1854 }
1855
1856 /* Set pattern. */
1857 lua_pushinteger(L, wanted);
1858 lua_replace(L, 2);
1859
1860 /* init bufffer, and fiil it wih prefix. */
1861 luaL_buffinit(L, &socket->b);
1862
1863 /* Check prefix. */
1864 if (lua_gettop(L) >= 3) {
1865 if (lua_type(L, 3) != LUA_TSTRING)
1866 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1867 pattern = lua_tolstring(L, 3, &len);
1868 luaL_addlstring(&socket->b, pattern, len);
1869 }
1870
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001871 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001872}
1873
1874/* Write the Lua input string in the output buffer.
1875 * This fucntion returns a yield if no space are available.
1876 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001877static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001878{
1879 struct hlua_socket *socket;
1880 struct hlua *hlua = hlua_gethlua(L);
1881 struct appctx *appctx;
1882 size_t buf_len;
1883 const char *buf;
1884 int len;
1885 int send_len;
1886 int sent;
1887
1888 /* Check if this lua stack is schedulable. */
1889 if (!hlua || !hlua->task)
1890 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1891 "'frontend', 'backend' or 'task'"));
1892
1893 /* Get object */
1894 socket = MAY_LJMP(hlua_checksocket(L, 1));
1895 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001896 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001897
1898 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001899 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001900 lua_pushinteger(L, -1);
1901 return 1;
1902 }
1903
1904 /* Update the input buffer data. */
1905 buf += sent;
1906 send_len = buf_len - sent;
1907
1908 /* All the data are sent. */
1909 if (sent >= buf_len)
1910 return 1; /* Implicitly return the length sent. */
1911
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001912 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1913 * the request buffer if its not required.
1914 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001915 if (socket->s->req.buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02001916 if (!stream_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001917 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001918 goto hlua_socket_write_yield_return;
1919 }
1920 }
1921
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001922 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001923 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001924 if (len <= 0)
1925 goto hlua_socket_write_yield_return;
1926
1927 /* send data */
1928 if (len < send_len)
1929 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001930 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001931
1932 /* "Not enough space" (-1), "Buffer too little to contain
1933 * the data" (-2) are not expected because the available length
1934 * is tested.
1935 * Other unknown error are also not expected.
1936 */
1937 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001938 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001939 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001940
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001941 MAY_LJMP(hlua_socket_close(L));
1942 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001943 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001944 return 1;
1945 }
1946
1947 /* update buffers. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001948 stream_int_notify(&socket->s->si[0]);
1949 stream_int_update_applet(&socket->s->si[0]);
1950
Willy Tarreau94aa6172015-03-13 14:19:06 +01001951 socket->s->req.rex = TICK_ETERNITY;
1952 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001953
1954 /* Update length sent. */
1955 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001956 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001957
1958 /* All the data buffer is sent ? */
1959 if (sent + len >= buf_len)
1960 return 1;
1961
1962hlua_socket_write_yield_return:
1963 appctx = objt_appctx(socket->s->si[0].end);
1964 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1965 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001966 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001967 return 0;
1968}
1969
1970/* This function initiate the send of data. It just check the input
1971 * parameters and push an integer in the Lua stack that contain the
1972 * amount of data writed in the buffer. This is used by the function
1973 * "hlua_socket_write_yield" that can yield.
1974 *
1975 * The Lua function gets between 3 and 4 parameters. The first one is
1976 * the associated object. The second is a string buffer. The third is
1977 * a facultative integer that represents where is the buffer position
1978 * of the start of the data that can send. The first byte is the
1979 * position "1". The default value is "1". The fourth argument is a
1980 * facultative integer that represents where is the buffer position
1981 * of the end of the data that can send. The default is the last byte.
1982 */
1983static int hlua_socket_send(struct lua_State *L)
1984{
1985 int i;
1986 int j;
1987 const char *buf;
1988 size_t buf_len;
1989
1990 /* Check number of arguments. */
1991 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1992 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1993
1994 /* Get the string. */
1995 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1996
1997 /* Get and check j. */
1998 if (lua_gettop(L) == 4) {
1999 j = MAY_LJMP(luaL_checkinteger(L, 4));
2000 if (j < 0)
2001 j = buf_len + j + 1;
2002 if (j > buf_len)
2003 j = buf_len + 1;
2004 lua_pop(L, 1);
2005 }
2006 else
2007 j = buf_len;
2008
2009 /* Get and check i. */
2010 if (lua_gettop(L) == 3) {
2011 i = MAY_LJMP(luaL_checkinteger(L, 3));
2012 if (i < 0)
2013 i = buf_len + i + 1;
2014 if (i > buf_len)
2015 i = buf_len + 1;
2016 lua_pop(L, 1);
2017 } else
2018 i = 1;
2019
2020 /* Check bth i and j. */
2021 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002022 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002023 return 1;
2024 }
2025 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002026 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002027 return 1;
2028 }
2029 if (i == 0)
2030 i = 1;
2031 if (j == 0)
2032 j = 1;
2033
2034 /* Pop the string. */
2035 lua_pop(L, 1);
2036
2037 /* Update the buffer length. */
2038 buf += i - 1;
2039 buf_len = j - i + 1;
2040 lua_pushlstring(L, buf, buf_len);
2041
2042 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002043 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002044
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002045 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002046}
2047
Willy Tarreau22b0a682015-06-17 19:43:49 +02002048#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002049__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2050{
2051 static char buffer[SOCKET_INFO_MAX_LEN];
2052 int ret;
2053 int len;
2054 char *p;
2055
2056 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2057 if (ret <= 0) {
2058 lua_pushnil(L);
2059 return 1;
2060 }
2061
2062 if (ret == AF_UNIX) {
2063 lua_pushstring(L, buffer+1);
2064 return 1;
2065 }
2066 else if (ret == AF_INET6) {
2067 buffer[0] = '[';
2068 len = strlen(buffer);
2069 buffer[len] = ']';
2070 len++;
2071 buffer[len] = ':';
2072 len++;
2073 p = buffer;
2074 }
2075 else if (ret == AF_INET) {
2076 p = buffer + 1;
2077 len = strlen(p);
2078 p[len] = ':';
2079 len++;
2080 }
2081 else {
2082 lua_pushnil(L);
2083 return 1;
2084 }
2085
2086 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2087 lua_pushnil(L);
2088 return 1;
2089 }
2090
2091 lua_pushstring(L, p);
2092 return 1;
2093}
2094
2095/* Returns information about the peer of the connection. */
2096__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2097{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002098 struct hlua_socket *socket;
2099 struct connection *conn;
2100
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002101 MAY_LJMP(check_args(L, 1, "getpeername"));
2102
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002103 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002104
2105 /* Check if the tcp object is avalaible. */
2106 if (!socket->s) {
2107 lua_pushnil(L);
2108 return 1;
2109 }
2110
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002111 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002112 if (!conn) {
2113 lua_pushnil(L);
2114 return 1;
2115 }
2116
2117 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
2118 unsigned int salen = sizeof(conn->addr.to);
2119 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
2120 lua_pushnil(L);
2121 return 1;
2122 }
2123 conn->flags |= CO_FL_ADDR_TO_SET;
2124 }
2125
2126 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2127}
2128
2129/* Returns information about my connection side. */
2130static int hlua_socket_getsockname(struct lua_State *L)
2131{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002132 struct hlua_socket *socket;
2133 struct connection *conn;
2134
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002135 MAY_LJMP(check_args(L, 1, "getsockname"));
2136
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002137 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002138
2139 /* Check if the tcp object is avalaible. */
2140 if (!socket->s) {
2141 lua_pushnil(L);
2142 return 1;
2143 }
2144
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002145 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002146 if (!conn) {
2147 lua_pushnil(L);
2148 return 1;
2149 }
2150
2151 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
2152 unsigned int salen = sizeof(conn->addr.from);
2153 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
2154 lua_pushnil(L);
2155 return 1;
2156 }
2157 conn->flags |= CO_FL_ADDR_FROM_SET;
2158 }
2159
2160 return hlua_socket_info(L, &conn->addr.from);
2161}
2162
2163/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002164static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002165 .obj_type = OBJ_TYPE_APPLET,
2166 .name = "<LUA_TCP>",
2167 .fct = hlua_socket_handler,
2168 .release = hlua_socket_release,
2169};
2170
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002171__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002172{
2173 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2174 struct hlua *hlua = hlua_gethlua(L);
2175 struct appctx *appctx;
2176
2177 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002178 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002179 lua_pushnil(L);
2180 lua_pushstring(L, "Can't connect");
2181 return 2;
2182 }
2183
2184 appctx = objt_appctx(socket->s->si[0].end);
2185
2186 /* Check for connection established. */
2187 if (appctx->ctx.hlua.connected) {
2188 lua_pushinteger(L, 1);
2189 return 1;
2190 }
2191
2192 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2193 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002194 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002195 return 0;
2196}
2197
2198/* This function fail or initite the connection. */
2199__LJMP static int hlua_socket_connect(struct lua_State *L)
2200{
2201 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002202 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002203 const char *ip;
2204 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002205 struct hlua *hlua;
2206 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002207 int low, high;
2208 struct sockaddr_storage *addr;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002209
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002210 if (lua_gettop(L) < 2)
2211 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002212
2213 /* Get args. */
2214 socket = MAY_LJMP(hlua_checksocket(L, 1));
2215 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002216 if (lua_gettop(L) >= 3)
2217 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002218
Willy Tarreau973a5422015-08-05 21:47:23 +02002219 conn = si_alloc_conn(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002220 if (!conn)
2221 WILL_LJMP(luaL_error(L, "connect: internal error"));
2222
Willy Tarreau3adac082015-09-26 17:51:09 +02002223 /* needed for the connection not to be closed */
2224 conn->target = socket->s->target;
2225
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002226 /* Parse ip address. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002227 addr = str2sa_range(ip, &low, &high, NULL, NULL, NULL, 0);
2228 if (!addr)
2229 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
2230 if (low != high)
2231 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
2232 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002233
2234 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002235 if (low == 0) {
2236 if (conn->addr.to.ss_family == AF_INET) {
2237 if (port == -1)
2238 WILL_LJMP(luaL_error(L, "connect: port missing"));
2239 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2240 } else if (conn->addr.to.ss_family == AF_INET6) {
2241 if (port == -1)
2242 WILL_LJMP(luaL_error(L, "connect: port missing"));
2243 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2244 }
2245 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002246
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002247 hlua = hlua_gethlua(L);
2248 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002249
2250 /* inform the stream that we want to be notified whenever the
2251 * connection completes.
2252 */
2253 si_applet_cant_get(&socket->s->si[0]);
2254 si_applet_cant_put(&socket->s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002255 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002256
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002257 hlua->flags |= HLUA_MUST_GC;
2258
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002259 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2260 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002261 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002262
2263 return 0;
2264}
2265
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002266#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002267__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2268{
2269 struct hlua_socket *socket;
2270
2271 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2272 socket = MAY_LJMP(hlua_checksocket(L, 1));
2273 socket->s->target = &socket_ssl.obj_type;
2274 return MAY_LJMP(hlua_socket_connect(L));
2275}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002276#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002277
2278__LJMP static int hlua_socket_setoption(struct lua_State *L)
2279{
2280 return 0;
2281}
2282
2283__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2284{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002285 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002286 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002287
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002288 MAY_LJMP(check_args(L, 2, "settimeout"));
2289
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002290 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002291 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002292
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002293 socket->s->req.rto = tmout;
2294 socket->s->req.wto = tmout;
2295 socket->s->res.rto = tmout;
2296 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002297
2298 return 0;
2299}
2300
2301__LJMP static int hlua_socket_new(lua_State *L)
2302{
2303 struct hlua_socket *socket;
2304 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002305 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002306 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002307 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002308
2309 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002310 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002311 hlua_pusherror(L, "socket: full stack");
2312 goto out_fail_conf;
2313 }
2314
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002315 /* Create the object: obj[0] = userdata. */
2316 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002317 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002318 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002319 memset(socket, 0, sizeof(*socket));
2320
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002321 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002322 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002323 hlua_pusherror(L, "socket: uninitialized pools.");
2324 goto out_fail_conf;
2325 }
2326
Willy Tarreau87b09662015-04-03 00:22:06 +02002327 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002328 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2329 lua_setmetatable(L, -2);
2330
Willy Tarreaud420a972015-04-06 00:39:18 +02002331 /* Create the applet context */
2332 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002333 if (!appctx) {
2334 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002335 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002336 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002337
Willy Tarreaud420a972015-04-06 00:39:18 +02002338 appctx->ctx.hlua.socket = socket;
2339 appctx->ctx.hlua.connected = 0;
2340 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2341 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002342
Willy Tarreaud420a972015-04-06 00:39:18 +02002343 /* Now create a session, task and stream for this applet */
2344 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2345 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002346 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002347 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002348 }
2349
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002350 task = task_new();
2351 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002352 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002353 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002354 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002355 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002356
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002357 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002358 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002359 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002360 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002361 }
2362
Willy Tarreaud420a972015-04-06 00:39:18 +02002363 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002364 socket->s = strm;
2365 strm->hlua.T = NULL;
2366 strm->hlua.Tref = LUA_REFNIL;
2367 strm->hlua.Mref = LUA_REFNIL;
2368 strm->hlua.nargs = 0;
2369 strm->hlua.flags = 0;
2370 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002371
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002372 /* Configure "right" stream interface. this "si" is used to connect
2373 * and retrieve data from the server. The connection is initialized
2374 * with the "struct server".
2375 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002376 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002377
2378 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002379 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2380 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002381
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002382 /* Update statistics counters. */
2383 socket_proxy.feconn++; /* beconn will be increased later */
2384 jobs++;
2385 totalconn++;
2386
2387 /* Return yield waiting for connection. */
2388 return 1;
2389
Willy Tarreaud420a972015-04-06 00:39:18 +02002390 out_fail_stream:
2391 task_free(task);
2392 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002393 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002394 out_fail_sess:
2395 appctx_free(appctx);
2396 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002397 WILL_LJMP(lua_error(L));
2398 return 0;
2399}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002400
2401/*
2402 *
2403 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002404 * Class Channel
2405 *
2406 *
2407 */
2408
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002409/* The state between the channel data and the HTTP parser state can be
2410 * unconsistent, so reset the parser and call it again. Warning, this
2411 * action not revalidate the request and not send a 400 if the modified
2412 * resuest is not valid.
2413 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002414 * This function never fails. The direction is set using dir, which equals
2415 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002416 */
2417static void hlua_resynchonize_proto(struct stream *stream, int dir)
2418{
2419 /* Protocol HTTP. */
2420 if (stream->be->mode == PR_MODE_HTTP) {
2421
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002422 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002423 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002424 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002425 http_txn_reset_res(stream->txn);
2426
2427 if (stream->txn->hdr_idx.v)
2428 hdr_idx_init(&stream->txn->hdr_idx);
2429
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002430 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002431 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002432 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002433 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2434 }
2435}
2436
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002437/* Check the protocole integrity after the Lua manipulations. Close the stream
2438 * and returns 0 if fails, otherwise returns 1. The direction is set using dir,
2439 * which equals either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002440 */
2441static int hlua_check_proto(struct stream *stream, int dir)
2442{
2443 const struct chunk msg = { .len = 0 };
2444
Willy Tarreau9af89f72015-09-26 11:50:08 +02002445 /* Protocol HTTP. The message parsing state must match the request or
2446 * response state. The problem that may happen is that Lua modifies
2447 * the request or response message *after* it was parsed, and corrupted
2448 * it so that it could not be processed anymore. We just need to verify
2449 * if the parser is still expected to run or not.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002450 */
2451 if (stream->be->mode == PR_MODE_HTTP) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002452 if (dir == SMP_OPT_DIR_REQ &&
Willy Tarreau9af89f72015-09-26 11:50:08 +02002453 !(stream->req.analysers & AN_REQ_WAIT_HTTP) &&
2454 stream->txn->req.msg_state < HTTP_MSG_BODY) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002455 stream_int_retnclose(&stream->si[0], &msg);
2456 return 0;
2457 }
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002458 else if (dir == SMP_OPT_DIR_RES &&
Willy Tarreau9af89f72015-09-26 11:50:08 +02002459 !(stream->res.analysers & AN_RES_WAIT_HTTP) &&
2460 stream->txn->rsp.msg_state < HTTP_MSG_BODY) {
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002461 stream_int_retnclose(&stream->si[0], &msg);
2462 return 0;
2463 }
2464 }
2465 return 1;
2466}
2467
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002468/* Returns the struct hlua_channel join to the class channel in the
2469 * stack entry "ud" or throws an argument error.
2470 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002471__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002472{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002473 return (struct channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002474}
2475
Willy Tarreau47860ed2015-03-10 14:07:50 +01002476/* Pushes the channel onto the top of the stack. If the stask does not have a
2477 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002478 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002479static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002480{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002481 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002482 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002483 return 0;
2484
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002485 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002486 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002487 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002488
2489 /* Pop a class sesison metatable and affect it to the userdata. */
2490 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2491 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002492 return 1;
2493}
2494
2495/* Duplicate all the data present in the input channel and put it
2496 * in a string LUA variables. Returns -1 and push a nil value in
2497 * the stack if the channel is closed and all the data are consumed,
2498 * returns 0 if no data are available, otherwise it returns the length
2499 * of the builded string.
2500 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002501static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002502{
2503 char *blk1;
2504 char *blk2;
2505 int len1;
2506 int len2;
2507 int ret;
2508 luaL_Buffer b;
2509
Willy Tarreau47860ed2015-03-10 14:07:50 +01002510 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002511 if (unlikely(ret == 0))
2512 return 0;
2513
2514 if (unlikely(ret < 0)) {
2515 lua_pushnil(L);
2516 return -1;
2517 }
2518
2519 luaL_buffinit(L, &b);
2520 luaL_addlstring(&b, blk1, len1);
2521 if (unlikely(ret == 2))
2522 luaL_addlstring(&b, blk2, len2);
2523 luaL_pushresult(&b);
2524
2525 if (unlikely(ret == 2))
2526 return len1 + len2;
2527 return len1;
2528}
2529
2530/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2531 * a yield. This function keep the data in the buffer.
2532 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002533__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002534{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002535 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002536
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002537 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2538
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002539 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002540 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002541 return 1;
2542}
2543
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002544/* Check arguments for the function "hlua_channel_dup_yield". */
2545__LJMP static int hlua_channel_dup(lua_State *L)
2546{
2547 MAY_LJMP(check_args(L, 1, "dup"));
2548 MAY_LJMP(hlua_checkchannel(L, 1));
2549 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2550}
2551
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002552/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2553 * a yield. This function consumes the data in the buffer. It returns
2554 * a string containing the data or a nil pointer if no data are available
2555 * and the channel is closed.
2556 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002557__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002558{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002559 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002560 int ret;
2561
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002562 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002563
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002564 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002565 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002566 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002567
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002568 if (unlikely(ret == -1))
2569 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002570
Willy Tarreau47860ed2015-03-10 14:07:50 +01002571 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002572 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002573 return 1;
2574}
2575
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002576/* Check arguments for the fucntion "hlua_channel_get_yield". */
2577__LJMP static int hlua_channel_get(lua_State *L)
2578{
2579 MAY_LJMP(check_args(L, 1, "get"));
2580 MAY_LJMP(hlua_checkchannel(L, 1));
2581 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2582}
2583
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002584/* This functions consumes and returns one line. If the channel is closed,
2585 * and the last data does not contains a final '\n', the data are returned
2586 * without the final '\n'. When no more data are avalaible, it returns nil
2587 * value.
2588 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002589__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002590{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002591 char *blk1;
2592 char *blk2;
2593 int len1;
2594 int len2;
2595 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002596 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002597 int ret;
2598 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002599
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002600 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2601
Willy Tarreau47860ed2015-03-10 14:07:50 +01002602 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002603 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002604 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002605
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002606 if (ret == -1) {
2607 lua_pushnil(L);
2608 return 1;
2609 }
2610
2611 luaL_buffinit(L, &b);
2612 luaL_addlstring(&b, blk1, len1);
2613 len = len1;
2614 if (unlikely(ret == 2)) {
2615 luaL_addlstring(&b, blk2, len2);
2616 len += len2;
2617 }
2618 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002619 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002620 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002621 return 1;
2622}
2623
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002624/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2625__LJMP static int hlua_channel_getline(lua_State *L)
2626{
2627 MAY_LJMP(check_args(L, 1, "getline"));
2628 MAY_LJMP(hlua_checkchannel(L, 1));
2629 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2630}
2631
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002632/* This function takes a string as input, and append it at the
2633 * input side of channel. If the data is too big, but a space
2634 * is probably available after sending some data, the function
2635 * yield. If the data is bigger than the buffer, or if the
2636 * channel is closed, it returns -1. otherwise, it returns the
2637 * amount of data writed.
2638 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002639__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002640{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002641 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002642 size_t len;
2643 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2644 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2645 int ret;
2646 int max;
2647
Willy Tarreau47860ed2015-03-10 14:07:50 +01002648 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002649 if (max > len - l)
2650 max = len - l;
2651
Willy Tarreau47860ed2015-03-10 14:07:50 +01002652 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002653 if (ret == -2 || ret == -3) {
2654 lua_pushinteger(L, -1);
2655 return 1;
2656 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002657 if (ret == -1) {
2658 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002659 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002660 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002661 l += ret;
2662 lua_pop(L, 1);
2663 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002664 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002665
Willy Tarreau47860ed2015-03-10 14:07:50 +01002666 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2667 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002668 /* There are no space avalaible, and the output buffer is empty.
2669 * in this case, we cannot add more data, so we cannot yield,
2670 * we return the amount of copyied data.
2671 */
2672 return 1;
2673 }
2674 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002675 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002676 return 1;
2677}
2678
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002679/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002680 * of the writed string, or -1 if the channel is closed or if the
2681 * buffer size is too little for the data.
2682 */
2683__LJMP static int hlua_channel_append(lua_State *L)
2684{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002685 size_t len;
2686
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002687 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002688 MAY_LJMP(hlua_checkchannel(L, 1));
2689 MAY_LJMP(luaL_checklstring(L, 2, &len));
2690 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002691 lua_pushinteger(L, 0);
2692
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002693 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002694}
2695
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002696/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002697 * his process by cleaning the buffer. The result is a replacement
2698 * of the current data. It returns the length of the writed string,
2699 * or -1 if the channel is closed or if the buffer size is too
2700 * little for the data.
2701 */
2702__LJMP static int hlua_channel_set(lua_State *L)
2703{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002704 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002705
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002706 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002707 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002708 lua_pushinteger(L, 0);
2709
Willy Tarreau47860ed2015-03-10 14:07:50 +01002710 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002711
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002712 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002713}
2714
2715/* Append data in the output side of the buffer. This data is immediatly
2716 * sent. The fcuntion returns the ammount of data writed. If the buffer
2717 * cannot contains the data, the function yield. The function returns -1
2718 * if the channel is closed.
2719 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002720__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002721{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002722 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002723 size_t len;
2724 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2725 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2726 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002727 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002728
Willy Tarreau47860ed2015-03-10 14:07:50 +01002729 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002730 lua_pushinteger(L, -1);
2731 return 1;
2732 }
2733
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002734 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2735 * the request buffer if its not required.
2736 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002737 if (chn->buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02002738 if (!stream_alloc_recv_buffer(chn)) {
Willy Tarreau47860ed2015-03-10 14:07:50 +01002739 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002740 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002741 }
2742 }
2743
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002744 /* the writed data will be immediatly sent, so we can check
2745 * the avalaible space without taking in account the reserve.
2746 * The reserve is guaranted for the processing of incoming
2747 * data, because the buffer will be flushed.
2748 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002749 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002750
2751 /* If there are no space avalaible, and the output buffer is empty.
2752 * in this case, we cannot add more data, so we cannot yield,
2753 * we return the amount of copyied data.
2754 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002755 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002756 return 1;
2757
2758 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002759 if (max > len - l)
2760 max = len - l;
2761
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002762 /* The buffer avalaible size may be not contiguous. This test
2763 * detects a non contiguous buffer and realign it.
2764 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002765 if (bi_space_for_replace(chn->buf) < max)
2766 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002767
2768 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002769 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002770
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002771 /* buffer replace considers that the input part is filled.
2772 * so, I must forward these new data in the output part.
2773 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002774 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002775
2776 l += max;
2777 lua_pop(L, 1);
2778 lua_pushinteger(L, l);
2779
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002780 /* If there are no space avalaible, and the output buffer is empty.
2781 * in this case, we cannot add more data, so we cannot yield,
2782 * we return the amount of copyied data.
2783 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002784 max = chn->buf->size - buffer_len(chn->buf);
2785 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002786 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002787
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002788 if (l < len) {
2789 /* If we are waiting for space in the response buffer, we
2790 * must set the flag WAKERESWR. This flag required the task
2791 * wake up if any activity is detected on the response buffer.
2792 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002793 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002794 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002795 else
2796 HLUA_SET_WAKEREQWR(hlua);
2797 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002798 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002799
2800 return 1;
2801}
2802
2803/* Just a wraper of "_hlua_channel_send". This wrapper permits
2804 * yield the LUA process, and resume it without checking the
2805 * input arguments.
2806 */
2807__LJMP static int hlua_channel_send(lua_State *L)
2808{
2809 MAY_LJMP(check_args(L, 2, "send"));
2810 lua_pushinteger(L, 0);
2811
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002812 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002813}
2814
2815/* This function forward and amount of butes. The data pass from
2816 * the input side of the buffer to the output side, and can be
2817 * forwarded. This function never fails.
2818 *
2819 * The Lua function takes an amount of bytes to be forwarded in
2820 * imput. It returns the number of bytes forwarded.
2821 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002822__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002823{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002824 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002825 int len;
2826 int l;
2827 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002828 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002829
2830 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2831 len = MAY_LJMP(luaL_checkinteger(L, 2));
2832 l = MAY_LJMP(luaL_checkinteger(L, -1));
2833
2834 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002835 if (max > chn->buf->i)
2836 max = chn->buf->i;
2837 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002838 l += max;
2839
2840 lua_pop(L, 1);
2841 lua_pushinteger(L, l);
2842
2843 /* Check if it miss bytes to forward. */
2844 if (l < len) {
2845 /* The the input channel or the output channel are closed, we
2846 * must return the amount of data forwarded.
2847 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002848 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002849 return 1;
2850
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002851 /* If we are waiting for space data in the response buffer, we
2852 * must set the flag WAKERESWR. This flag required the task
2853 * wake up if any activity is detected on the response buffer.
2854 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002855 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002856 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002857 else
2858 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002859
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002860 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002861 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002862 }
2863
2864 return 1;
2865}
2866
2867/* Just check the input and prepare the stack for the previous
2868 * function "hlua_channel_forward_yield"
2869 */
2870__LJMP static int hlua_channel_forward(lua_State *L)
2871{
2872 MAY_LJMP(check_args(L, 2, "forward"));
2873 MAY_LJMP(hlua_checkchannel(L, 1));
2874 MAY_LJMP(luaL_checkinteger(L, 2));
2875
2876 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002877 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002878}
2879
2880/* Just returns the number of bytes available in the input
2881 * side of the buffer. This function never fails.
2882 */
2883__LJMP static int hlua_channel_get_in_len(lua_State *L)
2884{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002885 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002886
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002887 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002888 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002889 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002890 return 1;
2891}
2892
2893/* Just returns the number of bytes available in the output
2894 * side of the buffer. This function never fails.
2895 */
2896__LJMP static int hlua_channel_get_out_len(lua_State *L)
2897{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002898 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002899
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002900 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002901 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002902 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002903 return 1;
2904}
2905
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002906/*
2907 *
2908 *
2909 * Class Fetches
2910 *
2911 *
2912 */
2913
2914/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002915 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002916 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002917__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002918{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002919 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002920}
2921
2922/* This function creates and push in the stack a fetch object according
2923 * with a current TXN.
2924 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002925static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002926{
Willy Tarreau7073c472015-04-06 11:15:40 +02002927 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002928
2929 /* Check stack size. */
2930 if (!lua_checkstack(L, 3))
2931 return 0;
2932
2933 /* Create the object: obj[0] = userdata.
2934 * Note that the base of the Fetches object is the
2935 * transaction object.
2936 */
2937 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002938 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002939 lua_rawseti(L, -2, 0);
2940
Willy Tarreau7073c472015-04-06 11:15:40 +02002941 hsmp->s = txn->s;
2942 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01002943 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002944 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002945
2946 /* Pop a class sesison metatable and affect it to the userdata. */
2947 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2948 lua_setmetatable(L, -2);
2949
2950 return 1;
2951}
2952
2953/* This function is an LUA binding. It is called with each sample-fetch.
2954 * It uses closure argument to store the associated sample-fetch. It
2955 * returns only one argument or throws an error. An error is thrown
2956 * only if an error is encountered during the argument parsing. If
2957 * the "sample-fetch" function fails, nil is returned.
2958 */
2959__LJMP static int hlua_run_sample_fetch(lua_State *L)
2960{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002961 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002962 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002963 struct arg args[ARGM_NBARGS + 1];
2964 int i;
2965 struct sample smp;
2966
2967 /* Get closure arguments. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002968 f = (struct sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002969
2970 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002971 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002972
Thierry FOURNIERca988662015-12-20 18:43:03 +01002973 /* Check execution authorization. */
2974 if (f->use & SMP_USE_HTTP_ANY &&
2975 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
2976 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
2977 "is not available in Lua services", f->kw);
2978 WILL_LJMP(lua_error(L));
2979 }
2980
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002981 /* Get extra arguments. */
2982 for (i = 0; i < lua_gettop(L) - 1; i++) {
2983 if (i >= ARGM_NBARGS)
2984 break;
2985 hlua_lua2arg(L, i + 2, &args[i]);
2986 }
2987 args[i].type = ARGT_STOP;
2988
2989 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002990 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002991
2992 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002993 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002994 lua_pushfstring(L, "error in arguments");
2995 WILL_LJMP(lua_error(L));
2996 }
2997
2998 /* Initialise the sample. */
2999 memset(&smp, 0, sizeof(smp));
3000
3001 /* Run the sample fetch process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02003002 smp.px = hsmp->p;
3003 smp.sess = hsmp->s->sess;
3004 smp.strm = hsmp->s;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003005 smp.opt = hsmp->dir & SMP_OPT_DIR;
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003006 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003007 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003008 lua_pushstring(L, "");
3009 else
3010 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003011 return 1;
3012 }
3013
3014 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003015 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003016 hlua_smp2lua_str(L, &smp);
3017 else
3018 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003019 return 1;
3020}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003021
3022/*
3023 *
3024 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003025 * Class Converters
3026 *
3027 *
3028 */
3029
3030/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003031 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003032 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003033__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003034{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003035 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003036}
3037
3038/* This function creates and push in the stack a Converters object
3039 * according with a current TXN.
3040 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003041static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003042{
Willy Tarreau7073c472015-04-06 11:15:40 +02003043 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003044
3045 /* Check stack size. */
3046 if (!lua_checkstack(L, 3))
3047 return 0;
3048
3049 /* Create the object: obj[0] = userdata.
3050 * Note that the base of the Converters object is the
3051 * same than the TXN object.
3052 */
3053 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003054 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003055 lua_rawseti(L, -2, 0);
3056
Willy Tarreau7073c472015-04-06 11:15:40 +02003057 hsmp->s = txn->s;
3058 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003059 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003060 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003061
Willy Tarreau87b09662015-04-03 00:22:06 +02003062 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003063 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3064 lua_setmetatable(L, -2);
3065
3066 return 1;
3067}
3068
3069/* This function is an LUA binding. It is called with each converter.
3070 * It uses closure argument to store the associated converter. It
3071 * returns only one argument or throws an error. An error is thrown
3072 * only if an error is encountered during the argument parsing. If
3073 * the converter function function fails, nil is returned.
3074 */
3075__LJMP static int hlua_run_sample_conv(lua_State *L)
3076{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003077 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003078 struct sample_conv *conv;
3079 struct arg args[ARGM_NBARGS + 1];
3080 int i;
3081 struct sample smp;
3082
3083 /* Get closure arguments. */
3084 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
3085
3086 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003087 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003088
3089 /* Get extra arguments. */
3090 for (i = 0; i < lua_gettop(L) - 2; i++) {
3091 if (i >= ARGM_NBARGS)
3092 break;
3093 hlua_lua2arg(L, i + 3, &args[i]);
3094 }
3095 args[i].type = ARGT_STOP;
3096
3097 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003098 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003099
3100 /* Run the special args checker. */
3101 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3102 hlua_pusherror(L, "error in arguments");
3103 WILL_LJMP(lua_error(L));
3104 }
3105
3106 /* Initialise the sample. */
3107 if (!hlua_lua2smp(L, 2, &smp)) {
3108 hlua_pusherror(L, "error in the input argument");
3109 WILL_LJMP(lua_error(L));
3110 }
3111
3112 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003113 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003114 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003115 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003116 WILL_LJMP(lua_error(L));
3117 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003118 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3119 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003120 hlua_pusherror(L, "error during the input argument casting");
3121 WILL_LJMP(lua_error(L));
3122 }
3123
3124 /* Run the sample conversion process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02003125 smp.px = hsmp->p;
3126 smp.sess = hsmp->s->sess;
3127 smp.strm = hsmp->s;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003128 smp.opt = hsmp->dir & SMP_OPT_DIR;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003129 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003130 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003131 lua_pushstring(L, "");
3132 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003133 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003134 return 1;
3135 }
3136
3137 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003138 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003139 hlua_smp2lua_str(L, &smp);
3140 else
3141 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003142 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003143}
3144
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003145/*
3146 *
3147 *
3148 * Class AppletTCP
3149 *
3150 *
3151 */
3152
3153/* Returns a struct hlua_txn if the stack entry "ud" is
3154 * a class stream, otherwise it throws an error.
3155 */
3156__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3157{
3158 return (struct hlua_appctx *)MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
3159}
3160
3161/* This function creates and push in the stack an Applet object
3162 * according with a current TXN.
3163 */
3164static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3165{
3166 struct hlua_appctx *appctx;
3167 struct stream_interface *si = ctx->owner;
3168 struct stream *s = si_strm(si);
3169 struct proxy *p = s->be;
3170
3171 /* Check stack size. */
3172 if (!lua_checkstack(L, 3))
3173 return 0;
3174
3175 /* Create the object: obj[0] = userdata.
3176 * Note that the base of the Converters object is the
3177 * same than the TXN object.
3178 */
3179 lua_newtable(L);
3180 appctx = lua_newuserdata(L, sizeof(*appctx));
3181 lua_rawseti(L, -2, 0);
3182 appctx->appctx = ctx;
3183 appctx->htxn.s = s;
3184 appctx->htxn.p = p;
3185
3186 /* Create the "f" field that contains a list of fetches. */
3187 lua_pushstring(L, "f");
3188 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3189 return 0;
3190 lua_settable(L, -3);
3191
3192 /* Create the "sf" field that contains a list of stringsafe fetches. */
3193 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003194 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003195 return 0;
3196 lua_settable(L, -3);
3197
3198 /* Create the "c" field that contains a list of converters. */
3199 lua_pushstring(L, "c");
3200 if (!hlua_converters_new(L, &appctx->htxn, 0))
3201 return 0;
3202 lua_settable(L, -3);
3203
3204 /* Create the "sc" field that contains a list of stringsafe converters. */
3205 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003206 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003207 return 0;
3208 lua_settable(L, -3);
3209
3210 /* Pop a class stream metatable and affect it to the table. */
3211 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3212 lua_setmetatable(L, -2);
3213
3214 return 1;
3215}
3216
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003217__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3218{
3219 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3220 struct stream *s = appctx->htxn.s;
3221 struct hlua *hlua = &s->hlua;
3222
3223 MAY_LJMP(check_args(L, 2, "set_priv"));
3224
3225 /* Remove previous value. */
3226 if (hlua->Mref != -1)
3227 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3228
3229 /* Get and store new value. */
3230 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3231 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3232
3233 return 0;
3234}
3235
3236__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3237{
3238 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3239 struct stream *s = appctx->htxn.s;
3240 struct hlua *hlua = &s->hlua;
3241
3242 /* Push configuration index in the stack. */
3243 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3244
3245 return 1;
3246}
3247
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003248/* 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;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003479 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003480 struct stream_interface *si = ctx->owner;
3481 struct stream *s = si_strm(si);
3482 struct proxy *px = s->be;
3483 struct http_txn *txn = s->txn;
3484 const char *path;
3485 const char *end;
3486 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003487
3488 /* Check stack size. */
3489 if (!lua_checkstack(L, 3))
3490 return 0;
3491
3492 /* Create the object: obj[0] = userdata.
3493 * Note that the base of the Converters object is the
3494 * same than the TXN object.
3495 */
3496 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003497 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003498 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003499 appctx->appctx = ctx;
3500 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
3501 appctx->htxn.s = s;
3502 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003503
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003504 /* Create the "f" field that contains a list of fetches. */
3505 lua_pushstring(L, "f");
3506 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3507 return 0;
3508 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003509
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003510 /* Create the "sf" field that contains a list of stringsafe fetches. */
3511 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003512 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003513 return 0;
3514 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003515
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003516 /* Create the "c" field that contains a list of converters. */
3517 lua_pushstring(L, "c");
3518 if (!hlua_converters_new(L, &appctx->htxn, 0))
3519 return 0;
3520 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003521
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003522 /* Create the "sc" field that contains a list of stringsafe converters. */
3523 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003524 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003525 return 0;
3526 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003527
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003528 /* Stores the request method. */
3529 lua_pushstring(L, "method");
3530 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3531 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003532
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003533 /* Stores the http version. */
3534 lua_pushstring(L, "version");
3535 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3536 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003537
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003538 /* creates an array of headers. hlua_http_get_headers() crates and push
3539 * the array on the top of the stack.
3540 */
3541 lua_pushstring(L, "headers");
3542 htxn.s = s;
3543 htxn.p = px;
3544 htxn.dir = SMP_OPT_DIR_REQ;
3545 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3546 return 0;
3547 lua_settable(L, -3);
3548
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003549 /* Get path and qs */
3550 path = http_get_path(txn);
3551 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3552 p = path;
3553 while (p < end && *p != '?')
3554 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003555
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003556 /* Stores the request path. */
3557 lua_pushstring(L, "path");
3558 lua_pushlstring(L, path, p - path);
3559 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003560
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003561 /* Stores the query string. */
3562 lua_pushstring(L, "qs");
3563 if (*p == '?')
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003564 p++;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003565 lua_pushlstring(L, p, end - p);
3566 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003567
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003568 /* Stores the request path. */
3569 lua_pushstring(L, "length");
3570 lua_pushinteger(L, txn->req.body_len);
3571 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003572
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003573 /* Create an array of HTTP request headers. */
3574 lua_pushstring(L, "headers");
3575 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3576 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003577
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003578 /* Create an empty array of HTTP request headers. */
3579 lua_pushstring(L, "response");
3580 lua_newtable(L);
3581 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003582
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003583 /* Pop a class stream metatable and affect it to the table. */
3584 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3585 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003586
3587 return 1;
3588}
3589
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003590__LJMP static int hlua_applet_http_set_priv(lua_State *L)
3591{
3592 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3593 struct stream *s = appctx->htxn.s;
3594 struct hlua *hlua = &s->hlua;
3595
3596 MAY_LJMP(check_args(L, 2, "set_priv"));
3597
3598 /* Remove previous value. */
3599 if (hlua->Mref != -1)
3600 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3601
3602 /* Get and store new value. */
3603 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3604 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3605
3606 return 0;
3607}
3608
3609__LJMP static int hlua_applet_http_get_priv(lua_State *L)
3610{
3611 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3612 struct stream *s = appctx->htxn.s;
3613 struct hlua *hlua = &s->hlua;
3614
3615 /* Push configuration index in the stack. */
3616 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3617
3618 return 1;
3619}
3620
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003621/* If expected data not yet available, it returns a yield. This function
3622 * consumes the data in the buffer. It returns a string containing the
3623 * data. This string can be empty.
3624 */
3625__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003626{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003627 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3628 struct stream_interface *si = appctx->appctx->owner;
3629 struct channel *chn = si_ic(si);
3630 int ret;
3631 char *blk1;
3632 int len1;
3633 char *blk2;
3634 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003635
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003636 /* Maybe we cant send a 100-continue ? */
3637 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3638 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3639 /* if ret == -2 or -3 the channel closed or the message si too
3640 * big for the buffers. We cant send anything. So, we ignoring
3641 * the error, considers that the 100-continue is sent, and try
3642 * to receive.
3643 * If ret is -1, we dont have room in the buffer, so we yield.
3644 */
3645 if (ret == -1) {
3646 si_applet_cant_put(si);
3647 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3648 }
3649 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3650 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003651
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003652 /* Check for the end of the data. */
3653 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
3654 luaL_pushresult(&appctx->b);
3655 return 1;
3656 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003657
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003658 /* Read the maximum amount of data avalaible. */
3659 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003660
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003661 /* Data not yet avalaible. return yield. */
3662 if (ret == 0) {
3663 si_applet_cant_get(si);
3664 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3665 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003666
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003667 /* End of data: commit the total strings and return. */
3668 if (ret < 0) {
3669 luaL_pushresult(&appctx->b);
3670 return 1;
3671 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003672
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003673 /* Ensure that the block 2 length is usable. */
3674 if (ret == 1)
3675 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003676
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003677 /* Copy the fisrt block caping to the length required. */
3678 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3679 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3680 luaL_addlstring(&appctx->b, blk1, len1);
3681 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003682
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003683 /* Copy the second block. */
3684 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3685 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3686 luaL_addlstring(&appctx->b, blk2, len2);
3687 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003688
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003689 /* Consume input channel output buffer data. */
3690 bo_skip(si_oc(si), len1 + len2);
3691 luaL_pushresult(&appctx->b);
3692 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003693}
3694
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003695/* Check arguments for the fucntion "hlua_channel_get_yield". */
3696__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003697{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003698 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003699
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003700 /* Initialise the string catenation. */
3701 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003702
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003703 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003704}
3705
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003706/* If expected data not yet available, it returns a yield. This function
3707 * consumes the data in the buffer. It returns a string containing the
3708 * data. This string can be empty.
3709 */
3710__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003711{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003712 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3713 struct stream_interface *si = appctx->appctx->owner;
3714 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3715 struct channel *chn = si_ic(si);
3716 int ret;
3717 char *blk1;
3718 int len1;
3719 char *blk2;
3720 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003721
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003722 /* Maybe we cant send a 100-continue ? */
3723 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3724 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3725 /* if ret == -2 or -3 the channel closed or the message si too
3726 * big for the buffers. We cant send anything. So, we ignoring
3727 * the error, considers that the 100-continue is sent, and try
3728 * to receive.
3729 * If ret is -1, we dont have room in the buffer, so we yield.
3730 */
3731 if (ret == -1) {
3732 si_applet_cant_put(si);
3733 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3734 }
3735 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3736 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003737
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003738 /* Read the maximum amount of data avalaible. */
3739 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003740
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003741 /* Data not yet avalaible. return yield. */
3742 if (ret == 0) {
3743 si_applet_cant_get(si);
3744 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3745 }
3746
3747 /* End of data: commit the total strings and return. */
3748 if (ret < 0) {
3749 luaL_pushresult(&appctx->b);
3750 return 1;
3751 }
3752
3753 /* Ensure that the block 2 length is usable. */
3754 if (ret == 1)
3755 len2 = 0;
3756
3757 /* Copy the fisrt block caping to the length required. */
3758 if (len1 > len)
3759 len1 = len;
3760 luaL_addlstring(&appctx->b, blk1, len1);
3761 len -= len1;
3762
3763 /* Copy the second block. */
3764 if (len2 > len)
3765 len2 = len;
3766 luaL_addlstring(&appctx->b, blk2, len2);
3767 len -= len2;
3768
3769 /* Consume input channel output buffer data. */
3770 bo_skip(si_oc(si), len1 + len2);
3771 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
3772 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
3773
3774 /* If we are no other data avalaible, yield waiting for new data. */
3775 if (len > 0) {
3776 lua_pushinteger(L, len);
3777 lua_replace(L, 2);
3778 si_applet_cant_get(si);
3779 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3780 }
3781
3782 /* return the result. */
3783 luaL_pushresult(&appctx->b);
3784 return 1;
3785}
3786
3787/* Check arguments for the fucntion "hlua_channel_get_yield". */
3788__LJMP static int hlua_applet_http_recv(lua_State *L)
3789{
3790 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3791 int len = -1;
3792
3793 /* Check arguments. */
3794 if (lua_gettop(L) > 2)
3795 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3796 if (lua_gettop(L) >= 2) {
3797 len = MAY_LJMP(luaL_checkinteger(L, 2));
3798 lua_pop(L, 1);
3799 }
3800
3801 /* Check the required length */
3802 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3803 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3804 lua_pushinteger(L, len);
3805
3806 /* Initialise the string catenation. */
3807 luaL_buffinit(L, &appctx->b);
3808
3809 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
3810}
3811
3812/* Append data in the output side of the buffer. This data is immediatly
3813 * sent. The fcuntion returns the ammount of data writed. If the buffer
3814 * cannot contains the data, the function yield. The function returns -1
3815 * if the channel is closed.
3816 */
3817__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
3818{
3819 size_t len;
3820 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3821 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3822 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3823 struct stream_interface *si = appctx->appctx->owner;
3824 struct channel *chn = si_ic(si);
3825 int max;
3826
3827 /* Get the max amount of data which can write as input in the channel. */
3828 max = channel_recv_max(chn);
3829 if (max > (len - l))
3830 max = len - l;
3831
3832 /* Copy data. */
3833 bi_putblk(chn, str + l, max);
3834
3835 /* update counters. */
3836 l += max;
3837 lua_pop(L, 1);
3838 lua_pushinteger(L, l);
3839
3840 /* If some data is not send, declares the situation to the
3841 * applet, and returns a yield.
3842 */
3843 if (l < len) {
3844 si_applet_cant_put(si);
3845 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
3846 }
3847
3848 return 1;
3849}
3850
3851/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
3852 * yield the LUA process, and resume it without checking the
3853 * input arguments.
3854 */
3855__LJMP static int hlua_applet_http_send(lua_State *L)
3856{
3857 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3858 size_t len;
3859 char hex[10];
3860
3861 MAY_LJMP(luaL_checklstring(L, 2, &len));
3862
3863 /* If transfer encoding chunked is selected, we surround the data
3864 * by chunk data.
3865 */
3866 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
3867 snprintf(hex, 9, "%x", (unsigned int)len);
3868 lua_pushfstring(L, "%s\r\n", hex);
3869 lua_insert(L, 2); /* swap the last 2 entries. */
3870 lua_pushstring(L, "\r\n");
3871 lua_concat(L, 3);
3872 }
3873
3874 /* This interger is used for followinf the amount of data sent. */
3875 lua_pushinteger(L, 0);
3876
3877 /* We want to send some data. Headers must be sent. */
3878 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
3879 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
3880 WILL_LJMP(lua_error(L));
3881 }
3882
3883 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
3884}
3885
3886__LJMP static int hlua_applet_http_addheader(lua_State *L)
3887{
3888 const char *name;
3889 int ret;
3890
3891 MAY_LJMP(hlua_checkapplet_http(L, 1));
3892 name = MAY_LJMP(luaL_checkstring(L, 2));
3893 MAY_LJMP(luaL_checkstring(L, 3));
3894
3895 /* Push in the stack the "response" entry. */
3896 ret = lua_getfield(L, 1, "response");
3897 if (ret != LUA_TTABLE) {
3898 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
3899 "is expected as an array. %s found", lua_typename(L, ret));
3900 WILL_LJMP(lua_error(L));
3901 }
3902
3903 /* check if the header is already registered if it is not
3904 * the case, register it.
3905 */
3906 ret = lua_getfield(L, -1, name);
3907 if (ret == LUA_TNIL) {
3908
3909 /* Entry not found. */
3910 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
3911
3912 /* Insert the new header name in the array in the top of the stack.
3913 * It left the new array in the top of the stack.
3914 */
3915 lua_newtable(L);
3916 lua_pushvalue(L, 2);
3917 lua_pushvalue(L, -2);
3918 lua_settable(L, -4);
3919
3920 } else if (ret != LUA_TTABLE) {
3921
3922 /* corruption error. */
3923 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
3924 "is expected as an array. %s found", name, lua_typename(L, ret));
3925 WILL_LJMP(lua_error(L));
3926 }
3927
3928 /* Now the top od thestack is an array of values. We push
3929 * the header value as new entry.
3930 */
3931 lua_pushvalue(L, 3);
3932 ret = lua_rawlen(L, -2);
3933 lua_rawseti(L, -2, ret + 1);
3934 lua_pushboolean(L, 1);
3935 return 1;
3936}
3937
3938__LJMP static int hlua_applet_http_status(lua_State *L)
3939{
3940 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3941 int status = MAY_LJMP(luaL_checkinteger(L, 2));
3942
3943 if (status < 100 || status > 599) {
3944 lua_pushboolean(L, 0);
3945 return 1;
3946 }
3947
3948 appctx->appctx->ctx.hlua_apphttp.status = status;
3949 lua_pushboolean(L, 1);
3950 return 1;
3951}
3952
3953/* We will build the status line and the headers of the HTTP response.
3954 * We will try send at once if its not possible, we give back the hand
3955 * waiting for more room.
3956 */
3957__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
3958{
3959 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3960 struct stream_interface *si = appctx->appctx->owner;
3961 struct channel *chn = si_ic(si);
3962 int ret;
3963 size_t len;
3964 const char *msg;
3965
3966 /* Get the message as the first argument on the stack. */
3967 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
3968
3969 /* Send the message at once. */
3970 ret = bi_putblk(chn, msg, len);
3971
3972 /* if ret == -2 or -3 the channel closed or the message si too
3973 * big for the buffers.
3974 */
3975 if (ret == -2 || ret == -3) {
3976 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
3977 WILL_LJMP(lua_error(L));
3978 }
3979
3980 /* If ret is -1, we dont have room in the buffer, so we yield. */
3981 if (ret == -1) {
3982 si_applet_cant_put(si);
3983 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
3984 }
3985
3986 /* Headers sent, set the flag. */
3987 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
3988 return 0;
3989}
3990
3991__LJMP static int hlua_applet_http_start_response(lua_State *L)
3992{
3993 struct chunk *tmp = get_trash_chunk();
3994 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003995 const char *name;
3996 const char *value;
3997 int id;
3998 int hdr_connection = 0;
3999 int hdr_contentlength = -1;
4000 int hdr_chunked = 0;
4001
4002 /* Use the same http version than the request. */
4003 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004004 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004005 appctx->appctx->ctx.hlua_apphttp.status,
4006 get_reason(appctx->appctx->ctx.hlua_apphttp.status));
4007
4008 /* Get the array associated to the field "response" in the object AppletHTTP. */
4009 lua_pushvalue(L, 0);
4010 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4011 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4012 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4013 WILL_LJMP(lua_error(L));
4014 }
4015
4016 /* Browse the list of headers. */
4017 lua_pushnil(L);
4018 while(lua_next(L, -2) != 0) {
4019
4020 /* We expect a string as -2. */
4021 if (lua_type(L, -2) != LUA_TSTRING) {
4022 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4023 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4024 lua_typename(L, lua_type(L, -2)));
4025 WILL_LJMP(lua_error(L));
4026 }
4027 name = lua_tostring(L, -2);
4028
4029 /* We expect an array as -1. */
4030 if (lua_type(L, -1) != LUA_TTABLE) {
4031 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4032 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4033 name,
4034 lua_typename(L, lua_type(L, -1)));
4035 WILL_LJMP(lua_error(L));
4036 }
4037
4038 /* Browse the table who is on the top of the stack. */
4039 lua_pushnil(L);
4040 while(lua_next(L, -2) != 0) {
4041
4042 /* We expect a number as -2. */
4043 if (lua_type(L, -2) != LUA_TNUMBER) {
4044 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4045 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4046 name,
4047 lua_typename(L, lua_type(L, -2)));
4048 WILL_LJMP(lua_error(L));
4049 }
4050 id = lua_tointeger(L, -2);
4051
4052 /* We expect a string as -2. */
4053 if (lua_type(L, -1) != LUA_TSTRING) {
4054 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4055 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4056 name, id,
4057 lua_typename(L, lua_type(L, -1)));
4058 WILL_LJMP(lua_error(L));
4059 }
4060 value = lua_tostring(L, -1);
4061
4062 /* Catenate a new header. */
4063 chunk_appendf(tmp, "%s: %s\r\n", name, value);
4064
4065 /* Protocol checks. */
4066
4067 /* Check if the header conneciton is present. */
4068 if (strcasecmp("connection", name) == 0)
4069 hdr_connection = 1;
4070
4071 /* Copy the header content length. The length conversion
4072 * is done without control. If it contains a ad value, this
4073 * is not our problem.
4074 */
4075 if (strcasecmp("content-length", name) == 0)
4076 hdr_contentlength = atoi(value);
4077
4078 /* Check if the client annouces a transfer-encoding chunked it self. */
4079 if (strcasecmp("transfer-encoding", name) == 0 &&
4080 strcasecmp("chunked", value) == 0)
4081 hdr_chunked = 1;
4082
4083 /* Remove the array from the stack, and get next element with a remaining string. */
4084 lua_pop(L, 1);
4085 }
4086
4087 /* Remove the array from the stack, and get next element with a remaining string. */
4088 lua_pop(L, 1);
4089 }
4090
4091 /* If the http protocol version is 1.1, we expect an header "connection" set
4092 * to "close" to be HAProxy/keeplive compliant. Otherwise, we expect nothing.
4093 * If the header conneciton is present, don't change it, if it is not present,
4094 * we must set.
4095 *
4096 * we set a "connection: close" header for ensuring that the keepalive will be
4097 * respected by haproxy. HAProcy considers that the application cloe the connection
4098 * and it keep the connection from the client open.
4099 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004100 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 && !hdr_connection)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004101 chunk_appendf(tmp, "Connection: close\r\n");
4102
4103 /* If we dont have a content-length set, we must announce a transfer enconding
4104 * chunked. This is required by haproxy for the keepalive compliance.
4105 * If the applet annouce a transfer-encoding chunked itslef, don't
4106 * do anything.
4107 */
4108 if (hdr_contentlength == -1 && hdr_chunked == 0) {
4109 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4110 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4111 }
4112
4113 /* Finalize headers. */
4114 chunk_appendf(tmp, "\r\n");
4115
4116 /* Remove the last entry and the array of headers */
4117 lua_pop(L, 2);
4118
4119 /* Push the headers block. */
4120 lua_pushlstring(L, tmp->str, tmp->len);
4121
4122 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4123}
4124
4125/*
4126 *
4127 *
4128 * Class HTTP
4129 *
4130 *
4131 */
4132
4133/* Returns a struct hlua_txn if the stack entry "ud" is
4134 * a class stream, otherwise it throws an error.
4135 */
4136__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4137{
4138 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
4139}
4140
4141/* This function creates and push in the stack a HTTP object
4142 * according with a current TXN.
4143 */
4144static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4145{
4146 struct hlua_txn *htxn;
4147
4148 /* Check stack size. */
4149 if (!lua_checkstack(L, 3))
4150 return 0;
4151
4152 /* Create the object: obj[0] = userdata.
4153 * Note that the base of the Converters object is the
4154 * same than the TXN object.
4155 */
4156 lua_newtable(L);
4157 htxn = lua_newuserdata(L, sizeof(*htxn));
4158 lua_rawseti(L, -2, 0);
4159
4160 htxn->s = txn->s;
4161 htxn->p = txn->p;
4162
4163 /* Pop a class stream metatable and affect it to the table. */
4164 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4165 lua_setmetatable(L, -2);
4166
4167 return 1;
4168}
4169
4170/* This function creates ans returns an array of HTTP headers.
4171 * This function does not fails. It is used as wrapper with the
4172 * 2 following functions.
4173 */
4174__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4175{
4176 const char *cur_ptr, *cur_next, *p;
4177 int old_idx, cur_idx;
4178 struct hdr_idx_elem *cur_hdr;
4179 const char *hn, *hv;
4180 int hnl, hvl;
4181 int type;
4182 const char *in;
4183 char *out;
4184 int len;
4185
4186 /* Create the table. */
4187 lua_newtable(L);
4188
4189 if (!htxn->s->txn)
4190 return 1;
4191
4192 /* Build array of headers. */
4193 old_idx = 0;
4194 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4195
4196 while (1) {
4197 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4198 if (!cur_idx)
4199 break;
4200 old_idx = cur_idx;
4201
4202 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4203 cur_ptr = cur_next;
4204 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4205
4206 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4207 * and the next header starts at cur_next. We'll check
4208 * this header in the list as well as against the default
4209 * rule.
4210 */
4211
4212 /* look for ': *'. */
4213 hn = cur_ptr;
4214 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4215 if (p >= cur_ptr+cur_hdr->len)
4216 continue;
4217 hnl = p - hn;
4218 p++;
4219 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4220 p++;
4221 if (p >= cur_ptr+cur_hdr->len)
4222 continue;
4223 hv = p;
4224 hvl = cur_ptr+cur_hdr->len-p;
4225
4226 /* Lowercase the key. Don't check the size of trash, it have
4227 * the size of one buffer and the input data contains in one
4228 * buffer.
4229 */
4230 out = trash.str;
4231 for (in=hn; in<hn+hnl; in++, out++)
4232 *out = tolower(*in);
4233 *out = '\0';
4234
4235 /* Check for existing entry:
4236 * assume that the table is on the top of the stack, and
4237 * push the key in the stack, the function lua_gettable()
4238 * perform the lookup.
4239 */
4240 lua_pushlstring(L, trash.str, hnl);
4241 lua_gettable(L, -2);
4242 type = lua_type(L, -1);
4243
4244 switch (type) {
4245 case LUA_TNIL:
4246 /* Table not found, create it. */
4247 lua_pop(L, 1); /* remove the nil value. */
4248 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4249 lua_newtable(L); /* create and push empty table. */
4250 lua_pushlstring(L, hv, hvl); /* push header value. */
4251 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4252 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4253 break;
4254
4255 case LUA_TTABLE:
4256 /* Entry found: push the value in the table. */
4257 len = lua_rawlen(L, -1);
4258 lua_pushlstring(L, hv, hvl); /* push header value. */
4259 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4260 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4261 break;
4262
4263 default:
4264 /* Other cases are errors. */
4265 hlua_pusherror(L, "internal error during the parsing of headers.");
4266 WILL_LJMP(lua_error(L));
4267 }
4268 }
4269
4270 return 1;
4271}
4272
4273__LJMP static int hlua_http_req_get_headers(lua_State *L)
4274{
4275 struct hlua_txn *htxn;
4276
4277 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4278 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4279
4280 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4281}
4282
4283__LJMP static int hlua_http_res_get_headers(lua_State *L)
4284{
4285 struct hlua_txn *htxn;
4286
4287 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4288 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4289
4290 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4291}
4292
4293/* This function replace full header, or just a value in
4294 * the request or in the response. It is a wrapper fir the
4295 * 4 following functions.
4296 */
4297__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4298 struct http_msg *msg, int action)
4299{
4300 size_t name_len;
4301 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4302 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4303 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4304 struct my_regex re;
4305
4306 if (!regex_comp(reg, &re, 1, 1, NULL))
4307 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4308
4309 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4310 regex_free(&re);
4311 return 0;
4312}
4313
4314__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4315{
4316 struct hlua_txn *htxn;
4317
4318 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4319 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4320
4321 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4322}
4323
4324__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4325{
4326 struct hlua_txn *htxn;
4327
4328 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4329 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4330
4331 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4332}
4333
4334__LJMP static int hlua_http_req_rep_val(lua_State *L)
4335{
4336 struct hlua_txn *htxn;
4337
4338 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4339 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4340
4341 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4342}
4343
4344__LJMP static int hlua_http_res_rep_val(lua_State *L)
4345{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004346 struct hlua_txn *htxn;
4347
4348 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4349 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4350
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004351 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004352}
4353
4354/* This function deletes all the occurences of an header.
4355 * It is a wrapper for the 2 following functions.
4356 */
4357__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4358{
4359 size_t len;
4360 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4361 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004362 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004363
4364 ctx.idx = 0;
4365 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4366 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4367 return 0;
4368}
4369
4370__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4371{
4372 struct hlua_txn *htxn;
4373
4374 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4375 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4376
Willy Tarreaueee5b512015-04-03 23:46:31 +02004377 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004378}
4379
4380__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4381{
4382 struct hlua_txn *htxn;
4383
4384 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4385 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4386
Willy Tarreaueee5b512015-04-03 23:46:31 +02004387 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004388}
4389
4390/* This function adds an header. It is a wrapper used by
4391 * the 2 following functions.
4392 */
4393__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4394{
4395 size_t name_len;
4396 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4397 size_t value_len;
4398 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4399 char *p;
4400
4401 /* Check length. */
4402 trash.len = value_len + name_len + 2;
4403 if (trash.len > trash.size)
4404 return 0;
4405
4406 /* Creates the header string. */
4407 p = trash.str;
4408 memcpy(p, name, name_len);
4409 p += name_len;
4410 *p = ':';
4411 p++;
4412 *p = ' ';
4413 p++;
4414 memcpy(p, value, value_len);
4415
Willy Tarreaueee5b512015-04-03 23:46:31 +02004416 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004417 trash.str, trash.len) != 0);
4418
4419 return 0;
4420}
4421
4422__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4423{
4424 struct hlua_txn *htxn;
4425
4426 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4427 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4428
Willy Tarreaueee5b512015-04-03 23:46:31 +02004429 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004430}
4431
4432__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4433{
4434 struct hlua_txn *htxn;
4435
4436 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4437 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4438
Willy Tarreaueee5b512015-04-03 23:46:31 +02004439 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004440}
4441
4442static int hlua_http_req_set_hdr(lua_State *L)
4443{
4444 struct hlua_txn *htxn;
4445
4446 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4447 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4448
Willy Tarreaueee5b512015-04-03 23:46:31 +02004449 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4450 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004451}
4452
4453static int hlua_http_res_set_hdr(lua_State *L)
4454{
4455 struct hlua_txn *htxn;
4456
4457 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4458 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4459
Willy Tarreaueee5b512015-04-03 23:46:31 +02004460 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4461 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004462}
4463
4464/* This function set the method. */
4465static int hlua_http_req_set_meth(lua_State *L)
4466{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004467 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004468 size_t name_len;
4469 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004470
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004471 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004472 return 1;
4473}
4474
4475/* This function set the method. */
4476static int hlua_http_req_set_path(lua_State *L)
4477{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004478 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004479 size_t name_len;
4480 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004481 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004482 return 1;
4483}
4484
4485/* This function set the query-string. */
4486static int hlua_http_req_set_query(lua_State *L)
4487{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004488 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004489 size_t name_len;
4490 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004491
4492 /* Check length. */
4493 if (name_len > trash.size - 1) {
4494 lua_pushboolean(L, 0);
4495 return 1;
4496 }
4497
4498 /* Add the mark question as prefix. */
4499 chunk_reset(&trash);
4500 trash.str[trash.len++] = '?';
4501 memcpy(trash.str + trash.len, name, name_len);
4502 trash.len += name_len;
4503
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004504 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004505 return 1;
4506}
4507
4508/* This function set the uri. */
4509static int hlua_http_req_set_uri(lua_State *L)
4510{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004511 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004512 size_t name_len;
4513 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004514
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004515 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004516 return 1;
4517}
4518
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004519/* This function set the response code. */
4520static int hlua_http_res_set_status(lua_State *L)
4521{
4522 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4523 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
4524
4525 http_set_status(code, htxn->s);
4526 return 0;
4527}
4528
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004529/*
4530 *
4531 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004532 * Class TXN
4533 *
4534 *
4535 */
4536
4537/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004538 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004539 */
4540__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
4541{
4542 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
4543}
4544
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004545__LJMP static int hlua_set_var(lua_State *L)
4546{
4547 struct hlua_txn *htxn;
4548 const char *name;
4549 size_t len;
4550 struct sample smp;
4551
4552 MAY_LJMP(check_args(L, 3, "set_var"));
4553
4554 /* It is useles to retrieve the stream, but this function
4555 * runs only in a stream context.
4556 */
4557 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4558 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4559
4560 /* Converts the third argument in a sample. */
4561 hlua_lua2smp(L, 3, &smp);
4562
4563 /* Store the sample in a variable. */
4564 vars_set_by_name(name, len, htxn->s, &smp);
4565 return 0;
4566}
4567
4568__LJMP static int hlua_get_var(lua_State *L)
4569{
4570 struct hlua_txn *htxn;
4571 const char *name;
4572 size_t len;
4573 struct sample smp;
4574
4575 MAY_LJMP(check_args(L, 2, "get_var"));
4576
4577 /* It is useles to retrieve the stream, but this function
4578 * runs only in a stream context.
4579 */
4580 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4581 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4582
4583 if (!vars_get_by_name(name, len, htxn->s, &smp)) {
4584 lua_pushnil(L);
4585 return 1;
4586 }
4587
4588 return hlua_smp2lua(L, &smp);
4589}
4590
Willy Tarreau59551662015-03-10 14:23:13 +01004591__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004592{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004593 struct hlua *hlua;
4594
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004595 MAY_LJMP(check_args(L, 2, "set_priv"));
4596
Willy Tarreau87b09662015-04-03 00:22:06 +02004597 /* It is useles to retrieve the stream, but this function
4598 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004599 */
4600 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004601 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004602
4603 /* Remove previous value. */
4604 if (hlua->Mref != -1)
4605 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
4606
4607 /* Get and store new value. */
4608 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4609 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4610
4611 return 0;
4612}
4613
Willy Tarreau59551662015-03-10 14:23:13 +01004614__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004615{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004616 struct hlua *hlua;
4617
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004618 MAY_LJMP(check_args(L, 1, "get_priv"));
4619
Willy Tarreau87b09662015-04-03 00:22:06 +02004620 /* It is useles to retrieve the stream, but this function
4621 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004622 */
4623 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004624 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004625
4626 /* Push configuration index in the stack. */
4627 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4628
4629 return 1;
4630}
4631
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004632/* Create stack entry containing a class TXN. This function
4633 * return 0 if the stack does not contains free slots,
4634 * otherwise it returns 1.
4635 */
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004636static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004637{
Willy Tarreaude491382015-04-06 11:04:28 +02004638 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004639
4640 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004641 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004642 return 0;
4643
4644 /* NOTE: The allocation never fails. The failure
4645 * throw an error, and the function never returns.
4646 * if the throw is not avalaible, the process is aborted.
4647 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004648 /* Create the object: obj[0] = userdata. */
4649 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02004650 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004651 lua_rawseti(L, -2, 0);
4652
Willy Tarreaude491382015-04-06 11:04:28 +02004653 htxn->s = s;
4654 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004655 htxn->dir = dir;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004656
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004657 /* Create the "f" field that contains a list of fetches. */
4658 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004659 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004660 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004661 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004662
4663 /* Create the "sf" field that contains a list of stringsafe fetches. */
4664 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004665 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004666 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004667 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004668
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004669 /* Create the "c" field that contains a list of converters. */
4670 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02004671 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004672 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004673 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004674
4675 /* Create the "sc" field that contains a list of stringsafe converters. */
4676 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004677 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004678 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004679 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004680
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004681 /* Create the "req" field that contains the request channel object. */
4682 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004683 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004684 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004685 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004686
4687 /* Create the "res" field that contains the response channel object. */
4688 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004689 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004690 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004691 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004692
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004693 /* Creates the HTTP object is the current proxy allows http. */
4694 lua_pushstring(L, "http");
4695 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02004696 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004697 return 0;
4698 }
4699 else
4700 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004701 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004702
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004703 /* Pop a class sesison metatable and affect it to the userdata. */
4704 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
4705 lua_setmetatable(L, -2);
4706
4707 return 1;
4708}
4709
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004710__LJMP static int hlua_txn_deflog(lua_State *L)
4711{
4712 const char *msg;
4713 struct hlua_txn *htxn;
4714
4715 MAY_LJMP(check_args(L, 2, "deflog"));
4716 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4717 msg = MAY_LJMP(luaL_checkstring(L, 2));
4718
4719 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
4720 return 0;
4721}
4722
4723__LJMP static int hlua_txn_log(lua_State *L)
4724{
4725 int level;
4726 const char *msg;
4727 struct hlua_txn *htxn;
4728
4729 MAY_LJMP(check_args(L, 3, "log"));
4730 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4731 level = MAY_LJMP(luaL_checkinteger(L, 2));
4732 msg = MAY_LJMP(luaL_checkstring(L, 3));
4733
4734 if (level < 0 || level >= NB_LOG_LEVELS)
4735 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
4736
4737 hlua_sendlog(htxn->s->be, level, msg);
4738 return 0;
4739}
4740
4741__LJMP static int hlua_txn_log_debug(lua_State *L)
4742{
4743 const char *msg;
4744 struct hlua_txn *htxn;
4745
4746 MAY_LJMP(check_args(L, 2, "Debug"));
4747 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4748 msg = MAY_LJMP(luaL_checkstring(L, 2));
4749 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
4750 return 0;
4751}
4752
4753__LJMP static int hlua_txn_log_info(lua_State *L)
4754{
4755 const char *msg;
4756 struct hlua_txn *htxn;
4757
4758 MAY_LJMP(check_args(L, 2, "Info"));
4759 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4760 msg = MAY_LJMP(luaL_checkstring(L, 2));
4761 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
4762 return 0;
4763}
4764
4765__LJMP static int hlua_txn_log_warning(lua_State *L)
4766{
4767 const char *msg;
4768 struct hlua_txn *htxn;
4769
4770 MAY_LJMP(check_args(L, 2, "Warning"));
4771 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4772 msg = MAY_LJMP(luaL_checkstring(L, 2));
4773 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
4774 return 0;
4775}
4776
4777__LJMP static int hlua_txn_log_alert(lua_State *L)
4778{
4779 const char *msg;
4780 struct hlua_txn *htxn;
4781
4782 MAY_LJMP(check_args(L, 2, "Alert"));
4783 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4784 msg = MAY_LJMP(luaL_checkstring(L, 2));
4785 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
4786 return 0;
4787}
4788
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004789__LJMP static int hlua_txn_set_loglevel(lua_State *L)
4790{
4791 struct hlua_txn *htxn;
4792 int ll;
4793
4794 MAY_LJMP(check_args(L, 2, "set_loglevel"));
4795 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4796 ll = MAY_LJMP(luaL_checkinteger(L, 2));
4797
4798 if (ll < 0 || ll > 7)
4799 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
4800
4801 htxn->s->logs.level = ll;
4802 return 0;
4803}
4804
4805__LJMP static int hlua_txn_set_tos(lua_State *L)
4806{
4807 struct hlua_txn *htxn;
4808 struct connection *cli_conn;
4809 int tos;
4810
4811 MAY_LJMP(check_args(L, 2, "set_tos"));
4812 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4813 tos = MAY_LJMP(luaL_checkinteger(L, 2));
4814
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02004815 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004816 inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, tos);
4817
4818 return 0;
4819}
4820
4821__LJMP static int hlua_txn_set_mark(lua_State *L)
4822{
4823#ifdef SO_MARK
4824 struct hlua_txn *htxn;
4825 struct connection *cli_conn;
4826 int mark;
4827
4828 MAY_LJMP(check_args(L, 2, "set_mark"));
4829 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4830 mark = MAY_LJMP(luaL_checkinteger(L, 2));
4831
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02004832 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02004833 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004834#endif
4835 return 0;
4836}
4837
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004838/* This function is an Lua binding that send pending data
4839 * to the client, and close the stream interface.
4840 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004841__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004842{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004843 struct hlua_txn *htxn;
Willy Tarreau81389672015-03-10 12:03:52 +01004844 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004845
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004846 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004847 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004848
Willy Tarreaub2ccb562015-04-06 11:11:15 +02004849 ic = &htxn->s->req;
4850 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01004851
Willy Tarreau630ef452015-08-28 10:06:15 +02004852 if (htxn->s->txn) {
4853 /* HTTP mode, let's stay in sync with the stream */
4854 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
4855 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
4856 htxn->s->txn->req.sov = 0;
4857 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
4858 oc->analysers = AN_RES_HTTP_XFER_BODY;
4859 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
4860 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
4861
Willy Tarreau630ef452015-08-28 10:06:15 +02004862 /* Note that if we want to support keep-alive, we need
4863 * to bypass the close/shutr_now calls below, but that
4864 * may only be done if the HTTP request was already
4865 * processed and the connection header is known (ie
4866 * not during TCP rules).
4867 */
4868 }
4869
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02004870 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01004871 channel_abort(ic);
4872 channel_auto_close(ic);
4873 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02004874
4875 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01004876 channel_auto_read(oc);
4877 channel_auto_close(oc);
4878 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004879
Willy Tarreau0458b082015-08-28 09:40:04 +02004880 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004881
4882 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004883 return 0;
4884}
4885
4886__LJMP static int hlua_log(lua_State *L)
4887{
4888 int level;
4889 const char *msg;
4890
4891 MAY_LJMP(check_args(L, 2, "log"));
4892 level = MAY_LJMP(luaL_checkinteger(L, 1));
4893 msg = MAY_LJMP(luaL_checkstring(L, 2));
4894
4895 if (level < 0 || level >= NB_LOG_LEVELS)
4896 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
4897
4898 hlua_sendlog(NULL, level, msg);
4899 return 0;
4900}
4901
4902__LJMP static int hlua_log_debug(lua_State *L)
4903{
4904 const char *msg;
4905
4906 MAY_LJMP(check_args(L, 1, "debug"));
4907 msg = MAY_LJMP(luaL_checkstring(L, 1));
4908 hlua_sendlog(NULL, LOG_DEBUG, msg);
4909 return 0;
4910}
4911
4912__LJMP static int hlua_log_info(lua_State *L)
4913{
4914 const char *msg;
4915
4916 MAY_LJMP(check_args(L, 1, "info"));
4917 msg = MAY_LJMP(luaL_checkstring(L, 1));
4918 hlua_sendlog(NULL, LOG_INFO, msg);
4919 return 0;
4920}
4921
4922__LJMP static int hlua_log_warning(lua_State *L)
4923{
4924 const char *msg;
4925
4926 MAY_LJMP(check_args(L, 1, "warning"));
4927 msg = MAY_LJMP(luaL_checkstring(L, 1));
4928 hlua_sendlog(NULL, LOG_WARNING, msg);
4929 return 0;
4930}
4931
4932__LJMP static int hlua_log_alert(lua_State *L)
4933{
4934 const char *msg;
4935
4936 MAY_LJMP(check_args(L, 1, "alert"));
4937 msg = MAY_LJMP(luaL_checkstring(L, 1));
4938 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004939 return 0;
4940}
4941
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004942__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004943{
4944 int wakeup_ms = lua_tointeger(L, -1);
4945 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004946 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004947 return 0;
4948}
4949
4950__LJMP static int hlua_sleep(lua_State *L)
4951{
4952 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004953 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004954
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004955 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004956
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004957 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004958 wakeup_ms = tick_add(now_ms, delay);
4959 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004960
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004961 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
4962 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004963}
4964
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004965__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004966{
4967 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004968 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004969
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004970 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004971
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004972 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004973 wakeup_ms = tick_add(now_ms, delay);
4974 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004975
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004976 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
4977 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004978}
4979
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004980/* This functionis an LUA binding. it permits to give back
4981 * the hand at the HAProxy scheduler. It is used when the
4982 * LUA processing consumes a lot of time.
4983 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01004984__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004985{
4986 return 0;
4987}
4988
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004989__LJMP static int hlua_yield(lua_State *L)
4990{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01004991 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
4992 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004993}
4994
Thierry FOURNIER37196f42015-02-16 19:34:56 +01004995/* This function change the nice of the currently executed
4996 * task. It is used set low or high priority at the current
4997 * task.
4998 */
Willy Tarreau59551662015-03-10 14:23:13 +01004999__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005000{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005001 struct hlua *hlua;
5002 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005003
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005004 MAY_LJMP(check_args(L, 1, "set_nice"));
5005 hlua = hlua_gethlua(L);
5006 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005007
5008 /* If he task is not set, I'm in a start mode. */
5009 if (!hlua || !hlua->task)
5010 return 0;
5011
5012 if (nice < -1024)
5013 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005014 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005015 nice = 1024;
5016
5017 hlua->task->nice = nice;
5018 return 0;
5019}
5020
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005021/* This function is used as a calback of a task. It is called by the
5022 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5023 * return an E_AGAIN signal, the emmiter of this signal must set a
5024 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005025 *
5026 * Task wrapper are longjmp safe because the only one Lua code
5027 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005028 */
5029static struct task *hlua_process_task(struct task *task)
5030{
5031 struct hlua *hlua = task->context;
5032 enum hlua_exec status;
5033
5034 /* We need to remove the task from the wait queue before executing
5035 * the Lua code because we don't know if it needs to wait for
5036 * another timer or not in the case of E_AGAIN.
5037 */
5038 task_delete(task);
5039
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005040 /* If it is the first call to the task, we must initialize the
5041 * execution timeouts.
5042 */
5043 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005044 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005045
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005046 /* Execute the Lua code. */
5047 status = hlua_ctx_resume(hlua, 1);
5048
5049 switch (status) {
5050 /* finished or yield */
5051 case HLUA_E_OK:
5052 hlua_ctx_destroy(hlua);
5053 task_delete(task);
5054 task_free(task);
5055 break;
5056
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005057 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
5058 if (hlua->wake_time != TICK_ETERNITY)
5059 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005060 break;
5061
5062 /* finished with error. */
5063 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005064 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005065 hlua_ctx_destroy(hlua);
5066 task_delete(task);
5067 task_free(task);
5068 break;
5069
5070 case HLUA_E_ERR:
5071 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005072 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005073 hlua_ctx_destroy(hlua);
5074 task_delete(task);
5075 task_free(task);
5076 break;
5077 }
5078 return NULL;
5079}
5080
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005081/* This function is an LUA binding that register LUA function to be
5082 * executed after the HAProxy configuration parsing and before the
5083 * HAProxy scheduler starts. This function expect only one LUA
5084 * argument that is a function. This function returns nothing, but
5085 * throws if an error is encountered.
5086 */
5087__LJMP static int hlua_register_init(lua_State *L)
5088{
5089 struct hlua_init_function *init;
5090 int ref;
5091
5092 MAY_LJMP(check_args(L, 1, "register_init"));
5093
5094 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5095
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005096 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005097 if (!init)
5098 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5099
5100 init->function_ref = ref;
5101 LIST_ADDQ(&hlua_init_functions, &init->l);
5102 return 0;
5103}
5104
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005105/* This functio is an LUA binding. It permits to register a task
5106 * executed in parallel of the main HAroxy activity. The task is
5107 * created and it is set in the HAProxy scheduler. It can be called
5108 * from the "init" section, "post init" or during the runtime.
5109 *
5110 * Lua prototype:
5111 *
5112 * <none> core.register_task(<function>)
5113 */
5114static int hlua_register_task(lua_State *L)
5115{
5116 struct hlua *hlua;
5117 struct task *task;
5118 int ref;
5119
5120 MAY_LJMP(check_args(L, 1, "register_task"));
5121
5122 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5123
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005124 hlua = calloc(1, sizeof(*hlua));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005125 if (!hlua)
5126 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5127
5128 task = task_new();
5129 task->context = hlua;
5130 task->process = hlua_process_task;
5131
5132 if (!hlua_ctx_init(hlua, task))
5133 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5134
5135 /* Restore the function in the stack. */
5136 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5137 hlua->nargs = 0;
5138
5139 /* Schedule task. */
5140 task_schedule(task, now_ms);
5141
5142 return 0;
5143}
5144
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005145/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5146 * doesn't allow "yield" functions because the HAProxy engine cannot
5147 * resume converters.
5148 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005149static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005150{
5151 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005152 struct stream *stream = smp->strm;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005153
Willy Tarreau87b09662015-04-03 00:22:06 +02005154 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005155 * Lua context can be not initialized. This behavior
5156 * permits to save performances because a systematic
5157 * Lua initialization cause 5% performances loss.
5158 */
Willy Tarreau87b09662015-04-03 00:22:06 +02005159 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005160 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005161 return 0;
5162 }
5163
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005164 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005165 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005166
5167 /* The following Lua calls can fail. */
5168 if (!SET_SAFE_LJMP(stream->hlua.T)) {
5169 SEND_ERR(stream->be, "Lua converter '%s': critical error.\n", fcn->name);
5170 return 0;
5171 }
5172
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005173 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005174 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005175 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005176 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005177 return 0;
5178 }
5179
5180 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005181 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005182
5183 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005184 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005185 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005186 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005187 return 0;
5188 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005189 hlua_smp2lua(stream->hlua.T, smp);
5190 stream->hlua.nargs = 2;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005191
5192 /* push keywords in the stack. */
5193 if (arg_p) {
5194 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02005195 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005196 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005197 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005198 return 0;
5199 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005200 hlua_arg2lua(stream->hlua.T, arg_p);
5201 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005202 }
5203 }
5204
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005205 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005206 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005207
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005208 /* At this point the execution is safe. */
5209 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005210 }
5211
5212 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005213 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005214 /* finished. */
5215 case HLUA_E_OK:
5216 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005217 hlua_lua2smp(stream->hlua.T, -1, smp);
5218 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005219 return 1;
5220
5221 /* yield. */
5222 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005223 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005224 return 0;
5225
5226 /* finished with error. */
5227 case HLUA_E_ERRMSG:
5228 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005229 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
5230 fcn->name, lua_tostring(stream->hlua.T, -1));
Willy Tarreau87b09662015-04-03 00:22:06 +02005231 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005232 return 0;
5233
5234 case HLUA_E_ERR:
5235 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005236 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005237
5238 default:
5239 return 0;
5240 }
5241}
5242
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005243/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5244 * doesn't allow "yield" functions because the HAProxy engine cannot
5245 * resume sample-fetches.
5246 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005247static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5248 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005249{
5250 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005251 struct stream *stream = smp->strm;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005252
Willy Tarreau87b09662015-04-03 00:22:06 +02005253 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005254 * Lua context can be not initialized. This behavior
5255 * permits to save performances because a systematic
5256 * Lua initialization cause 5% performances loss.
5257 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005258 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005259 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005260 return 0;
5261 }
5262
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005263 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005264 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005265
5266 /* The following Lua calls can fail. */
5267 if (!SET_SAFE_LJMP(stream->hlua.T)) {
5268 SEND_ERR(smp->px, "Lua sample-fetch '%s': critical error.\n", fcn->name);
5269 return 0;
5270 }
5271
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005272 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005273 if (!lua_checkstack(stream->hlua.T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005274 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005275 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005276 return 0;
5277 }
5278
5279 /* Restore the function in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005280 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005281
5282 /* push arguments in the stack. */
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005283 if (!hlua_txn_new(stream->hlua.T, stream, smp->px, smp->opt & SMP_OPT_DIR)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005284 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005285 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005286 return 0;
5287 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005288 stream->hlua.nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005289
5290 /* push keywords in the stack. */
5291 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5292 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005293 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005294 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005295 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005296 return 0;
5297 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005298 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005299 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005300 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005301 return 0;
5302 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005303 hlua_arg2lua(stream->hlua.T, arg_p);
5304 stream->hlua.nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005305 }
5306
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005307 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005308 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005309
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005310 /* At this point the execution is safe. */
5311 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005312 }
5313
5314 /* Execute the function. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005315 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005316 /* finished. */
5317 case HLUA_E_OK:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005318 if (!hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005319 return 0;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005320 /* Convert the returned value in sample. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005321 hlua_lua2smp(stream->hlua.T, -1, smp);
5322 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005323
5324 /* Set the end of execution flag. */
5325 smp->flags &= ~SMP_F_MAY_CHANGE;
5326 return 1;
5327
5328 /* yield. */
5329 case HLUA_E_AGAIN:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005330 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005331 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005332 return 0;
5333
5334 /* finished with error. */
5335 case HLUA_E_ERRMSG:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005336 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005337 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005338 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
5339 fcn->name, lua_tostring(stream->hlua.T, -1));
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005340 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005341 return 0;
5342
5343 case HLUA_E_ERR:
Thierry FOURNIER26a7aac2015-10-13 14:25:11 +02005344 hlua_check_proto(stream, (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_RES);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005345 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005346 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005347
5348 default:
5349 return 0;
5350 }
5351}
5352
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005353/* This function is an LUA binding used for registering
5354 * "sample-conv" functions. It expects a converter name used
5355 * in the haproxy configuration file, and an LUA function.
5356 */
5357__LJMP static int hlua_register_converters(lua_State *L)
5358{
5359 struct sample_conv_kw_list *sck;
5360 const char *name;
5361 int ref;
5362 int len;
5363 struct hlua_function *fcn;
5364
5365 MAY_LJMP(check_args(L, 2, "register_converters"));
5366
5367 /* First argument : converter name. */
5368 name = MAY_LJMP(luaL_checkstring(L, 1));
5369
5370 /* Second argument : lua function. */
5371 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5372
5373 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005374 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005375 if (!sck)
5376 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005377 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005378 if (!fcn)
5379 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5380
5381 /* Fill fcn. */
5382 fcn->name = strdup(name);
5383 if (!fcn->name)
5384 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5385 fcn->function_ref = ref;
5386
5387 /* List head */
5388 sck->list.n = sck->list.p = NULL;
5389
5390 /* converter keyword. */
5391 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005392 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005393 if (!sck->kw[0].kw)
5394 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5395
5396 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5397 sck->kw[0].process = hlua_sample_conv_wrapper;
5398 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
5399 sck->kw[0].val_args = NULL;
5400 sck->kw[0].in_type = SMP_T_STR;
5401 sck->kw[0].out_type = SMP_T_STR;
5402 sck->kw[0].private = fcn;
5403
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005404 /* Register this new converter */
5405 sample_register_convs(sck);
5406
5407 return 0;
5408}
5409
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005410/* This fucntion is an LUA binding used for registering
5411 * "sample-fetch" functions. It expects a converter name used
5412 * in the haproxy configuration file, and an LUA function.
5413 */
5414__LJMP static int hlua_register_fetches(lua_State *L)
5415{
5416 const char *name;
5417 int ref;
5418 int len;
5419 struct sample_fetch_kw_list *sfk;
5420 struct hlua_function *fcn;
5421
5422 MAY_LJMP(check_args(L, 2, "register_fetches"));
5423
5424 /* First argument : sample-fetch name. */
5425 name = MAY_LJMP(luaL_checkstring(L, 1));
5426
5427 /* Second argument : lua function. */
5428 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5429
5430 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005431 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005432 if (!sfk)
5433 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005434 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005435 if (!fcn)
5436 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5437
5438 /* Fill fcn. */
5439 fcn->name = strdup(name);
5440 if (!fcn->name)
5441 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5442 fcn->function_ref = ref;
5443
5444 /* List head */
5445 sfk->list.n = sfk->list.p = NULL;
5446
5447 /* sample-fetch keyword. */
5448 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005449 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005450 if (!sfk->kw[0].kw)
5451 return luaL_error(L, "lua out of memory error.");
5452
5453 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
5454 sfk->kw[0].process = hlua_sample_fetch_wrapper;
5455 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
5456 sfk->kw[0].val_args = NULL;
5457 sfk->kw[0].out_type = SMP_T_STR;
5458 sfk->kw[0].use = SMP_USE_HTTP_ANY;
5459 sfk->kw[0].val = 0;
5460 sfk->kw[0].private = fcn;
5461
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005462 /* Register this new fetch. */
5463 sample_register_fetches(sfk);
5464
5465 return 0;
5466}
5467
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005468/* This function is a wrapper to execute each LUA function declared
5469 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005470 * return ACT_RET_CONT if the processing is finished (with or without
5471 * error) and return ACT_RET_YIELD if the function must be called again
5472 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005473 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005474static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02005475 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005476{
5477 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005478 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005479 int dir;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005480
5481 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01005482 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
5483 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
5484 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
5485 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005486 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005487 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005488 return ACT_RET_CONT;
5489 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005490
Willy Tarreau87b09662015-04-03 00:22:06 +02005491 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005492 * Lua context can be not initialized. This behavior
5493 * permits to save performances because a systematic
5494 * Lua initialization cause 5% performances loss.
5495 */
5496 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005497 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005498 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005499 return ACT_RET_CONT;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005500 }
5501
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005502 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01005503 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005504
5505 /* The following Lua calls can fail. */
5506 if (!SET_SAFE_LJMP(s->hlua.T)) {
5507 SEND_ERR(px, "Lua function '%s': critical error.\n",
5508 rule->arg.hlua_rule->fcn.name);
5509 return ACT_RET_CONT;
5510 }
5511
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005512 /* Check stack available size. */
5513 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005514 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005515 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005516 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005517 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005518 }
5519
5520 /* Restore the function in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005521 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005522
Willy Tarreau87b09662015-04-03 00:22:06 +02005523 /* Create and and push object stream in the stack. */
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005524 if (!hlua_txn_new(s->hlua.T, s, px, dir)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005525 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005526 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005527 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005528 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005529 }
5530 s->hlua.nargs = 1;
5531
5532 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005533 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005534 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005535 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005536 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005537 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005538 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005539 }
5540 lua_pushstring(s->hlua.T, *arg);
5541 s->hlua.nargs++;
5542 }
5543
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005544 /* Now the execution is safe. */
5545 RESET_SAFE_LJMP(s->hlua.T);
5546
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005547 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005548 s->hlua.max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005549 }
5550
5551 /* Execute the function. */
Willy Tarreau528192d2015-09-27 10:48:01 +02005552 switch (hlua_ctx_resume(&s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005553 /* finished. */
5554 case HLUA_E_OK:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005555 if (!hlua_check_proto(s, dir))
5556 return ACT_RET_ERR;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005557 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005558
5559 /* yield. */
5560 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005561 /* Set timeout in the required channel. */
5562 if (s->hlua.wake_time != TICK_ETERNITY) {
5563 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005564 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005565 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005566 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005567 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005568 /* Some actions can be wake up when a "write" event
5569 * is detected on a response channel. This is useful
5570 * only for actions targetted on the requests.
5571 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01005572 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005573 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01005574 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005575 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005576 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01005577 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005578 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005579 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005580
5581 /* finished with error. */
5582 case HLUA_E_ERRMSG:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005583 if (!hlua_check_proto(s, dir))
5584 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005585 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005586 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005587 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005588 lua_pop(s->hlua.T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005589 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005590
5591 case HLUA_E_ERR:
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005592 if (!hlua_check_proto(s, dir))
5593 return ACT_RET_ERR;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005594 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005595 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005596 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005597
5598 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005599 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005600 }
5601}
5602
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005603struct task *hlua_applet_wakeup(struct task *t)
5604{
5605 struct appctx *ctx = t->context;
5606 struct stream_interface *si = ctx->owner;
5607
5608 /* If the applet is wake up without any expected work, the sheduler
5609 * remove it from the run queue. This flag indicate that the applet
5610 * is waiting for write. If the buffer is full, the main processing
5611 * will send some data and after call the applet, otherwise it call
5612 * the applet ASAP.
5613 */
5614 si_applet_cant_put(si);
5615 appctx_wakeup(ctx);
5616 return NULL;
5617}
5618
5619static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5620{
5621 struct stream_interface *si = ctx->owner;
5622 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5623 struct task *task;
5624 char **arg;
5625
5626 HLUA_INIT(hlua);
5627 ctx->ctx.hlua_apptcp.flags = 0;
5628
5629 /* Create task used by signal to wakeup applets. */
5630 task = task_new();
5631 if (!task) {
5632 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
5633 ctx->rule->arg.hlua_rule->fcn.name);
5634 return 0;
5635 }
5636 task->nice = 0;
5637 task->context = ctx;
5638 task->process = hlua_applet_wakeup;
5639 ctx->ctx.hlua_apptcp.task = task;
5640
5641 /* In the execution wrappers linked with a stream, the
5642 * Lua context can be not initialized. This behavior
5643 * permits to save performances because a systematic
5644 * Lua initialization cause 5% performances loss.
5645 */
5646 if (!hlua_ctx_init(hlua, task)) {
5647 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
5648 ctx->rule->arg.hlua_rule->fcn.name);
5649 return 0;
5650 }
5651
5652 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005653 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005654
5655 /* The following Lua calls can fail. */
5656 if (!SET_SAFE_LJMP(hlua->T)) {
5657 SEND_ERR(px, "Lua applet tcp '%s': critical error.\n",
5658 ctx->rule->arg.hlua_rule->fcn.name);
5659 RESET_SAFE_LJMP(hlua->T);
5660 return 0;
5661 }
5662
5663 /* Check stack available size. */
5664 if (!lua_checkstack(hlua->T, 1)) {
5665 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5666 ctx->rule->arg.hlua_rule->fcn.name);
5667 RESET_SAFE_LJMP(hlua->T);
5668 return 0;
5669 }
5670
5671 /* Restore the function in the stack. */
5672 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
5673
5674 /* Create and and push object stream in the stack. */
5675 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
5676 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5677 ctx->rule->arg.hlua_rule->fcn.name);
5678 RESET_SAFE_LJMP(hlua->T);
5679 return 0;
5680 }
5681 hlua->nargs = 1;
5682
5683 /* push keywords in the stack. */
5684 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
5685 if (!lua_checkstack(hlua->T, 1)) {
5686 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5687 ctx->rule->arg.hlua_rule->fcn.name);
5688 RESET_SAFE_LJMP(hlua->T);
5689 return 0;
5690 }
5691 lua_pushstring(hlua->T, *arg);
5692 hlua->nargs++;
5693 }
5694
5695 RESET_SAFE_LJMP(hlua->T);
5696
5697 /* Wakeup the applet ASAP. */
5698 si_applet_cant_get(si);
5699 si_applet_cant_put(si);
5700
5701 return 1;
5702}
5703
5704static void hlua_applet_tcp_fct(struct appctx *ctx)
5705{
5706 struct stream_interface *si = ctx->owner;
5707 struct stream *strm = si_strm(si);
5708 struct channel *res = si_ic(si);
5709 struct act_rule *rule = ctx->rule;
5710 struct proxy *px = strm->be;
5711 struct hlua *hlua = &ctx->ctx.hlua_apptcp.hlua;
5712
5713 /* The applet execution is already done. */
5714 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
5715 return;
5716
5717 /* If the stream is disconnect or closed, ldo nothing. */
5718 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
5719 return;
5720
5721 /* Execute the function. */
5722 switch (hlua_ctx_resume(hlua, 1)) {
5723 /* finished. */
5724 case HLUA_E_OK:
5725 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
5726
5727 /* log time */
5728 strm->logs.tv_request = now;
5729
5730 /* eat the whole request */
5731 bo_skip(si_oc(si), si_ob(si)->o);
5732 res->flags |= CF_READ_NULL;
5733 si_shutr(si);
5734 return;
5735
5736 /* yield. */
5737 case HLUA_E_AGAIN:
5738 return;
5739
5740 /* finished with error. */
5741 case HLUA_E_ERRMSG:
5742 /* Display log. */
5743 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
5744 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
5745 lua_pop(hlua->T, 1);
5746 goto error;
5747
5748 case HLUA_E_ERR:
5749 /* Display log. */
5750 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
5751 rule->arg.hlua_rule->fcn.name);
5752 goto error;
5753
5754 default:
5755 goto error;
5756 }
5757
5758error:
5759
5760 /* For all other cases, just close the stream. */
5761 si_shutw(si);
5762 si_shutr(si);
5763 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
5764}
5765
5766static void hlua_applet_tcp_release(struct appctx *ctx)
5767{
5768 task_free(ctx->ctx.hlua_apptcp.task);
5769 ctx->ctx.hlua_apptcp.task = NULL;
5770 hlua_ctx_destroy(&ctx->ctx.hlua_apptcp.hlua);
5771}
5772
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005773/* The function returns 1 if the initialisation is complete, 0 if
5774 * an errors occurs and -1 if more data are required for initializing
5775 * the applet.
5776 */
5777static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5778{
5779 struct stream_interface *si = ctx->owner;
5780 struct channel *req = si_oc(si);
5781 struct http_msg *msg;
5782 struct http_txn *txn;
5783 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
5784 char **arg;
5785 struct hdr_ctx hdr;
5786 struct task *task;
5787 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
5788
5789 /* Wait for a full HTTP request. */
5790 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
5791 if (smp.flags & SMP_F_MAY_CHANGE)
5792 return -1;
5793 return 0;
5794 }
5795 txn = strm->txn;
5796 msg = &txn->req;
5797
Willy Tarreau0078bfc2015-10-07 20:20:28 +02005798 /* We want two things in HTTP mode :
5799 * - enforce server-close mode if we were in keep-alive, so that the
5800 * applet is released after each response ;
5801 * - enable request body transfer to the applet in order to resync
5802 * with the response body.
5803 */
5804 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
5805 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02005806
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005807 HLUA_INIT(hlua);
5808 ctx->ctx.hlua_apphttp.left_bytes = -1;
5809 ctx->ctx.hlua_apphttp.flags = 0;
5810
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01005811 if (txn->req.flags & HTTP_MSGF_VER_11)
5812 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
5813
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005814 /* Create task used by signal to wakeup applets. */
5815 task = task_new();
5816 if (!task) {
5817 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
5818 ctx->rule->arg.hlua_rule->fcn.name);
5819 return 0;
5820 }
5821 task->nice = 0;
5822 task->context = ctx;
5823 task->process = hlua_applet_wakeup;
5824 ctx->ctx.hlua_apphttp.task = task;
5825
5826 /* In the execution wrappers linked with a stream, the
5827 * Lua context can be not initialized. This behavior
5828 * permits to save performances because a systematic
5829 * Lua initialization cause 5% performances loss.
5830 */
5831 if (!hlua_ctx_init(hlua, task)) {
5832 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
5833 ctx->rule->arg.hlua_rule->fcn.name);
5834 return 0;
5835 }
5836
5837 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005838 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005839
5840 /* The following Lua calls can fail. */
5841 if (!SET_SAFE_LJMP(hlua->T)) {
5842 SEND_ERR(px, "Lua applet http '%s': critical error.\n",
5843 ctx->rule->arg.hlua_rule->fcn.name);
5844 return 0;
5845 }
5846
5847 /* Check stack available size. */
5848 if (!lua_checkstack(hlua->T, 1)) {
5849 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5850 ctx->rule->arg.hlua_rule->fcn.name);
5851 RESET_SAFE_LJMP(hlua->T);
5852 return 0;
5853 }
5854
5855 /* Restore the function in the stack. */
5856 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
5857
5858 /* Create and and push object stream in the stack. */
5859 if (!hlua_applet_http_new(hlua->T, ctx)) {
5860 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5861 ctx->rule->arg.hlua_rule->fcn.name);
5862 RESET_SAFE_LJMP(hlua->T);
5863 return 0;
5864 }
5865 hlua->nargs = 1;
5866
5867 /* Look for a 100-continue expected. */
5868 if (msg->flags & HTTP_MSGF_VER_11) {
5869 hdr.idx = 0;
5870 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
5871 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
5872 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
5873 }
5874
5875 /* push keywords in the stack. */
5876 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
5877 if (!lua_checkstack(hlua->T, 1)) {
5878 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
5879 ctx->rule->arg.hlua_rule->fcn.name);
5880 RESET_SAFE_LJMP(hlua->T);
5881 return 0;
5882 }
5883 lua_pushstring(hlua->T, *arg);
5884 hlua->nargs++;
5885 }
5886
5887 RESET_SAFE_LJMP(hlua->T);
5888
5889 /* Wakeup the applet when data is ready for read. */
5890 si_applet_cant_get(si);
5891
5892 return 1;
5893}
5894
5895static void hlua_applet_http_fct(struct appctx *ctx)
5896{
5897 struct stream_interface *si = ctx->owner;
5898 struct stream *strm = si_strm(si);
5899 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005900 struct act_rule *rule = ctx->rule;
5901 struct proxy *px = strm->be;
5902 struct hlua *hlua = &ctx->ctx.hlua_apphttp.hlua;
5903 char *blk1;
5904 int len1;
5905 char *blk2;
5906 int len2;
5907 int ret;
5908
5909 /* If the stream is disconnect or closed, ldo nothing. */
5910 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
5911 return;
5912
5913 /* Set the currently running flag. */
5914 if (!HLUA_IS_RUNNING(hlua) &&
5915 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
5916
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005917 /* Wait for full HTTP analysys. */
5918 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
5919 si_applet_cant_get(si);
5920 return;
5921 }
5922
5923 /* Store the max amount of bytes that we can read. */
5924 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
5925
5926 /* We need to flush the request header. This left the body
5927 * for the Lua.
5928 */
5929
5930 /* Read the maximum amount of data avalaible. */
5931 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
5932 if (ret == -1)
5933 return;
5934
5935 /* No data available, ask for more data. */
5936 if (ret == 1)
5937 len2 = 0;
5938 if (ret == 0)
5939 len1 = 0;
5940 if (len1 + len2 < strm->txn->req.eoh + 2) {
5941 si_applet_cant_get(si);
5942 return;
5943 }
5944
5945 /* skip the requests bytes. */
5946 bo_skip(si_oc(si), strm->txn->req.eoh + 2);
5947 }
5948
5949 /* Executes The applet if it is not done. */
5950 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
5951
5952 /* Execute the function. */
5953 switch (hlua_ctx_resume(hlua, 1)) {
5954 /* finished. */
5955 case HLUA_E_OK:
5956 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
5957 break;
5958
5959 /* yield. */
5960 case HLUA_E_AGAIN:
5961 return;
5962
5963 /* finished with error. */
5964 case HLUA_E_ERRMSG:
5965 /* Display log. */
5966 SEND_ERR(px, "Lua applet http '%s': %s.\n",
5967 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
5968 lua_pop(hlua->T, 1);
5969 goto error;
5970
5971 case HLUA_E_ERR:
5972 /* Display log. */
5973 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
5974 rule->arg.hlua_rule->fcn.name);
5975 goto error;
5976
5977 default:
5978 goto error;
5979 }
5980 }
5981
5982 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
5983
5984 /* We must send the final chunk. */
5985 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
5986 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
5987
5988 /* sent last chunk at once. */
5989 ret = bi_putblk(res, "0\r\n\r\n", 5);
5990
5991 /* critical error. */
5992 if (ret == -2 || ret == -3) {
5993 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
5994 rule->arg.hlua_rule->fcn.name);
5995 goto error;
5996 }
5997
5998 /* no enough space error. */
5999 if (ret == -1) {
6000 si_applet_cant_put(si);
6001 return;
6002 }
6003
6004 /* set the last chunk sent. */
6005 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6006 }
6007
6008 /* close the connection. */
6009
6010 /* status / log */
6011 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6012 strm->logs.tv_request = now;
6013
6014 /* eat the whole request */
6015 bo_skip(si_oc(si), si_ob(si)->o);
6016 res->flags |= CF_READ_NULL;
6017 si_shutr(si);
6018
6019 return;
6020 }
6021
6022error:
6023
6024 /* If we are in HTTP mode, and we are not send any
6025 * data, return a 500 server error in best effort:
6026 * if there are no room avalaible in the buffer,
6027 * just close the connection.
6028 */
6029 bi_putblk(res, error_500, strlen(error_500));
6030 if (!(strm->flags & SF_ERR_MASK))
6031 strm->flags |= SF_ERR_RESOURCE;
6032 si_shutw(si);
6033 si_shutr(si);
6034 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6035}
6036
6037static void hlua_applet_http_release(struct appctx *ctx)
6038{
6039 task_free(ctx->ctx.hlua_apphttp.task);
6040 ctx->ctx.hlua_apphttp.task = NULL;
6041 hlua_ctx_destroy(&ctx->ctx.hlua_apphttp.hlua);
6042}
6043
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006044/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6045 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006046 *
6047 * This function can fail with an abort() due to an Lua critical error.
6048 * We are in the configuration parsing process of HAProxy, this abort() is
6049 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006050 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006051static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6052 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006053{
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006054 struct hlua_function *fcn = (struct hlua_function *)rule->kw->private;
6055
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006056 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006057 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006058 if (!rule->arg.hlua_rule) {
6059 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006060 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006061 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006062
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006063 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006064 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006065
6066 /* TODO: later accept arguments. */
6067 rule->arg.hlua_rule->args = NULL;
6068
Thierry FOURNIER42148732015-09-02 17:17:33 +02006069 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006070 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006071 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006072}
6073
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006074static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6075 struct act_rule *rule, char **err)
6076{
6077 struct hlua_function *fcn = (struct hlua_function *)rule->kw->private;
6078
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006079 /* HTTP applets are forbidden in tcp-request rules.
6080 * HTTP applet request requires everything initilized by
6081 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6082 * The applet will be immediately initilized, but its before
6083 * the call of this analyzer.
6084 */
6085 if (rule->from != ACT_F_HTTP_REQ) {
6086 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6087 return ACT_RET_PRS_ERR;
6088 }
6089
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006090 /* Memory for the rule. */
6091 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6092 if (!rule->arg.hlua_rule) {
6093 memprintf(err, "out of memory error");
6094 return ACT_RET_PRS_ERR;
6095 }
6096
6097 /* Reference the Lua function and store the reference. */
6098 rule->arg.hlua_rule->fcn = *fcn;
6099
6100 /* TODO: later accept arguments. */
6101 rule->arg.hlua_rule->args = NULL;
6102
6103 /* Add applet pointer in the rule. */
6104 rule->applet.obj_type = OBJ_TYPE_APPLET;
6105 rule->applet.name = fcn->name;
6106 rule->applet.init = hlua_applet_http_init;
6107 rule->applet.fct = hlua_applet_http_fct;
6108 rule->applet.release = hlua_applet_http_release;
6109 rule->applet.timeout = hlua_timeout_applet;
6110
6111 return ACT_RET_PRS_OK;
6112}
6113
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006114/* This function is an LUA binding used for registering
6115 * "sample-conv" functions. It expects a converter name used
6116 * in the haproxy configuration file, and an LUA function.
6117 */
6118__LJMP static int hlua_register_action(lua_State *L)
6119{
6120 struct action_kw_list *akl;
6121 const char *name;
6122 int ref;
6123 int len;
6124 struct hlua_function *fcn;
6125
Thierry FOURNIERed0bdaa2015-12-20 19:51:06 +01006126 MAY_LJMP(check_args(L, 3, "register_action"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006127
6128 /* First argument : converter name. */
6129 name = MAY_LJMP(luaL_checkstring(L, 1));
6130
6131 /* Second argument : environment. */
6132 if (lua_type(L, 2) != LUA_TTABLE)
6133 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6134
6135 /* Third argument : lua function. */
6136 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6137
6138 /* browse the second argulent as an array. */
6139 lua_pushnil(L);
6140 while (lua_next(L, 2) != 0) {
6141 if (lua_type(L, -1) != LUA_TSTRING)
6142 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6143
6144 /* Check required environment. Only accepted "http" or "tcp". */
6145 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006146 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006147 if (!akl)
6148 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006149 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006150 if (!fcn)
6151 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6152
6153 /* Fill fcn. */
6154 fcn->name = strdup(name);
6155 if (!fcn->name)
6156 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6157 fcn->function_ref = ref;
6158
6159 /* List head */
6160 akl->list.n = akl->list.p = NULL;
6161
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006162 /* action keyword. */
6163 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006164 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006165 if (!akl->kw[0].kw)
6166 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6167
6168 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6169
6170 akl->kw[0].match_pfx = 0;
6171 akl->kw[0].private = fcn;
6172 akl->kw[0].parse = action_register_lua;
6173
6174 /* select the action registering point. */
6175 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6176 tcp_req_cont_keywords_register(akl);
6177 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6178 tcp_res_cont_keywords_register(akl);
6179 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6180 http_req_keywords_register(akl);
6181 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6182 http_res_keywords_register(akl);
6183 else
6184 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
6185 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6186 "are expected.", lua_tostring(L, -1)));
6187
6188 /* pop the environment string. */
6189 lua_pop(L, 1);
6190 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006191 return ACT_RET_PRS_OK;
6192}
6193
6194static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6195 struct act_rule *rule, char **err)
6196{
6197 struct hlua_function *fcn = (struct hlua_function *)rule->kw->private;
6198
6199 /* Memory for the rule. */
6200 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6201 if (!rule->arg.hlua_rule) {
6202 memprintf(err, "out of memory error");
6203 return ACT_RET_PRS_ERR;
6204 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006205
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006206 /* Reference the Lua function and store the reference. */
6207 rule->arg.hlua_rule->fcn = *fcn;
6208
6209 /* TODO: later accept arguments. */
6210 rule->arg.hlua_rule->args = NULL;
6211
6212 /* Add applet pointer in the rule. */
6213 rule->applet.obj_type = OBJ_TYPE_APPLET;
6214 rule->applet.name = fcn->name;
6215 rule->applet.init = hlua_applet_tcp_init;
6216 rule->applet.fct = hlua_applet_tcp_fct;
6217 rule->applet.release = hlua_applet_tcp_release;
6218 rule->applet.timeout = hlua_timeout_applet;
6219
6220 return 0;
6221}
6222
6223/* This function is an LUA binding used for registering
6224 * "sample-conv" functions. It expects a converter name used
6225 * in the haproxy configuration file, and an LUA function.
6226 */
6227__LJMP static int hlua_register_service(lua_State *L)
6228{
6229 struct action_kw_list *akl;
6230 const char *name;
6231 const char *env;
6232 int ref;
6233 int len;
6234 struct hlua_function *fcn;
6235
6236 MAY_LJMP(check_args(L, 3, "register_service"));
6237
6238 /* First argument : converter name. */
6239 name = MAY_LJMP(luaL_checkstring(L, 1));
6240
6241 /* Second argument : environment. */
6242 env = MAY_LJMP(luaL_checkstring(L, 2));
6243
6244 /* Third argument : lua function. */
6245 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6246
6247 /* Check required environment. Only accepted "http" or "tcp". */
6248 /* Allocate and fill the sample fetch keyword struct. */
6249 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6250 if (!akl)
6251 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6252 fcn = calloc(1, sizeof(*fcn));
6253 if (!fcn)
6254 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6255
6256 /* Fill fcn. */
6257 len = strlen("<lua.>") + strlen(name) + 1;
6258 fcn->name = calloc(1, len);
6259 if (!fcn->name)
6260 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6261 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6262 fcn->function_ref = ref;
6263
6264 /* List head */
6265 akl->list.n = akl->list.p = NULL;
6266
6267 /* converter keyword. */
6268 len = strlen("lua.") + strlen(name) + 1;
6269 akl->kw[0].kw = calloc(1, len);
6270 if (!akl->kw[0].kw)
6271 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6272
6273 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6274
6275 if (strcmp(env, "tcp") == 0)
6276 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006277 else if (strcmp(env, "http") == 0)
6278 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006279 else
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006280 WILL_LJMP(luaL_error(L, "lua service environment '%s' is unknown. "
6281 "'tcp' or 'http' are expected."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006282
6283 akl->kw[0].match_pfx = 0;
6284 akl->kw[0].private = fcn;
6285
6286 /* End of array. */
6287 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6288
6289 /* Register this new converter */
6290 service_keywords_register(akl);
6291
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006292 return 0;
6293}
6294
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006295static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
6296 struct proxy *defpx, const char *file, int line,
6297 char **err, unsigned int *timeout)
6298{
6299 const char *error;
6300
6301 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
6302 if (error && *error != '\0') {
6303 memprintf(err, "%s: invalid timeout", args[0]);
6304 return -1;
6305 }
6306 return 0;
6307}
6308
6309static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
6310 struct proxy *defpx, const char *file, int line,
6311 char **err)
6312{
6313 return hlua_read_timeout(args, section_type, curpx, defpx,
6314 file, line, err, &hlua_timeout_session);
6315}
6316
6317static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
6318 struct proxy *defpx, const char *file, int line,
6319 char **err)
6320{
6321 return hlua_read_timeout(args, section_type, curpx, defpx,
6322 file, line, err, &hlua_timeout_task);
6323}
6324
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006325static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
6326 struct proxy *defpx, const char *file, int line,
6327 char **err)
6328{
6329 return hlua_read_timeout(args, section_type, curpx, defpx,
6330 file, line, err, &hlua_timeout_applet);
6331}
6332
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006333static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
6334 struct proxy *defpx, const char *file, int line,
6335 char **err)
6336{
6337 char *error;
6338
6339 hlua_nb_instruction = strtoll(args[1], &error, 10);
6340 if (*error != '\0') {
6341 memprintf(err, "%s: invalid number", args[0]);
6342 return -1;
6343 }
6344 return 0;
6345}
6346
Willy Tarreau32f61e22015-03-18 17:54:59 +01006347static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
6348 struct proxy *defpx, const char *file, int line,
6349 char **err)
6350{
6351 char *error;
6352
6353 if (*(args[1]) == 0) {
6354 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
6355 return -1;
6356 }
6357 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
6358 if (*error != '\0') {
6359 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
6360 return -1;
6361 }
6362 return 0;
6363}
6364
6365
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006366/* This function is called by the main configuration key "lua-load". It loads and
6367 * execute an lua file during the parsing of the HAProxy configuration file. It is
6368 * the main lua entry point.
6369 *
6370 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
6371 * occured, otherwise it returns 0.
6372 *
6373 * In some error case, LUA set an error message in top of the stack. This function
6374 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006375 *
6376 * This function can fail with an abort() due to an Lua critical error.
6377 * We are in the configuration parsing process of HAProxy, this abort() is
6378 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006379 */
6380static int hlua_load(char **args, int section_type, struct proxy *curpx,
6381 struct proxy *defpx, const char *file, int line,
6382 char **err)
6383{
6384 int error;
6385
6386 /* Just load and compile the file. */
6387 error = luaL_loadfile(gL.T, args[1]);
6388 if (error) {
6389 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
6390 lua_pop(gL.T, 1);
6391 return -1;
6392 }
6393
6394 /* If no syntax error where detected, execute the code. */
6395 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
6396 switch (error) {
6397 case LUA_OK:
6398 break;
6399 case LUA_ERRRUN:
6400 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
6401 lua_pop(gL.T, 1);
6402 return -1;
6403 case LUA_ERRMEM:
6404 memprintf(err, "lua out of memory error\n");
6405 return -1;
6406 case LUA_ERRERR:
6407 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
6408 lua_pop(gL.T, 1);
6409 return -1;
6410 case LUA_ERRGCMM:
6411 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
6412 lua_pop(gL.T, 1);
6413 return -1;
6414 default:
6415 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
6416 lua_pop(gL.T, 1);
6417 return -1;
6418 }
6419
6420 return 0;
6421}
6422
6423/* configuration keywords declaration */
6424static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006425 { CFG_GLOBAL, "lua-load", hlua_load },
6426 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
6427 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02006428 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006429 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01006430 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006431 { 0, NULL, NULL },
6432}};
6433
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006434/* This function can fail with an abort() due to an Lua critical error.
6435 * We are in the initialisation process of HAProxy, this abort() is
6436 * tolerated.
6437 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006438int hlua_post_init()
6439{
6440 struct hlua_init_function *init;
6441 const char *msg;
6442 enum hlua_exec ret;
6443
6444 list_for_each_entry(init, &hlua_init_functions, l) {
6445 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
6446 ret = hlua_ctx_resume(&gL, 0);
6447 switch (ret) {
6448 case HLUA_E_OK:
6449 lua_pop(gL.T, -1);
6450 return 1;
6451 case HLUA_E_AGAIN:
6452 Alert("lua init: yield not allowed.\n");
6453 return 0;
6454 case HLUA_E_ERRMSG:
6455 msg = lua_tostring(gL.T, -1);
6456 Alert("lua init: %s.\n", msg);
6457 return 0;
6458 case HLUA_E_ERR:
6459 default:
6460 Alert("lua init: unknown runtime error.\n");
6461 return 0;
6462 }
6463 }
6464 return 1;
6465}
6466
Willy Tarreau32f61e22015-03-18 17:54:59 +01006467/* The memory allocator used by the Lua stack. <ud> is a pointer to the
6468 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
6469 * is the previously allocated size or the kind of object in case of a new
6470 * allocation. <nsize> is the requested new size.
6471 */
6472static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
6473{
6474 struct hlua_mem_allocator *zone = ud;
6475
6476 if (nsize == 0) {
6477 /* it's a free */
6478 if (ptr)
6479 zone->allocated -= osize;
6480 free(ptr);
6481 return NULL;
6482 }
6483
6484 if (!ptr) {
6485 /* it's a new allocation */
6486 if (zone->limit && zone->allocated + nsize > zone->limit)
6487 return NULL;
6488
6489 ptr = malloc(nsize);
6490 if (ptr)
6491 zone->allocated += nsize;
6492 return ptr;
6493 }
6494
6495 /* it's a realloc */
6496 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
6497 return NULL;
6498
6499 ptr = realloc(ptr, nsize);
6500 if (ptr)
6501 zone->allocated += nsize - osize;
6502 return ptr;
6503}
6504
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006505/* Ithis function can fail with an abort() due to an Lua critical error.
6506 * We are in the initialisation process of HAProxy, this abort() is
6507 * tolerated.
6508 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01006509void hlua_init(void)
6510{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006511 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006512 int idx;
6513 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006514 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006515 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006516#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006517 struct srv_kw *kw;
6518 int tmp_error;
6519 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01006520 char *args[] = { /* SSL client configuration. */
6521 "ssl",
6522 "verify",
6523 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01006524 NULL
6525 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006526#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006527
Willy Tarreau87b09662015-04-03 00:22:06 +02006528 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01006529 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
6530
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006531 /* Register configuration keywords. */
6532 cfg_register_keywords(&cfg_kws);
6533
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006534 /* Init main lua stack. */
6535 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01006536 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01006537 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006538 gL.T = luaL_newstate();
6539 hlua_sethlua(&gL);
6540 gL.Tref = LUA_REFNIL;
6541 gL.task = NULL;
6542
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006543 /* From this point, until the end of the initialisation fucntion,
6544 * the Lua function can fail with an abort. We are in the initialisation
6545 * process of HAProxy, this abort() is tolerated.
6546 */
6547
Willy Tarreau32f61e22015-03-18 17:54:59 +01006548 /* change the memory allocators to track memory usage */
6549 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
6550
Thierry FOURNIER380d0932015-01-23 14:27:52 +01006551 /* Initialise lua. */
6552 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006553
Thierry Fournier75933d42016-01-21 09:30:18 +01006554 /* Set safe environment for the initialisation. */
6555 if (!SET_SAFE_LJMP(gL.T)) {
6556 fprintf(stderr, "Lua init: critical error.\n");
6557 exit(1);
6558 }
6559
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006560 /*
6561 *
6562 * Create "core" object.
6563 *
6564 */
6565
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01006566 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006567 lua_newtable(gL.T);
6568
6569 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006570 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006571 hlua_class_const_int(gL.T, log_levels[i], i);
6572
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006573 /* Register special functions. */
6574 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006575 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006576 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006577 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006578 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006579 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006580 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01006581 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006582 hlua_class_function(gL.T, "sleep", hlua_sleep);
6583 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01006584 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
6585 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
6586 hlua_class_function(gL.T, "set_map", hlua_set_map);
6587 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006588 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006589 hlua_class_function(gL.T, "log", hlua_log);
6590 hlua_class_function(gL.T, "Debug", hlua_log_debug);
6591 hlua_class_function(gL.T, "Info", hlua_log_info);
6592 hlua_class_function(gL.T, "Warning", hlua_log_warning);
6593 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02006594 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01006595 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006596
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01006597 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006598
6599 /*
6600 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006601 * Register class Map
6602 *
6603 */
6604
6605 /* This table entry is the object "Map" base. */
6606 lua_newtable(gL.T);
6607
6608 /* register pattern types. */
6609 for (i=0; i<PAT_MATCH_NUM; i++)
6610 hlua_class_const_int(gL.T, pat_match_names[i], i);
6611
6612 /* register constructor. */
6613 hlua_class_function(gL.T, "new", hlua_map_new);
6614
6615 /* Create and fill the metatable. */
6616 lua_newtable(gL.T);
6617
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006618 /* Create the __tostring identifier */
6619 lua_pushstring(gL.T, "__tostring");
6620 lua_pushstring(gL.T, CLASS_MAP);
6621 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6622 lua_rawset(gL.T, -3);
6623
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006624 /* Create and fille the __index entry. */
6625 lua_pushstring(gL.T, "__index");
6626 lua_newtable(gL.T);
6627
6628 /* Register . */
6629 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
6630 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
6631
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006632 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02006633
6634 /* Register previous table in the registry with reference and named entry. */
6635 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6636 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6637 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_MAP); /* register class session. */
6638 class_map_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6639
6640 /* Assign the metatable to the mai Map object. */
6641 lua_setmetatable(gL.T, -2);
6642
6643 /* Set a name to the table. */
6644 lua_setglobal(gL.T, "Map");
6645
6646 /*
6647 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006648 * Register class Channel
6649 *
6650 */
6651
6652 /* Create and fill the metatable. */
6653 lua_newtable(gL.T);
6654
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006655 /* Create the __tostring identifier */
6656 lua_pushstring(gL.T, "__tostring");
6657 lua_pushstring(gL.T, CLASS_CHANNEL);
6658 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6659 lua_rawset(gL.T, -3);
6660
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006661 /* Create and fille the __index entry. */
6662 lua_pushstring(gL.T, "__index");
6663 lua_newtable(gL.T);
6664
6665 /* Register . */
6666 hlua_class_function(gL.T, "get", hlua_channel_get);
6667 hlua_class_function(gL.T, "dup", hlua_channel_dup);
6668 hlua_class_function(gL.T, "getline", hlua_channel_getline);
6669 hlua_class_function(gL.T, "set", hlua_channel_set);
6670 hlua_class_function(gL.T, "append", hlua_channel_append);
6671 hlua_class_function(gL.T, "send", hlua_channel_send);
6672 hlua_class_function(gL.T, "forward", hlua_channel_forward);
6673 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
6674 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
6675
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006676 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01006677
6678 /* Register previous table in the registry with reference and named entry. */
6679 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6680 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
6681 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6682
6683 /*
6684 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006685 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006686 *
6687 */
6688
6689 /* Create and fill the metatable. */
6690 lua_newtable(gL.T);
6691
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006692 /* Create the __tostring identifier */
6693 lua_pushstring(gL.T, "__tostring");
6694 lua_pushstring(gL.T, CLASS_FETCHES);
6695 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6696 lua_rawset(gL.T, -3);
6697
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006698 /* Create and fille the __index entry. */
6699 lua_pushstring(gL.T, "__index");
6700 lua_newtable(gL.T);
6701
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006702 /* Browse existing fetches and create the associated
6703 * object method.
6704 */
6705 sf = NULL;
6706 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
6707
6708 /* Dont register the keywork if the arguments check function are
6709 * not safe during the runtime.
6710 */
6711 if ((sf->val_args != NULL) &&
6712 (sf->val_args != val_payload_lv) &&
6713 (sf->val_args != val_hdr))
6714 continue;
6715
6716 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
6717 * by an underscore.
6718 */
6719 strncpy(trash.str, sf->kw, trash.size);
6720 trash.str[trash.size - 1] = '\0';
6721 for (p = trash.str; *p; p++)
6722 if (*p == '.' || *p == '-' || *p == '+')
6723 *p = '_';
6724
6725 /* Register the function. */
6726 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01006727 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006728 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006729 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01006730 }
6731
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006732 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006733
6734 /* Register previous table in the registry with reference and named entry. */
6735 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6736 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
6737 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6738
6739 /*
6740 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006741 * Register class Converters
6742 *
6743 */
6744
6745 /* Create and fill the metatable. */
6746 lua_newtable(gL.T);
6747
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006748 /* Create the __tostring identifier */
6749 lua_pushstring(gL.T, "__tostring");
6750 lua_pushstring(gL.T, CLASS_CONVERTERS);
6751 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6752 lua_rawset(gL.T, -3);
6753
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006754 /* Create and fill the __index entry. */
6755 lua_pushstring(gL.T, "__index");
6756 lua_newtable(gL.T);
6757
6758 /* Browse existing converters and create the associated
6759 * object method.
6760 */
6761 sc = NULL;
6762 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
6763 /* Dont register the keywork if the arguments check function are
6764 * not safe during the runtime.
6765 */
6766 if (sc->val_args != NULL)
6767 continue;
6768
6769 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
6770 * by an underscore.
6771 */
6772 strncpy(trash.str, sc->kw, trash.size);
6773 trash.str[trash.size - 1] = '\0';
6774 for (p = trash.str; *p; p++)
6775 if (*p == '.' || *p == '-' || *p == '+')
6776 *p = '_';
6777
6778 /* Register the function. */
6779 lua_pushstring(gL.T, trash.str);
6780 lua_pushlightuserdata(gL.T, sc);
6781 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006782 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006783 }
6784
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006785 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01006786
6787 /* Register previous table in the registry with reference and named entry. */
6788 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6789 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
6790 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6791
6792 /*
6793 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006794 * Register class HTTP
6795 *
6796 */
6797
6798 /* Create and fill the metatable. */
6799 lua_newtable(gL.T);
6800
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006801 /* Create the __tostring identifier */
6802 lua_pushstring(gL.T, "__tostring");
6803 lua_pushstring(gL.T, CLASS_HTTP);
6804 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6805 lua_rawset(gL.T, -3);
6806
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006807 /* Create and fille the __index entry. */
6808 lua_pushstring(gL.T, "__index");
6809 lua_newtable(gL.T);
6810
6811 /* Register Lua functions. */
6812 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
6813 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
6814 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
6815 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
6816 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
6817 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
6818 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
6819 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
6820 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
6821 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
6822
6823 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
6824 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
6825 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
6826 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
6827 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
6828 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02006829 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006830
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006831 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01006832
6833 /* Register previous table in the registry with reference and named entry. */
6834 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6835 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_HTTP); /* register class session. */
6836 class_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6837
6838 /*
6839 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006840 * Register class AppletTCP
6841 *
6842 */
6843
6844 /* Create and fill the metatable. */
6845 lua_newtable(gL.T);
6846
6847 /* Create the __tostring identifier */
6848 lua_pushstring(gL.T, "__tostring");
6849 lua_pushstring(gL.T, CLASS_APPLET_TCP);
6850 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6851 lua_rawset(gL.T, -3);
6852
6853 /* Create and fille the __index entry. */
6854 lua_pushstring(gL.T, "__index");
6855 lua_newtable(gL.T);
6856
6857 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01006858 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
6859 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
6860 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
6861 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
6862 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006863
6864 lua_settable(gL.T, -3);
6865
6866 /* Register previous table in the registry with reference and named entry. */
6867 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6868 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_APPLET_TCP); /* register class session. */
6869 class_applet_tcp_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6870
6871 /*
6872 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006873 * Register class AppletHTTP
6874 *
6875 */
6876
6877 /* Create and fill the metatable. */
6878 lua_newtable(gL.T);
6879
6880 /* Create the __tostring identifier */
6881 lua_pushstring(gL.T, "__tostring");
6882 lua_pushstring(gL.T, CLASS_APPLET_HTTP);
6883 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6884 lua_rawset(gL.T, -3);
6885
6886 /* Create and fille the __index entry. */
6887 lua_pushstring(gL.T, "__index");
6888 lua_newtable(gL.T);
6889
6890 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01006891 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
6892 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006893 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
6894 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
6895 hlua_class_function(gL.T, "send", hlua_applet_http_send);
6896 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
6897 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
6898 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
6899
6900 lua_settable(gL.T, -3);
6901
6902 /* Register previous table in the registry with reference and named entry. */
6903 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6904 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_APPLET_HTTP); /* register class session. */
6905 class_applet_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
6906
6907 /*
6908 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006909 * Register class TXN
6910 *
6911 */
6912
6913 /* Create and fill the metatable. */
6914 lua_newtable(gL.T);
6915
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006916 /* Create the __tostring identifier */
6917 lua_pushstring(gL.T, "__tostring");
6918 lua_pushstring(gL.T, CLASS_TXN);
6919 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6920 lua_rawset(gL.T, -3);
6921
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01006922 /* Create and fille the __index entry. */
6923 lua_pushstring(gL.T, "__index");
6924 lua_newtable(gL.T);
6925
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006926 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01006927 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
6928 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02006929 hlua_class_function(gL.T, "set_var", hlua_set_var);
6930 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006931 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006932 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
6933 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
6934 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006935 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
6936 hlua_class_function(gL.T, "log", hlua_txn_log);
6937 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
6938 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
6939 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
6940 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01006941
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006942 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01006943
6944 /* Register previous table in the registry with reference and named entry. */
6945 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6946 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
6947 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006948
6949 /*
6950 *
6951 * Register class Socket
6952 *
6953 */
6954
6955 /* Create and fill the metatable. */
6956 lua_newtable(gL.T);
6957
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02006958 /* Create the __tostring identifier */
6959 lua_pushstring(gL.T, "__tostring");
6960 lua_pushstring(gL.T, CLASS_SOCKET);
6961 lua_pushcclosure(gL.T, hlua_dump_object, 1);
6962 lua_rawset(gL.T, -3);
6963
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006964 /* Create and fille the __index entry. */
6965 lua_pushstring(gL.T, "__index");
6966 lua_newtable(gL.T);
6967
Baptiste Assmann84bb4932015-03-02 21:40:06 +01006968#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006969 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01006970#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006971 hlua_class_function(gL.T, "connect", hlua_socket_connect);
6972 hlua_class_function(gL.T, "send", hlua_socket_send);
6973 hlua_class_function(gL.T, "receive", hlua_socket_receive);
6974 hlua_class_function(gL.T, "close", hlua_socket_close);
6975 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
6976 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
6977 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
6978 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
6979
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006980 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006981
6982 /* Register the garbage collector entry. */
6983 lua_pushstring(gL.T, "__gc");
6984 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02006985 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01006986
6987 /* Register previous table in the registry with reference and named entry. */
6988 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6989 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
6990 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
6991 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
6992
6993 /* Proxy and server configuration initialisation. */
6994 memset(&socket_proxy, 0, sizeof(socket_proxy));
6995 init_new_proxy(&socket_proxy);
6996 socket_proxy.parent = NULL;
6997 socket_proxy.last_change = now.tv_sec;
6998 socket_proxy.id = "LUA-SOCKET";
6999 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
7000 socket_proxy.maxconn = 0;
7001 socket_proxy.accept = NULL;
7002 socket_proxy.options2 |= PR_O2_INDEPSTR;
7003 socket_proxy.srv = NULL;
7004 socket_proxy.conn_retries = 0;
7005 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
7006
7007 /* Init TCP server: unchanged parameters */
7008 memset(&socket_tcp, 0, sizeof(socket_tcp));
7009 socket_tcp.next = NULL;
7010 socket_tcp.proxy = &socket_proxy;
7011 socket_tcp.obj_type = OBJ_TYPE_SERVER;
7012 LIST_INIT(&socket_tcp.actconns);
7013 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007014 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007015 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007016 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007017 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
7018 socket_tcp.last_change = 0;
7019 socket_tcp.id = "LUA-TCP-CONN";
7020 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7021 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7022 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
7023
7024 /* XXX: Copy default parameter from default server,
7025 * but the default server is not initialized.
7026 */
7027 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
7028 socket_tcp.minconn = socket_proxy.defsrv.minconn;
7029 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
7030 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
7031 socket_tcp.onerror = socket_proxy.defsrv.onerror;
7032 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7033 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
7034 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7035 socket_tcp.uweight = socket_proxy.defsrv.iweight;
7036 socket_tcp.iweight = socket_proxy.defsrv.iweight;
7037
7038 socket_tcp.check.status = HCHK_STATUS_INI;
7039 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
7040 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
7041 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
7042 socket_tcp.check.server = &socket_tcp;
7043
7044 socket_tcp.agent.status = HCHK_STATUS_INI;
7045 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
7046 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
7047 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
7048 socket_tcp.agent.server = &socket_tcp;
7049
7050 socket_tcp.xprt = &raw_sock;
7051
7052#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007053 /* Init TCP server: unchanged parameters */
7054 memset(&socket_ssl, 0, sizeof(socket_ssl));
7055 socket_ssl.next = NULL;
7056 socket_ssl.proxy = &socket_proxy;
7057 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7058 LIST_INIT(&socket_ssl.actconns);
7059 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007060 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007061 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007062 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007063 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
7064 socket_ssl.last_change = 0;
7065 socket_ssl.id = "LUA-SSL-CONN";
7066 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7067 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7068 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7069
7070 /* XXX: Copy default parameter from default server,
7071 * but the default server is not initialized.
7072 */
7073 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7074 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7075 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7076 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7077 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7078 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7079 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7080 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7081 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7082 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7083
7084 socket_ssl.check.status = HCHK_STATUS_INI;
7085 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7086 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7087 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7088 socket_ssl.check.server = &socket_ssl;
7089
7090 socket_ssl.agent.status = HCHK_STATUS_INI;
7091 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7092 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7093 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7094 socket_ssl.agent.server = &socket_ssl;
7095
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007096 socket_ssl.use_ssl = 1;
7097 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007098
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007099 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007100 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7101 /*
7102 *
7103 * If the keyword is not known, we can search in the registered
7104 * server keywords. This is usefull to configure special SSL
7105 * features like client certificates and ssl_verify.
7106 *
7107 */
7108 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7109 if (tmp_error != 0) {
7110 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7111 abort(); /* This must be never arrives because the command line
7112 not editable by the user. */
7113 }
7114 idx += kw->skip;
7115 }
7116 }
7117
7118 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007119 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007120#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01007121
7122 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007123}